Package: layabauth
Handle OAuth2 authentication for REST APIsAs expected by the HTTP specification, token is extracted fromAuthorizationheader and must be prefixed withBearer.Token will then be validated and in case it is valid, you will be able to access the raw token (as string) and the decoded token body (as dictionary).StarletteProvides aStarlette authentication backend:layabauth.starlette.OAuth2IdTokenBackend.3 arguments are required:TheJWKsURI as defined in .well-known.Azure Active Directory:https://sts.windows.net/common/discovery/keysMicrosoft Identity Platform:https://sts.windows.net/common/discovery/keysA callable to create theauthenticated userbased on received token.A callable to returnsauthenticated user scopesbased on received token.Below is a sampleStarletteapplication with an endpoint requesting a Microsoft issued OAuth2 token.importstarlette.applicationsfromstarlette.authenticationimportSimpleUser,requiresfromstarlette.middlewareimportMiddlewarefromstarlette.middleware.authenticationimportAuthenticationMiddlewarefromstarlette.responsesimportPlainTextResponseimportlayabauth.starlettebackend=layabauth.starlette.OAuth2IdTokenBackend(jwks_uri="https://sts.windows.net/common/discovery/keys",create_user=lambdatoken,token_body:SimpleUser(token_body["name"]),scopes=lambdatoken,token_body:token_body["scopes"])app=starlette.applications.Starlette(middleware=[Middleware(AuthenticationMiddleware,backend=backend)])@app.route("/my_endpoint")@requires('my_scope')asyncdefmy_endpoint(request):returnPlainTextResponse(request.user.display_name)FlaskProvides a decoratorlayabauth.flask.requires_authenticationto ensure that, in a context of aFlaskapplication, a valid OAuth2 token was received.TheJWKsURI as defined in .well-known is the only required argument.Azure Active Directory:https://sts.windows.net/common/discovery/keysMicrosoft Identity Platform:https://sts.windows.net/common/discovery/keysIf validation fails, anwerkzeug.exceptions.Unauthorizedexception is raised.
Otherwise token is stored inflask.g.tokenand decoded token body is stored inflask.g.token_body.Decorator works fine onflask-restplusmethods as well.Below is a sampleFlaskapplication with an endpoint requesting a Microsoft issued OAuth2 token.importflaskimportlayabauth.flaskapp=flask.Flask(__name__)@app.route("/my_endpoint")@layabauth.flask.requires_authentication("https://sts.windows.net/common/discovery/keys")defmy_endpoint():# Optional, ensure that the appropriates scopes are providedlayabauth.flask.requires_scopes(lambdatoken,token_body:token_body["scopes"],"my_scope")# Return the content of the name entry within the decoded token body.returnflask.Response(flask.g.token_body["name"])app.run()OpenAPIYou can generate OpenAPI 2.0securitydefinition thanks tolayabauth.authorizations.You can generate OpenAPI 2.0method securitythanks tolayabauth.method_authorizationsTestingAuthentication can be mocked usinglayabauth.testing.auth_mockpytestfixture.token_bodypytestfixture returning the decoded token body used in tests must be provided.jwks_uripytestfixture returning the jwks_uri used in tests must be provided.fromlayabauth.testingimport*@pytest.fixturedefjwks_uri():return"https://sts.windows.net/common/discovery/keys"@pytest.fixturedeftoken_body():return{"name":"TEST@email.com","scopes":["my_scope"]}deftest_authentication(auth_mock,client):response=client.get("/my_endpoint",headers={"Authentication":"Bearer mocked_token"})assertresponse.text=="TEST@email.com"How to installpython 3.7+must be installedUse pip to install module:python-mpipinstalllayabauth