canaille-globuzma/canaille/oauth2utils.py

286 lines
9.3 KiB
Python
Raw Normal View History

2020-08-16 17:39:14 +00:00
import datetime
2020-08-14 13:26:14 +00:00
from authlib.integrations.flask_oauth2 import AuthorizationServer, ResourceProtector
from authlib.oauth2.rfc6749.grants import (
AuthorizationCodeGrant as _AuthorizationCodeGrant,
ResourceOwnerPasswordCredentialsGrant as _ResourceOwnerPasswordCredentialsGrant,
RefreshTokenGrant as _RefreshTokenGrant,
2020-08-20 12:30:42 +00:00
ImplicitGrant,
ClientCredentialsGrant,
2020-08-14 11:18:08 +00:00
)
2020-08-14 13:26:14 +00:00
from authlib.oauth2.rfc6750 import BearerTokenValidator as _BearerTokenValidator
2020-08-24 13:56:30 +00:00
from authlib.oauth2.rfc7009 import RevocationEndpoint as _RevocationEndpoint
2020-08-25 13:28:13 +00:00
from authlib.oauth2.rfc7636 import CodeChallenge as _CodeChallenge
2020-08-24 12:44:32 +00:00
from authlib.oauth2.rfc7662 import IntrospectionEndpoint as _IntrospectionEndpoint
2020-08-14 13:26:14 +00:00
from authlib.oidc.core.grants import (
OpenIDCode as _OpenIDCode,
OpenIDImplicitGrant as _OpenIDImplicitGrant,
OpenIDHybridGrant as _OpenIDHybridGrant,
)
from authlib.oidc.core import UserInfo
2020-08-24 08:03:48 +00:00
from flask import current_app
2020-08-14 13:26:14 +00:00
from .models import Client, AuthorizationCode, Token, User
def exists_nonce(nonce, req):
2020-08-17 16:49:05 +00:00
exists = AuthorizationCode.filter(oauthClientID=req.client_id, oauthNonce=nonce)
2020-08-14 13:26:14 +00:00
return bool(exists)
2020-08-24 08:03:48 +00:00
def get_jwt_config(grant):
2020-08-28 14:07:39 +00:00
with open(current_app.config["JWT"]["PRIVATE_KEY"]) as pk:
return {
"key": pk.read(),
"alg": current_app.config["JWT"]["ALG"],
"iss": authorization.metadata["issuer"],
"exp": current_app.config["JWT"]["EXP"],
}
2020-08-24 08:03:48 +00:00
2020-08-14 13:26:14 +00:00
def generate_user_info(user, scope):
2020-08-27 08:50:50 +00:00
user = User.get(user)
2020-08-24 08:03:48 +00:00
fields = ["sub"]
if "profile" in scope:
fields += [
"name",
"family_name",
"given_name",
"nickname",
"preferred_username",
"profile",
"picture",
"website",
"gender",
"birthdate",
"zoneinfo",
"locale",
"updated_at",
]
if "email" in scope:
fields += ["email", "email_verified"]
if "address" in scope:
fields += ["address"]
if "phone" in scope:
fields += ["phone_number", "phone_number_verified"]
data = {}
for field in fields:
ldap_field_match = current_app.config["JWT"]["MAPPING"].get(field.upper())
if ldap_field_match and ldap_field_match in user.attrs:
data[field] = user.__getattr__(ldap_field_match)
2020-08-24 08:03:48 +00:00
if isinstance(data[field], list):
data[field] = data[field][0]
return UserInfo(**data)
2020-08-14 13:26:14 +00:00
2020-08-19 09:16:18 +00:00
def save_authorization_code(code, request):
2020-08-14 13:26:14 +00:00
nonce = request.data.get("nonce")
2020-08-17 15:49:49 +00:00
now = datetime.datetime.now()
code = AuthorizationCode(
2020-08-19 09:16:18 +00:00
oauthCode=code,
oauthSubject=request.user,
oauthClient=request.client.dn,
2020-08-19 09:16:18 +00:00
oauthRedirectURI=request.redirect_uri or request.client.oauthRedirectURIs[0],
2020-08-17 15:49:49 +00:00
oauthScope=request.scope,
2020-08-17 16:49:05 +00:00
oauthNonce=nonce,
2020-08-17 15:49:49 +00:00
oauthAuthorizationDate=now.strftime("%Y%m%d%H%M%SZ"),
oauthAuthorizationLifetime=str(84000),
2020-08-24 12:44:32 +00:00
oauthCodeChallenge=request.data.get("code_challenge"),
oauthCodeChallengeMethod=request.data.get("code_challenge_method"),
2020-08-14 13:26:14 +00:00
)
2020-08-17 15:49:49 +00:00
code.save()
return code.oauthCode
2020-08-14 11:18:08 +00:00
2020-08-14 13:26:14 +00:00
class AuthorizationCodeGrant(_AuthorizationCodeGrant):
2020-08-25 13:51:49 +00:00
TOKEN_ENDPOINT_AUTH_METHODS = ["client_secret_basic", "client_secret_post", "none"]
2020-08-19 09:16:18 +00:00
def save_authorization_code(self, code, request):
return save_authorization_code(code, request)
2020-08-14 11:18:08 +00:00
2020-08-19 08:28:28 +00:00
def query_authorization_code(self, code, client):
item = AuthorizationCode.filter(oauthCode=code, oauthClient=client.dn)
2020-08-17 16:49:05 +00:00
if item and not item[0].is_expired():
2020-08-17 15:49:49 +00:00
return item[0]
2020-08-14 11:18:08 +00:00
def delete_authorization_code(self, authorization_code):
2020-08-17 16:02:38 +00:00
authorization_code.delete()
2020-08-14 11:18:08 +00:00
def authenticate_user(self, authorization_code):
2020-08-27 08:50:50 +00:00
return User.get(authorization_code.oauthSubject).dn
2020-08-14 11:18:08 +00:00
2020-08-14 13:26:14 +00:00
class OpenIDCode(_OpenIDCode):
def exists_nonce(self, nonce, request):
return exists_nonce(nonce, request)
def get_jwt_config(self, grant):
2020-08-24 08:03:48 +00:00
return get_jwt_config(grant)
2020-08-14 13:26:14 +00:00
def generate_user_info(self, user, scope):
return generate_user_info(user, scope)
class PasswordGrant(_ResourceOwnerPasswordCredentialsGrant):
2020-08-14 11:18:08 +00:00
def authenticate_user(self, username, password):
2020-08-27 08:50:50 +00:00
return User.authenticate(username, password).dn
2020-08-14 11:18:08 +00:00
2020-08-14 13:26:14 +00:00
class RefreshTokenGrant(_RefreshTokenGrant):
2020-08-14 11:18:08 +00:00
def authenticate_refresh_token(self, refresh_token):
2020-08-24 08:52:21 +00:00
token = Token.filter(oauthRefreshToken=refresh_token)
if token and token[0].is_refresh_token_active():
return token[0]
2020-08-14 11:18:08 +00:00
def authenticate_user(self, credential):
2020-08-27 08:50:50 +00:00
return User.get(credential.oauthSubject).dn
2020-08-14 11:18:08 +00:00
def revoke_old_credential(self, credential):
2020-09-17 09:10:12 +00:00
credential.oauthRevokationDate = datetime.datetime.now().strftime(
"%Y%m%d%H%M%SZ"
)
2020-08-25 09:35:30 +00:00
credential.save()
2020-08-14 13:26:14 +00:00
2020-08-16 17:39:14 +00:00
2020-08-20 12:30:42 +00:00
class OpenIDImplicitGrant(_OpenIDImplicitGrant):
2020-08-14 13:26:14 +00:00
def exists_nonce(self, nonce, request):
return exists_nonce(nonce, request)
2020-08-23 17:56:37 +00:00
def get_jwt_config(self, grant=None):
2020-08-24 08:03:48 +00:00
return get_jwt_config(grant)
2020-08-14 13:26:14 +00:00
def generate_user_info(self, user, scope):
return generate_user_info(user, scope)
2020-08-20 12:30:42 +00:00
class OpenIDHybridGrant(_OpenIDHybridGrant):
2020-08-19 09:16:18 +00:00
def save_authorization_code(self, code, request):
return save_authorization_code(code, request)
2020-08-14 13:26:14 +00:00
def exists_nonce(self, nonce, request):
return exists_nonce(nonce, request)
2020-08-24 08:03:48 +00:00
def get_jwt_config(self, grant=None):
return get_jwt_config(grant)
2020-08-14 13:26:14 +00:00
def generate_user_info(self, user, scope):
return generate_user_info(user, scope)
2020-08-14 11:18:08 +00:00
def query_client(client_id):
return Client.get(client_id)
def save_token(token, request):
2020-08-16 17:39:14 +00:00
now = datetime.datetime.now()
2020-08-17 16:02:38 +00:00
t = Token(
2020-08-16 17:39:14 +00:00
oauthTokenType=token["token_type"],
oauthAccessToken=token["access_token"],
oauthIssueDate=now.strftime("%Y%m%d%H%M%SZ"),
oauthTokenLifetime=str(token["expires_in"]),
2020-08-17 07:45:35 +00:00
oauthScope=token["scope"],
oauthClient=request.client.dn,
2020-08-24 12:44:32 +00:00
oauthRefreshToken=token.get("refresh_token"),
2020-08-27 08:50:50 +00:00
oauthSubject=request.user,
2020-08-16 17:39:14 +00:00
)
2020-08-17 16:02:38 +00:00
t.save()
2020-08-14 11:18:08 +00:00
2020-08-14 13:26:14 +00:00
class BearerTokenValidator(_BearerTokenValidator):
2020-08-14 11:18:08 +00:00
def authenticate_token(self, token_string):
return Token.get(token_string)
def request_invalid(self, request):
return False
def token_revoked(self, token):
2020-09-17 09:10:12 +00:00
return bool(token.oauthRevokationDate)
2020-08-14 11:18:08 +00:00
2020-08-14 13:26:14 +00:00
2020-08-24 13:56:30 +00:00
class RevocationEndpoint(_RevocationEndpoint):
def query_token(self, token, token_type_hint, client):
if token_type_hint == "access_token":
return Token.filter(oauthClient=client.dn, oauthAccessToken=token)
2020-08-24 13:56:30 +00:00
elif token_type_hint == "refresh_token":
return Token.filter(oauthClient=client.dn, oauthRefreshToken=token)
2020-08-24 13:56:30 +00:00
item = Token.filter(oauthClient=client.dn, oauthAccessToken=token)
2020-08-24 13:56:30 +00:00
if item:
return item[0]
item = Token.filter(oauthClient=client.dn, oauthRefreshToken=token)
2020-08-24 13:56:30 +00:00
if item:
return item[0]
return None
def revoke_token(self, token):
2020-09-17 09:10:12 +00:00
token.oauthRevokationDate = datetime.datetime.now().strftime("%Y%m%d%H%M%SZ")
2020-08-24 13:56:30 +00:00
token.save()
2020-08-24 12:44:32 +00:00
class IntrospectionEndpoint(_IntrospectionEndpoint):
def query_token(self, token, token_type_hint, client):
if token_type_hint == "access_token":
tok = Token.filter(oauthAccessToken=token)
elif token_type_hint == "refresh_token":
tok = Token.filter(oauthRefreshToken=token)
else:
tok = Token.filter(oauthAccessToken=token)
if not tok:
tok = Token.filter(oauthRefreshToken=token)
if tok:
tok = tok[0]
if tok.oauthClient == client.dn:
2020-08-24 12:44:32 +00:00
return tok
# if has_introspect_permission(client):
# return tok
def introspect_token(self, token):
client_id = Client.get(token.oauthClient).oauthClientID
2020-08-24 12:44:32 +00:00
return {
"active": True,
"client_id": client_id,
2020-08-24 12:44:32 +00:00
"token_type": token.oauthTokenType,
"username": User.get(token.oauthSubject).name,
"scope": token.get_scope(),
"sub": token.oauthSubject,
"aud": client_id,
2020-08-28 14:07:39 +00:00
"iss": authorization.metadata["issuer"],
2020-08-24 12:44:32 +00:00
"exp": token.get_expires_at(),
"iat": token.get_issued_at(),
}
2020-08-25 13:28:13 +00:00
class CodeChallenge(_CodeChallenge):
def get_authorization_code_challenge(self, authorization_code):
return authorization_code.oauthCodeChallenge
def get_authorization_code_challenge_method(self, authorization_code):
return authorization_code.oauthCodeChallengeMethod
2020-08-14 13:26:14 +00:00
authorization = AuthorizationServer()
2020-08-14 11:18:08 +00:00
require_oauth = ResourceProtector()
def config_oauth(app):
2020-08-14 13:26:14 +00:00
authorization.init_app(app, query_client=query_client, save_token=save_token)
2020-08-14 11:18:08 +00:00
2020-08-20 12:30:42 +00:00
authorization.register_grant(PasswordGrant)
authorization.register_grant(ImplicitGrant)
2020-08-24 08:52:21 +00:00
authorization.register_grant(RefreshTokenGrant)
2020-08-20 12:30:42 +00:00
authorization.register_grant(ClientCredentialsGrant)
2020-08-14 13:26:14 +00:00
authorization.register_grant(
2020-08-24 12:44:32 +00:00
AuthorizationCodeGrant,
2020-08-25 13:39:44 +00:00
[OpenIDCode(require_nonce=True), CodeChallenge(required=True)],
2020-08-14 13:26:14 +00:00
)
2020-08-20 12:30:42 +00:00
authorization.register_grant(OpenIDImplicitGrant)
authorization.register_grant(OpenIDHybridGrant)
2020-08-14 11:18:08 +00:00
require_oauth.register_token_validator(BearerTokenValidator())
2020-08-24 12:44:32 +00:00
authorization.register_endpoint(IntrospectionEndpoint)
2020-08-24 13:56:30 +00:00
authorization.register_endpoint(RevocationEndpoint)