Security News
Supply Chain Attack Detected in Solana's web3.js Library
A supply chain attack has been detected in versions 1.95.6 and 1.95.7 of the popular @solana/web3.js library.
starlette-oauth2-api
Advanced tools
A Starlette middleware for authentication and authorization through JWT.
This middleware is intended to add authentication and authorization to an API (e.g. FastAPI) through access tokens provided by an external auth provider (e.g. Microsoft AD, Auth0). Its main use-case is when you have an API that relies on an external identity provider for authentication and authorization, and whose clients can request access tokens themselves. In this case, the API does not need to communicate with the identity provider - it only needs to validate that the access tokens are signed by the identity provider.
This middleware depends only on python-jose
, which it uses to decode and validate JWTs.
pip install starlette-oauth2-api
Below is an example of how to use this middleware:
from starlette.applications import Starlette
from starlette_oauth2_api import AuthenticateMiddleware
app = Starlette()
app.add_middleware(AuthenticateMiddleware,
providers={
'google': {
'keys': 'https://www.googleapis.com/oauth2/v3/certs',
'issuer': 'https://accounts.google.com',
'audience': '852159111111-xxxxxx.apps.googleusercontent.com',
}
},
public_paths={'/'},
)
At this point, every route except /
requires an authorization: Bearer {token}
where token
must:
issuer
to the audience audience
https://www.googleapis.com/oauth2/v3/certs
Failing any of the conditions above returns a 401 response, failing to contain the header with Bearer
returns a 400 response.
When the request is valid, the Middlware adds all claims in the JWT to oauth2-claims
, which can be accessed using
...
def home(request):
...
request.scope['oauth2-claims']
...
In particular, if your identity provider provides custom claims, you can use these for authorization.
Requests to initiate a websocket connection also require JWT, using the same method as usual HTTP requests. When the token is invalid (see below), the connection is terminated with code 1008.
To enable pre-flight checks, you must add the CORS middleware after adding the authentication middleware, so that the CORS middleware takes precedence and answers the preflight check. The header authentication
must be accepted in CORS, so that the browser presents it on the actual request.
from starlette.middleware.cors import CORSMiddleware
# app.add_middleware(AuthenticateMiddleware, ...)
app.add_middleware(CORSMiddleware,
allow_origins=settings.CORS_ORIGINS,
allow_methods=settings.CORS_METHODS,
allow_headers=['authorization'],
)
The argument providers
must be a dictionary whose keys are arbitrary, and its values must be a dictionary containing three keys:
issuer
audience
keys
This middleware uses the issuer to validate (by python-Jose) that the token was issued by a specific entity. Examples of issuers:
https://login.microsoftonline.com/<ad_tenant_id>/v2.0
https://accounts.google.com
This value can be found at https://.../.well-known/openid-configuration
, key iss
.
Like the issuer, this middleware uses the audience to validate that the token was intended for this API. Some examples of audiences from out-there:
https://<app-name>.azurewebsites.net
<tenant>-<project>.apps.googleusercontent.com
This value can be found when the application is configured in AD, which depends on the particular Identity provider that you use.
keys
correspond to the public keys of the identity provider, whose corresponding (private) counterpart was used to sign the token. This middleware relies on Python-Jose to verify that the token was signed by the counterpart key of this field.
keys
can be a URL or an object. When it is a URL, this middleware fetches the keys from it. Examples:
https://login.microsoftonline.com/<tenant-id>/discovery/v2.0/keys
https://www.googleapis.com/oauth2/v3/certs
This URL can be found at https://.../.well-known/openid-configuration
, key jwks_uri
.
When keys
is another object, it represents a JWK, JWK set as per RFC 7517, or other (non-standard) variation that python-jose accepts. An example of its content:
{'keys': [
{
"kid": "...",
"e": "AQAB",
"kty": "RSA",
"alg": "RS256",
"n": "...",
"use": "sig"
},
]}
The tradeoff between providing a JWK set or a url is the following: on the one hand, if you provide a JWK set, this middleware does not need access to the public internet to validate tokens, and can thus be deployed on environments without it. On the other hand, JWK are eventually rotated by the identity provider and you will have redeploy the application with the respective updated public keys.
The signature is verified with the keys explained above. If the token carries an at_hash
key in it's payload, it will be ignored. This is because the access token is required to decode it, which we do not have access to.
Some providers have rotating keys that the server must keep up-to-date. To refresh keys every so often, pass key_refresh_minutes
to the middleware. By default, it does not refresh keys, i.e. the key is constant and equal to the one first fetched from the provider.
FAQs
Unknown package
We found that starlette-oauth2-api demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
A supply chain attack has been detected in versions 1.95.6 and 1.95.7 of the popular @solana/web3.js library.
Research
Security News
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
Security News
Research
Socket researchers have discovered malicious npm packages targeting crypto developers, stealing credentials and wallet data using spyware delivered through typosquats of popular cryptographic libraries.