def custom_authorisation_handler(event, context):
    """
    Perform validation of API Gateway custom authoriser by checking JWT user token
    from header.
    """
    print("Client token: " + event['authorizationToken'])
    print("Method ARN: " + event['methodArn'])

    # Validate the incoming JWT token from pass Auth header
    authentication_token = event["authorizationToken"]
    jwt_token = authentication_token.replace(auth.AUTHENTICATION_SCHEME,
                                             '').strip(' ')

    decoded = auth.jwt_validate(jwt_token, os.environ['JWT_SECRET'],
                                os.environ['JWT_AUDIENCE'],
                                os.environ['JWT_ISSUER_3RD_PARTY'],
                                os.environ['JWT_ISSUER_SELF'])

    if decoded["iss"] == os.environ['JWT_ISSUER_3RD_PARTY']:
        # User email will be Principal ID to be associated with calls. Ex 'user|[email protected]'
        principal_id = 'user|' + decoded["https://aaf.edu.au/attributes"][
            "mail"]
    else:
        # Organisation is the principal ID
        principal_id = decoded["sub"]
    '''
    If the token is valid, a policy must be generated which will allow or deny
    access to the client. If access is denied, the client will receive a 403
    Access Denied response. If access is allowed, API Gateway will proceed with
    the backend integration configured on the method that was called.

    The policy is cached for 5 minutes by default (TTL is
    configurable in the authorizer) and will apply to subsequent calls to any
    method/resource in the RestApi made with the same token.
    '''
    tmp = event['methodArn'].split(':')
    api_gateway_arn_tmp = tmp[5].split('/')
    aws_account_id = tmp[4]

    policy = auth.AuthPolicy(principal_id, aws_account_id)
    policy.restApiId = api_gateway_arn_tmp[0]
    policy.region = tmp[3]
    policy.stage = api_gateway_arn_tmp[1]

    if decoded["iss"] == os.environ['JWT_ISSUER_SELF'] and decoded[
            "role"] == settings.SERVICE_ROLE:
        # Self signed provider users can use all HTTP methods
        policy.allow_all_methods()
        context = {
            'provider': decoded["sub"],
            'role': decoded["role"],
        }

        if "environment" in decoded:
            context["environment"] = decoded["environment"]
        else:
            context["environment"] = "demo"

    elif decoded["iss"] == os.environ['JWT_ISSUER_SELF'] and decoded[
            "role"] == settings.INSTITUTION_ROLE:
        policy.allow_method(auth.HttpVerb.GET, '/*')
        policy.allow_method(auth.HttpVerb.GET, '/RAiD/*')
        policy.allow_method(auth.HttpVerb.GET, '/providers/*')
        policy.allow_method(auth.HttpVerb.ALL, '/institutions/*')
        context = {
            'provider': decoded["sub"],
            #'grid': decoded["grid"], TODO
            'role': decoded["role"],
        }

        if "environment" in decoded:
            context["environment"] = decoded["environment"]
        else:
            context["environment"] = "demo"

    else:
        raise Exception('Unauthorized')

    # Finally, build the policy
    auth_response = policy.build()
    auth_response['context'] = context
    return auth_response
Exemplo n.º 2
0
import auth
from config import config
from models import PlayerRoom, User
from utils import FILE_DIR

# SETUP SERVER

sio = socketio.AsyncServer(
    async_mode="aiohttp",
    engineio_logger=False,
    cors_allowed_origins=config.get("Webserver",
                                    "cors_allowed_origins",
                                    fallback=None),
)
app = web.Application()
app["AuthzPolicy"] = auth.AuthPolicy()
aiohttp_security.setup(app, SessionIdentityPolicy(), app["AuthzPolicy"])
aiohttp_session.setup(app, EncryptedCookieStorage(auth.get_secret_token()))
aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader("templates"))
sio.attach(app)

# SETUP PATHS
os.chdir(FILE_DIR)

# SETUP LOGGING

logger = logging.getLogger("PlanarAllyServer")
logger.setLevel(logging.INFO)
file_handler = logging.FileHandler(str(FILE_DIR / "planarallyserver.log"))
file_handler.setLevel(logging.INFO)
formatter = logging.Formatter(
Exemplo n.º 3
0
def setup_app(middlewares: Iterable[Callable] = ()) -> web.Application:
    app = web.Application(middlewares=middlewares)
    app["AuthzPolicy"] = auth.AuthPolicy()
    aiohttp_security.setup(app, SessionIdentityPolicy(), app["AuthzPolicy"])
    aiohttp_session.setup(app, EncryptedCookieStorage(auth.get_secret_token()))
    return app