예제 #1
0
def authorizer(auth_request) -> AuthResponse:
    """Authorizes the bearer token sent up in an authenticated request.

    Args:
        auth_request - The request sent to the chalice application.

    Returns:
        An auth response containing allowed routes and a principal id.
    """
    if auth_request.token:
        with db.session_scope() as db_session:
            db.SESSION = db_session
            json_web_token = auth_request.token.split('Bearer')[1].strip()
            session = get_session_by_token(token=json_web_token)

            if session:
                decoded_payload = authenticate_user(
                    email=session.get('user', {}).get('email'),
                    password=session.get('user', {}).get('password'),
                    json_web_token=json_web_token,
                )

                if decoded_payload:
                    return AuthResponse(
                        context={'user_id': session.get('user', {}).get('id')},
                        routes=['*'],
                        principal_id=decoded_payload.get('sub'),
                    )

    return AuthResponse(routes=[], principal_id='user')
예제 #2
0
def demo_auth(auth_request):
    token=auth_request.token

    if token=="allow":
        return AuthResponse(routes=['/'], principal_id='user')
    else:
        return AuthResponse(routes=[], principal_id='user')
예제 #3
0
def auth(auth_request):
    token = auth_request.token
    if token == password:
        return AuthResponse(routes=['/getTxData', '/addresses'],
                            principal_id='user')
    else:
        return AuthResponse(routes=[], principal_id='user')
예제 #4
0
def jwt_auth(auth_request):
    token = auth_request.token
    decoded = None
    try:
        decoded = auth.decode_jwt_token(token)
    except jwt.exceptions.InvalidSignatureError as e:
        return AuthResponse(routes=[''], principal_id=None)
    return AuthResponse(routes=['*'], principal_id=decoded['sub'])
예제 #5
0
def basic_auth(auth_request):
    username, password = decode(auth_request.token)

    if username == password:
        context = {'stripe_user_id': '1234', 'is_admin': True}
        return AuthResponse(routes=['/*'],
                            principal_id=username,
                            context=context)
    return AuthResponse(routes=[], principal_id=None)
예제 #6
0
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)
    return AuthResponse(routes=[], principal_id=None)
예제 #7
0
def basic_auth_insecure(auth_request):
    token = auth_request.token
    if token == 'Basic YWRtaW46YWxsb3c=':  # "admin:allow"
        # A principal id may be a username, email address, or userid
        # routes=['*'] would allow any route
        return AuthResponse(routes=['/auth'], principal_id='user')
    else:
        # routes=[] would mean there are no valid routes for them
        return AuthResponse(routes=[], principal_id='invalid')
예제 #8
0
def token_auth(auth_request):
    if auth_request.auth_type == "TOKEN" and auth_request.token == sm_client.get_secret(
            CONFIG["secret_id"], CONFIG["secret_key"],
            CONFIG["secret_region"]):
        logger.info({"AuthType": auth_request.auth_type, "Success": True})
        return AuthResponse(routes=["/*"], principal_id="user")
    else:
        logger.info({"AuthType": auth_request.auth_type, "Success": False})
        return AuthResponse(routes=[], principal_id="user")
예제 #9
0
def jwt_auth(auth_request):
    token = auth_request.token
    decoded = auth.decode_jwt_token(token)
    app.log.debug(decoded)
    if decoded is not None:
        return AuthResponse(routes=['*'],
                            principal_id=(decoded['email'], decoded['name']))
    else:
        return AuthResponse(routes=[], principal_id='')
예제 #10
0
    def request_auth(self, event):
        auth_type = None
        method_arn = None
        token = None
        api_key = None
        api_gateway_arn_tmp = ''
        principal_id = 'user'

        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 self.API_KEY in event['headers']:
            api_key = event['headers'][self.API_KEY]

        if self.TOKEN_KEY in event['headers']:
            token = event['headers'][self.TOKEN_KEY]
            token = token.replace('bearer ', '')

        auth_request = AuthRequest(auth_type=auth_type,
                                   token=api_key,
                                   method_arn=method_arn)

        is_token_valid = self.validate_token(token)
        is_api_key_valid = self.validate_api_key(api_key)

        access_allowed = is_token_valid and 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
예제 #11
0
def api_key_auth(auth_request):
    """
    Custom auth function.
    The client need to provide the header Authorization with value of api_key.
    """

    if auth_request.token == api_key:
        return AuthResponse(routes=["/*"], principal_id="user")

    return AuthResponse(routes=[], principal_id="user")
 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)
예제 #13
0
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)
예제 #14
0
    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
예제 #15
0
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='')
예제 #16
0
파일: app.py 프로젝트: samhays/aws-data-api
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')
예제 #17
0
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')
예제 #18
0
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]}"}
예제 #19
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"]})
예제 #20
0
파일: app.py 프로젝트: ylathouris/hello
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
예제 #21
0
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})
예제 #22
0
파일: app.py 프로젝트: yangmiok/chalice
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')
예제 #23
0
        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
예제 #24
0
파일: coworks.py 프로젝트: gdoumenc/coworks
    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)
예제 #25
0
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
예제 #26
0
def jwt_auth(auth_request):
    token = auth_request.token
    decoded = auth.decode_jwt_token(token)
    return AuthResponse(routes=['*'], principal_id=decoded['sub'])
예제 #27
0
파일: app.py 프로젝트: jastr945/chalice_aws
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'])
예제 #28
0
 def myauth(event):
     if event.token == 'allow':
         return AuthResponse(['*'], principal_id='id')
예제 #29
0
def jwt_auth(auth_request):
    token = auth_request.token
    print(token)
    decoded = UserAuthUtility.decode_jwt_token(token)
    return AuthResponse(routes=['*'], principal_id=decoded['sub'])
예제 #30
0
def demo_auth(auth_request):
    if token == 'allow':
        return AuthResponse(routes=['/'], principal_id='user')
    else:
        return AuthResponse(routes=[''], principal_id='user')