def auth_handler(self, auth_request): token = auth_request.token try: claims = self._decoder.decode(token) return AuthResponse( self._route_selector.get_allowed_routes(claims), principal_id=self._principal_selector.get_principal(claims), ) except InvalidToken: return AuthResponse(routes=[], principal_id=None)
def basic_auth(auth_request): username, password = decode(auth_request.token) if username == password: context = {'is_admin': True} # return AuthResponse(routes=['/*'], principal_id=username) return AuthResponse(routes=[AuthRoute('/*', ["GET", "POST"])], principal_id=username, context=context) return AuthResponse(routes=[], principal_id=None)
def demo_auth(auth_request): """This is just the demo apps authentication check, nothing special.""" auth_api = BluemoonAuthorization() token = auth_request.token if token.startswith("Bearer "): token = token.split("Bearer ")[1] authorized = auth_api.check_authorization(token) if authorized: return AuthResponse(routes=["*"], principal_id=authorized.id) else: return AuthResponse(routes=[], principal_id=None)
def basic_auth(auth_request): username, password = decode(auth_request.token) if username == password: context = {"is_admin": True} return AuthResponse( routes=[AuthRoute("/*", ["GET", "POST"])], principal_id=username, context=context, ) else: return AuthResponse(routes=[], principal_id=None)
def token_auth(self, event): auth_type = 'TOKEN' api_key = None method_arn = '' principal_id = 'user' api_gateway_arn_tmp = '' if 'type' in event: auth_type = event['type'] if 'methodArn' in event: method_arn = event['methodArn'] tmp = event['methodArn'].split(':') api_gateway_arn_tmp = tmp[5].split('/') if 'authorizationToken' in event: api_key = event['authorizationToken'] get_logger().info("Event: {}".format(event)) auth_request = AuthRequest(auth_type=auth_type, token=api_key, method_arn=method_arn) is_api_key_valid = self.validate_api_key(api_key) access_allowed = is_api_key_valid if access_allowed: verb = api_gateway_arn_tmp[2] if len( api_gateway_arn_tmp) > 2 else '*' resource = api_gateway_arn_tmp[3] if len( api_gateway_arn_tmp) > 3 else '*' auth_response = AuthResponse( routes=[AuthRoute("/" + resource, [verb])], principal_id=principal_id) else: auth_response = AuthResponse(routes=[], principal_id=principal_id) auth_response_dict = auth_response.to_dict(auth_request) # deny resources if not access_allowed: self.deny_resources(auth_response_dict) # new! -- add additional key-value pairs associated with the authenticated principal # these are made available by APIGW like so: $context.authorizer.<key> # additional context is cached auth_response_dict['context'] = { 'key': api_key # $context.authorizer.key -> value } return auth_response_dict
def jwt_auth(auth_request): """ JWT based authorizer :param auth_request: :return: AuthResponse """ token = auth_request.token try: decoded = cognito.token_decoder(token) return AuthResponse(routes=['*'], principal_id=decoded['sub']) except Exception as e: app.log.error(e) return AuthResponse(routes=[''], principal_id='')
def custom_auth(auth_request): token = auth_request.token # This is just for demo purposes as shown in the API Gateway docs. # Normally you'd call an oauth provider, validate the jwt token, etc. # In this exampe, the token is treated as the status for demo purposes. if token == 'allow': return AuthResponse(routes=['/'], principal_id='user') else: # By specifying an empty list of routes, # we're saying this user is not authorized # for any URLs, which will result in an # Unauthorized response. return AuthResponse(routes=[], principal_id='user')
def god_auth(auth_request): token = auth_request.token print(auth_request.method_arn) decoded = token_helper.retrieve_verified_token_claims( keys, token, os.environ['APPCLIENTID']) if isinstance(decoded, dict) and decoded['custom:app_role'] == 'godmode': return AuthResponse(routes=['*'], principal_id=decoded['sub'], context={"email": decoded['email']}) # Default to cleaner option not allowing access. # but this code is executed as result of token_helper issues which # should be handled - Timed out tokens, invalid tokens. Future defect... return AuthResponse(routes=[], principal_id='none')
def auth(auth_request): token = auth_request.token app.log.debug(token) data, authenticated = authenticate(token) if not authenticated: # By specifying an empty list of routes, # we're saying this user is not authorized # for any URLs, which will result in an # Unauthorized response. app.log.error(data["error"]) return AuthResponse(routes=[], principal_id="user") user_id = data["sub"] app.log.info(f"Authenticated User: {user_id}") response = AuthResponse(routes=["*"], principal_id=user_id) return response
def jwt_auth(auth_request): """ handles authentication using jwt token :param auth_request: :return: aws policy statement """ print("request info", auth_request.token) token = auth_request.token log.info("decoding auth token") try: decoded = decode_jwt_token(token) if not decoded: print("returning error as unauthorized") return Response(body={"message": "unable to decode token"}, status_code=401) log.info(f'decoded the token {decoded}') return AuthResponse(routes=["*"], principal_id=decoded["email"], context={ "sessionId": decoded["sessionId"], "email": decoded["email"], "role": decoded["role"], "userId": decoded["userId"], "firstName": decoded["firstName"], "lastName": decoded["lastName"], "token": decoded["token"], }) except Exception as e: return {"message": f"unable to decode token.{e.args[0]}"}
def iamAuthorizer(auth_request): """ {'sub': 'f31c1cb8-681c-4d3e-9749-d7c074ffd7f6', 'email_verified': True, 'iss': 'https://cognito-idp.us-east-1.amazonaws.com/us-east-1_kcpcLxLzn', 'cognito:username': '******', 'aud': '77mcm1k9ll2ge68806h5kncfus', 'event_id': '1dc969c8-861e-11e8-b29e-336c6c2ce302', 'token_use': 'id', 'custom:center': 'CCMT', 'auth_time': 1531432454, 'name': 'Ashwin Ramaswami', 'exp': 1532273519, 'iat': 1532269919, 'email': '*****@*****.**'} """ claims = get_claims(auth_request.token) if not claims and not app.test_user_id: claims = { "sub": "cm:cognitoUserPool:anonymousUser", "name": "Anonymous", "email": "*****@*****.**", } else: if claims: claims["sub"] = "cm:cognitoUserPool:" + claims["sub"] id = claims["sub"] elif app.test_user_id: claims = {"sub": app.test_user_id} id = app.test_user_id # try: # user = User.objects.get({"_id": id}) # except DoesNotExist: # print(f"User does not exist. Creating user {id}") # user = User(id=id) # user.save() return AuthResponse(routes=["*"], principal_id="user", context={"id": claims["sub"]})
def jwt_auth(auth_request): token = auth_request.token jsonurl = urlopen("https://" + AUTH0_DOMAIN + "/.well-known/jwks.json") jwks = json.loads(jsonurl.read()) unverified_header = jwt.get_unverified_header(token) rsa_key = {} for key in jwks["keys"]: if key["kid"] == unverified_header["kid"]: rsa_key = { "kty": key["kty"], "kid": key["kid"], "use": key["use"], "n": key["n"], "e": key["e"] } if rsa_key: try: payload = jwt.decode(token, rsa_key, algorithms=ALGORITHMS, audience=API_AUDIENCE, issuer="https://" + AUTH0_DOMAIN + "/") except jwt.ExpiredSignatureError: print('tits1') return AuthResponse(routes=[], principal_id='user') # raise AuthError({"code": "token_expired", # "description": "token is expired"}, 401) except jwt.JWTClaimsError: print('tits2') return AuthResponse(routes=[], principal_id='user') # raise AuthError({"code": "invalid_claims", # "description": # "incorrect claims," # "please check the audience and issuer"}, 401) except Exception: print('tits3') return AuthResponse(routes=[], principal_id='user') # raise AuthError({"code": "invalid_header", # "description": # "Unable to parse authentication" # " token."}, 401) return AuthResponse(routes=['/'], principal_id='user', context={'decodedJwt': payload})
def dummy_auth(auth_request): if auth_request.token == 'yes': return AuthResponse(routes=[ '/builtin-auth', AuthRoute('/fake-profile', methods=['POST']) ], context={'foo': 'bar'}, principal_id='foo') else: raise UnauthorizedError('Authorization failed')
def proxy(auth_activation): subsegment = xray_recorder.current_subsegment() try: auth = auth_method(auth_activation) if subsegment: subsegment.put_metadata('result', auth) except Exception as e: self.current_app.log.info(f"Exception : {str(e)}") traceback.print_exc() if subsegment: subsegment.add_exception(e, traceback.extract_stack()) return AuthResponse(routes=[], principal_id='user') if type(auth) is bool: if auth: return AuthResponse(routes=['*'], principal_id='user') return AuthResponse(routes=[], principal_id='user') elif type(auth) is list: return AuthResponse(routes=auth, principal_id='user') return auth
def _token_handler(self, event, context): """Authorization handler.""" self.log.debug(f"Calling {self.name} for authorization : {event}") try: *_, method, route = event.get('methodArn').split('/', 3) authorizer = self._entry(f'/{route}', method).auth return authorizer(event, context) except Exception as e: self.log.debug(f"Error in authorization handler for {self.name} : {e}") request = AuthRequest(event['type'], event['authorizationToken'], event['methodArn']) return AuthResponse(routes=[], principal_id='user').to_dict(request)
def authorizer(auth_request): response = {} token = auth_request.token print('token = ', token) principal_id = 'user' auth_success = False if token: token = token.replace('Bearer ', '') decoded = jwt.decode(token, os.getenv( 'JWT_SECRET'), algorithms=["HS256"]) print('decoded = ', decoded) if decoded: principal_id = decoded['id'] auth_success = True if auth_success: response = AuthResponse(routes=['*'], principal_id=principal_id) else: response = AuthResponse(routes=[], principal_id=principal_id) return response
def demo_auth(auth_request): if token == 'allow': return AuthResponse(routes=['/'], principal_id='user') else: return AuthResponse(routes=[''], principal_id='user')
def authorizer(auth_request): token = auth_request.token return AuthResponse(routes=['*'], principal_id=token)
def jwt_auth(auth_request): token = auth_request.token[7:] decoded = jwt.decode(token, env.get('secret'), algorithms=['HS256']) return AuthResponse(routes=['*'], principal_id=decoded['sub'])
def myauth(event): if event.token == 'allow': return AuthResponse(['*'], principal_id='id')
def jwt_auth(auth_request): token = auth_request.token print(token) decoded = UserAuthUtility.decode_jwt_token(token) return AuthResponse(routes=['*'], principal_id=decoded['sub'])
def jwt_auth(auth_request): token = auth_request.token decoded = auth.decode_jwt_token(token) return AuthResponse(routes=['*'], principal_id=decoded['sub'])
def authorizer(auth_request): token = auth_request.token decoded = decode_jwt_token(token, JWT_SECRET) # Here login_info = email + "|" + role return AuthResponse(routes=['*'], principal_id=decoded['sub'])