Esempio n. 1
0
 def __init__(self,
         authorizationUrl: str,
         scopes: Dict[str, str]={},
         scheme_name: Optional[str]=None,
         auto_error: bool=True):
     flows = OAuthFlows(implicit={"authorizationUrl": authorizationUrl, 'scopes': scopes})
     super().__init__(flows=flows, scheme_name=scheme_name, auto_error=auto_error)
Esempio n. 2
0
 def __init__(self):
     # OpenAPI docs / Swagger auth
     self.scheme_name = 'ODP API Authorization'
     self.model = OAuth2(flows=OAuthFlows(clientCredentials=OAuthFlowClientCredentials(
         tokenUrl=f'{hydra_public_url}/oauth2/token',
         scopes={s.value: s.value for s in ODPScope},
     )))
def update_oauth2_scheme(authorization_url="", token_url=""):
    oauth2_scheme.model = OAuth2(
        flows=OAuthFlows(
            authorizationCode={
                "authorizationUrl": authorization_url,
                "tokenUrl": token_url,
                "refreshUrl": token_url,
            }
        )
    )
Esempio n. 4
0
 def __init__(
     self,
     tokenUrl: str,
     scheme_name: str = None,
     scopes: dict = None,
     auto_error: bool = True,
 ):
     if not scopes:
         scopes = {}
     flows = OAuthFlows(password={"tokenUrl": tokenUrl, "scopes": scopes})
     super().__init__(flows=flows,
                      scheme_name=scheme_name,
                      auto_error=auto_error)
    def __init__(self,
                 tokenUrl: str,
                 scheme_name: Optional[str] = None,
                 scopes: Dict = None,
                 auto_error: bool = True) -> None:

        if not scopes:
            scopes: Dict = {}

        flows = OAuthFlows(password={"tokenUrl": tokenUrl, "scopes": scopes})
        super().__init__(flows=flows,
                         scheme_name=scheme_name,
                         auto_error=auto_error)
Esempio n. 6
0
 def __init__(
     self,
     *args,
     tokenUrl: str,
     authorizationUrl: str,
     token_name: str = None,
     **kwargs,
 ):
     flows = OAuthFlows(authorizationCode={
         "tokenUrl": tokenUrl,
         "authorizationUrl": authorizationUrl,
     })
     super().__init__(flows=flows, *args, **kwargs)
     self._token_name = token_name or "token"
Esempio n. 7
0
 def __init__(
     self,
     client_id: str,
     authorizationUrl: str,
     tokenUrl: str,
     api_audience: str = None,
     scheme_name: str = None,
     scopes: dict = None,
     auto_error: bool = False,
     enabled: bool = True,
     use_pkce: bool = True,
     user_klass: type = User,
     flow_type: OAuthFlowType = OAuthFlowType.
     authorizationCode  # type: ignore
 ):
     """Initialise validator for token based authentication."""
     super().__init__(authorizationUrl=authorizationUrl,
                      tokenUrl=tokenUrl,
                      refreshUrl=api_audience,
                      scheme_name=scheme_name,
                      scopes=scopes,
                      auto_error=auto_error)
     self.client_id = client_id
     self.enabled = enabled
     if api_audience is None:
         api_audience = f"api://{client_id}"
     self.api_audience = api_audience
     self._use_pkce = use_pkce
     self._user_klass = user_klass
     if flow_type != OAuthFlowType.authorizationCode:  # type: ignore
         self.model.flows = OAuthFlows(
             **{
                 flow_type.value: {
                     'tokenUrl': tokenUrl,
                     'authorizationUrl': authorizationUrl,
                     'scopes': scopes
                 }
             })  # type: ignore
         self.logger.info(
             f'Using non default flow : {self.model.flows}')  # type: ignore
Esempio n. 8
0
    :param token_api_key_header API key provided by Authorization[api_key] header
    
    
    :type token_api_key_header: str
    :return: Information attached to provided api_key or None if api_key is invalid or does not allow access to called API
    :rtype: TokenModel | None
    """

    ...

oauth2_implicit = OAuth2(
    flows=OAuthFlows(
        implicit=OAuthFlowImplicit(
            authorizationUrl="http://petstore.swagger.io/api/oauth/dialog",
            scopes={
                "write:pets": "modify pets in your account",
                "read:pets": "read your pets",
            }
        )
    )
)


def get_token_petstore_auth(
    security_scopes: SecurityScopes, token: str = Depends(oauth2_implicit)
) -> TokenModel:
    """
    Validate and decode token.

    :param token Token provided by Authorization header
    :type token: str
Esempio n. 9
0
 def __init__(self):
     super(JWTScheme, self).__init__(
         auto_error=False,
         flows=OAuthFlows(password=OAuthFlowPassword(
             tokenUrl="/api/oauth2/ropcf")),
     )
 def __init__(self, scopes: List[str], client_id: str):
     self.scopes = scopes
     self.oauth2_scheme: OAuth2 = OAuth2(flows=OAuthFlows(
         implicit=OAuthFlowImplicit(authorizationUrl=url +
                                    f'?client_id={client_id}',
                                    scopes=self.scopes)))
Esempio n. 11
0
from fastapi.security import OAuth2
from google.auth import jwt
from google.auth.transport.requests import Request
from google.oauth2 import id_token
from pydantic import ValidationError
from starlette.status import HTTP_400_BAD_REQUEST, HTTP_403_FORBIDDEN

from excars import config, repositories
from excars.api.utils.redis import get_redis_cli
from excars.models.token import TokenPayload
from excars.models.user import User

oauth2 = OAuth2(  # pylint: disable=invalid-name
    flows=OAuthFlows(
        authorizationCode=OAuthFlowAuthorizationCode(
            authorizationUrl="https://accounts.google.com/o/oauth2/v2/auth?scope=openid+email+profile",
            tokenUrl="https://oauth2.googleapis.com/token",
        )
    )
)


async def get_current_user(token: str = Security(oauth2), redis_cli: Redis = Depends(get_redis_cli)) -> User:
    try:
        payload = verify_id_token(token.rpartition(" ")[-1])
    except ValueError as exc:
        raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail=str(exc)) from exc

    if payload["iss"] not in ["accounts.google.com", "https://accounts.google.com"]:
        raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Wrong issuer.")

    try:
Esempio n. 12
0
from fastapi import Depends
from fastapi.openapi.models import OAuthFlows, OAuthFlowAuthorizationCode
from fastapi.security import OAuth2

from app.config import settings
from app.helpers.oauth2 import Oauth2Client

oauth2_scheme = OAuth2(
    flows=OAuthFlows(
        authorizationCode=OAuthFlowAuthorizationCode(
            authorizationUrl=settings.AUTHORIZATION_URL,
            tokenUrl=settings.AUTHORIZATION_TOKEN_URL,
            scopes={
                'openid': 'OpenID',
                'email': 'Email',
                'profile': 'Profile',
                'groups': 'Groups',
                'offline_access': 'Offline Access',
            }
        ),
    )
)


def get_current_user(access_token: str = Depends(oauth2_scheme)):
    """
    Return the current user profile
    :return: current user
    """
    oauth2 = Oauth2Client()
    user = oauth2.user_profile(access_token)