Exemplo n.º 1
0
 def test_validate_token_fail(self, mockjwk, _):
     mockjwk.construct.return_value = jwk.construct(
         self.pub_pem, algorithm=jwk.ALGORITHMS.RS256)
     access_token = jwt.encode({
         'iss': 'iss',
         'aud': 'aud',
         'cid': 'cid'
     }, self.priv_pem, jwt.ALGORITHMS.RS256)
     access_token = '=' + access_token
     with self.assertRaises(Exception) as ctx:
         validate_token(access_token, 'iss', 'aud', 'cid')
     self.assertEqual('Invalid Token', str(ctx.exception))
Exemplo n.º 2
0
def check_token(request):
    access_token = request.META.get('HTTP_AUTHORIZATION')

    if access_token is None:
        return False, JsonResponse({"result": "HTTP_AUTHORIZATION required"},
                                   status=400)

    try:
        validate_token(access_token, config.issuer, config.aud,
                       config.client_id)
        return True, None

    except Exception as e:
        return False, JsonResponse({"result": e.args[0]}, status=400)
Exemplo n.º 3
0
 def test_validate_token(self, header, claims, error_t, cids, mockjwk, _):
     mockjwk.construct.return_value = jwk.construct(
         self.pub_pem, algorithm=jwk.ALGORITHMS.RS256)
     access_token = jwt.encode(claims, self.priv_pem, jwt.ALGORITHMS.RS256,
                               header)
     if error_t:
         with self.assertRaises(error_t) as ctx:
             validate_token(access_token, claims['iss'], claims['aud'],
                            cids)
         self.assertEqual(error_t, type(ctx.exception))
     else:
         res = validate_token(access_token, claims['iss'], claims['aud'],
                              cids)
         self.assertEqual(res, claims)
def current_user(request: Request,
                 token: str = Depends(get_token),
                 db: Session = Depends(get_db)):
    try:
        email = validate_token(token, issuer, audience, client_id)["sub"]
        request.state.user = get_or_create_user_by_email(db, email)
    except Exception as e:
        raise HTTPException(403, str(e))
Exemplo n.º 5
0
async def authenticate_user_by_alb_auth(request):
    aws_alb_auth_header_name = config.get(
        "get_user_by_aws_alb_auth_settings.aws_alb_auth_header_name", "X-Amzn-Oidc-Data"
    )
    aws_alb_claims_header_name = config.get(
        "get_user_by_aws_alb_auth_settings.aws_alb_claims_header_name",
        "X-Amzn-Oidc-Accesstoken",
    )
    encoded_auth_jwt = request.request.headers.get(aws_alb_auth_header_name)
    encoded_claims_jwt = request.request.headers.get(aws_alb_claims_header_name)
    if not encoded_auth_jwt:
        raise Exception(f"Missing header: {aws_alb_auth_header_name}")
    if not encoded_claims_jwt:
        raise Exception(f"Missing header: {aws_alb_claims_header_name}")

    jwt_headers = encoded_auth_jwt.split(".")[0]
    decoded_jwt_headers = base64.b64decode(jwt_headers)
    decoded_jwt_headers = decoded_jwt_headers.decode("utf-8")
    decoded_json = json.loads(decoded_jwt_headers)
    kid = decoded_json["kid"]
    # Step 2: Get the public key from regional endpoint
    url = "https://public-keys.auth.elb." + config.region + ".amazonaws.com/" + kid
    req = requests.get(url)
    pub_key = req.text
    # Step 3: Get the payload
    payload = jwt.decode(encoded_auth_jwt, pub_key, algorithms=["ES256"])
    email = payload.get(
        config.get("get_user_by_aws_alb_auth_settings.jwt_email_key", "email")
    )

    # Step 4: Parse the Access Token
    # User has already passed ALB auth and successfully authenticated
    access_token_jwt = jwt.decode(encoded_claims_jwt, pub_key, verify=False)
    groups = access_token_jwt.get(
        config.get("get_user_by_aws_alb_auth_settings.jwt_groups_key", "groups")
    )
    # Step 5: Verify the access token.
    validate_token(
        encoded_claims_jwt,
        access_token_jwt["iss"],
        access_token_jwt["aud"],
        access_token_jwt["cid"],
    )
    return {"user": email, "groups": groups}
Exemplo n.º 6
0
    def okta_authentication(token):

        dataResponse = {}
        try:
            issuer = "https://dev-612233.oktapreview.com/oauth2/default"
            client_ids = ["0oajynre6wdHJZ2I20h7"]
            audience = "api://default"
            dataResponse = validate_token(token, issuer, audience, client_ids)
        except Exception as e:
            traceback.print_exc()
            print("error")
        return dataResponse
 def post(self):
     email = self.get_argument("email")
     password = self.get_argument("password")
     self.set_header("Access-Control-Allow-Origin", "*")
     base_uri = self.get_argument("base_uri")
     client_id = self.get_argument("client_id")
     token = self.get_argument("token")
     try:
         response = validate_token(token, os.environ['OKTA_ISSUER_URI'],
                                   'api://default', client_id)
         print(response)
         self.write("Welcome {}\n".format(email))
     except:
         self.send_error(403)
Exemplo n.º 8
0
    def authenticate(self, request):
        access_token = request.META.get('HTTP_AUTHORIZATION')
        if not access_token:
            return None
        # access_token = generate_token(config.issuer, config.client_id, config.client_secret, "*****@*****.**",
        #                               "Advisor2020")
        # print(access_token)
        payload = validate_token(access_token, config.issuer, config.aud,
                                 config.client_id)

        try:
            user = get_user_model().objects.get(email=payload['sub'])

        except User.DoesNotExist:
            raise exceptions.AuthenticationFailed('No such user')

        return user, None
Exemplo n.º 9
0
    def wrap(*args, **kwargs):
        auth_header = request.headers.get("authorization", None)
        if not auth_header:
            return json.dumps({'error':
                               'no authorization token provided'}), 403, {
                                   'Content-type': 'application/json'
                               }

        # noinspection PyBroadException
        try:
            token = auth_header.split(' ')[1]
            resp = validate_token(token, ISSUER, AUDIENCE, CLIENT_ID)
            user = resp['sub']

        except Exception as e:
            print(e)
            return json.dumps({'error': 'invalid authorization token'}), 403, {
                'Content-type': 'application/json'
            }

        return f(user, *args, **kwargs)
Exemplo n.º 10
0
async def authenticate_user_by_alb_auth(request):
    aws_alb_auth_header_name = config.get(
        "get_user_by_aws_alb_auth_settings.aws_alb_auth_header_name",
        "X-Amzn-Oidc-Data")
    aws_alb_claims_header_name = config.get(
        "get_user_by_aws_alb_auth_settings.aws_alb_claims_header_name",
        "X-Amzn-Oidc-Accesstoken",
    )
    function = f"{__name__}.{sys._getframe().f_code.co_name}"
    log_data = {"function": function}
    encoded_auth_jwt = request.request.headers.get(aws_alb_auth_header_name)
    encoded_claims_jwt = request.request.headers.get(
        aws_alb_claims_header_name)
    if not encoded_auth_jwt:
        raise Exception(f"Missing header: {aws_alb_auth_header_name}")
    if not encoded_claims_jwt:
        raise Exception(f"Missing header: {aws_alb_claims_header_name}")

    jwt_headers = encoded_auth_jwt.split(".")[0]
    decoded_jwt_headers = base64.b64decode(jwt_headers)
    decoded_jwt_headers = decoded_jwt_headers.decode("utf-8")
    decoded_json = json.loads(decoded_jwt_headers)
    kid = decoded_json["kid"]
    # Step 2: Get the public key from regional endpoint
    url = "https://public-keys.auth.elb." + config.region + ".amazonaws.com/" + kid
    req = requests.get(url)
    pub_key = req.text
    # Step 3: Get the payload
    payload = jwt.decode(encoded_auth_jwt, pub_key, algorithms=["ES256"])
    email = payload.get(
        config.get("get_user_by_aws_alb_auth_settings.jwt_email_key", "email"))

    if not email:
        raise UnableToAuthenticate("Unable to determine user from ID Token")

    # Step 4: Parse the Access Token
    # User has already passed ALB auth and successfully authenticated
    try:
        access_token_jwt = jwt.decode(encoded_claims_jwt,
                                      pub_key,
                                      verify=False)
        groups = access_token_jwt.get(
            config.get("get_user_by_aws_alb_auth_settings.jwt_groups_key",
                       "groups"))
        # Step 5: Verify the access token.
        validate_token(
            encoded_claims_jwt,
            access_token_jwt["iss"],
            access_token_jwt["aud"],
            access_token_jwt["cid"],
        )
    except jwt.exceptions.DecodeError as e:
        # This exception occurs when the access token is not JWT-parsable. It is expected with some IdPs.
        log.debug({
            **log_data,
            "message":
            ("Unable to derive user's groups from access_token. This is expected for some identity providers."
             ),
            "error":
            e,
            "user":
            email,
        })
        log.debug(log_data, exc_info=True)
        groups = []
    except ExpiredSignatureError as e:
        # This exception occurs when the access token has expired. Delete cookies associated with ALB Auth
        # (AWSELBAuthSessionCookie-0)
        log.debug({
            **log_data,
            "message": ("Access token has expired"),
            "error": e,
            "user": email,
        })
        log.debug(log_data, exc_info=True)
        request.request.clear_cookie("AWSELBAuthSessionCookie-0")
        request.redirect(request.request.uri)

    return {"user": email, "groups": groups}