How to use the fastapi.Security function in fastapi

To help you get started, we’ve selected a few fastapi examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github tiangolo / fastapi / tests / test_security_http_base.py View on Github external
def read_current_user(credentials: HTTPAuthorizationCredentials = Security(security)):
    return {"scheme": credentials.scheme, "credentials": credentials.credentials}
github tiangolo / fastapi / tests / test_security_api_key_query.py View on Github external
def get_current_user(oauth_header: str = Security(api_key)):
    user = User(username=oauth_header)
    return user
github tiangolo / fastapi / tests / test_security_http_digest_optional.py View on Github external
def read_current_user(
    credentials: Optional[HTTPAuthorizationCredentials] = Security(security),
):
    if credentials is None:
        return {"msg": "Create an account first"}
    return {"scheme": credentials.scheme, "credentials": credentials.credentials}
github tiangolo / fastapi / tests / test_security_http_bearer_optional.py View on Github external
def read_current_user(
    credentials: Optional[HTTPAuthorizationCredentials] = Security(security),
):
    if credentials is None:
        return {"msg": "Create an account first"}
    return {"scheme": credentials.scheme, "credentials": credentials.credentials}
github tiangolo / fastapi / tests / test_security_openid_connect.py View on Github external
def get_current_user(oauth_header: str = Security(oid)):
    user = User(username=oauth_header)
    return user
github tiangolo / fastapi / tests / test_security_api_key_header_optional.py View on Github external
def get_current_user(oauth_header: Optional[str] = Security(api_key)):
    if oauth_header is None:
        return None
    user = User(username=oauth_header)
    return user
github nsidnev / fastapi-realworld-example-app / app / api / dependencies / authentication.py View on Github external
def _get_authorization_header_optional(
    authorization: Optional[str] = Security(RWAPIKeyHeader(auto_error=False)),
) -> str:
    if authorization:
        return _get_authorization_header(authorization)

    return ""
github tiangolo / fastapi / docs / src / security / tutorial005.py View on Github external
async def get_current_active_user(
    current_user: User = Security(get_current_user, scopes=["me"])
):
    if current_user.disabled:
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user
github 3lpsy / boucanpy / boucanpy / core / security.py View on Github external
async def __call__(
        self,
        request: Request,
        bl_token_repo: BlackListedTokenRepo = Depends(BlackListedTokenRepo()),
        token: str = Security(oauth2),
    ) -> TokenPayload:

        token = verify_jwt_token(
            token, bl_token_repo, self._leeway
        )  # proper validation goes here
        if self._satisfy not in ["all", "one"]:
            logger.warning(f"Invalid satisfy value: {self._satisfy}")

        if self._satisfy == "one":
            if not token_has_one_required_scopes(token, self._scopes):
                vmsg = f"Token does not have one of the required scopes: {str(self._scopes)}"
                logger.error(vmsg)
                abort(code=403, msg="Forbidden", debug=vmsg)
        else:
            if not token_has_required_scopes(token, self._scopes):
                vmsg = f"Token does not have all required scopes: {str(self._scopes)}"
github tiangolo / full-stack-fastapi-postgresql / {{cookiecutter.project_slug}} / backend / app / app / api / utils / security.py View on Github external
def get_current_user(
    db: Session = Depends(get_db), token: str = Security(reusable_oauth2)
):
    try:
        payload = jwt.decode(token, config.SECRET_KEY, algorithms=[ALGORITHM])
        token_data = TokenPayload(**payload)
    except PyJWTError:
        raise HTTPException(
            status_code=HTTP_403_FORBIDDEN, detail="Could not validate credentials"
        )
    user = crud.user.get(db, user_id=token_data.user_id)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user