Skip to content

Commit

Permalink
Merge pull request #505 from azmeuk/rfc7592
Browse files Browse the repository at this point in the history
Fixed RFC7592 Dynamic Client Registration Management Protocol
  • Loading branch information
lepture authored Nov 5, 2022
2 parents 9ae4db9 + 831f4d4 commit a7ac27a
Show file tree
Hide file tree
Showing 8 changed files with 761 additions and 65 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ Generic, spec-compliant implementation to build clients and providers:
- [RFC7009: OAuth 2.0 Token Revocation](https://docs.authlib.org/en/latest/specs/rfc7009.html)
- [RFC7523: JWT Profile for OAuth 2.0 Client Authentication and Authorization Grants](https://docs.authlib.org/en/latest/specs/rfc7523.html)
- [RFC7591: OAuth 2.0 Dynamic Client Registration Protocol](https://docs.authlib.org/en/latest/specs/rfc7591.html)
- [ ] RFC7592: OAuth 2.0 Dynamic Client Registration Management Protocol
- [RFC7592: OAuth 2.0 Dynamic Client Registration Management Protocol](https://docs.authlib.org/en/latest/specs/rfc7592.html)
- [RFC7636: Proof Key for Code Exchange by OAuth Public Clients](https://docs.authlib.org/en/latest/specs/rfc7636.html)
- [RFC7662: OAuth 2.0 Token Introspection](https://docs.authlib.org/en/latest/specs/rfc7662.html)
- [RFC8414: OAuth 2.0 Authorization Server Metadata](https://docs.authlib.org/en/latest/specs/rfc8414.html)
Expand Down
2 changes: 1 addition & 1 deletion authlib/integrations/flask_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ def create_oauth_request(request, request_cls, use_json=False):
if not request:
request = flask_req

if request.method == 'POST':
if request.method in ('POST', 'PUT'):
if use_json:
body = request.get_json()
else:
Expand Down
2 changes: 2 additions & 0 deletions authlib/integrations/sqla_oauth2/client_mixin.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ def client_metadata(self):

def set_client_metadata(self, value):
self._client_metadata = json_dumps(value)
if 'client_metadata' in self.__dict__:
del self.__dict__['client_metadata']

@property
def redirect_uris(self):
Expand Down
212 changes: 149 additions & 63 deletions authlib/oauth2/rfc7592/endpoint.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,34 @@
from authlib.consts import default_json_headers
from authlib.jose import JsonWebToken, JoseError
from ..rfc7591.claims import ClientMetadataClaims
from ..rfc6749 import scope_to_list
from ..rfc6749 import AccessDeniedError
from ..rfc6750 import InvalidTokenError
from ..rfc6749 import InvalidClientError
from ..rfc6749 import InvalidRequestError
from ..rfc6749 import UnauthorizedClientError
from ..rfc7591 import InvalidClientMetadataError
from ..rfc7591 import InvalidSoftwareStatementError
from ..rfc7591 import UnapprovedSoftwareStatementError


class ClientConfigurationEndpoint(object):
ENDPOINT_NAME = 'client_configuration'

#: The claims validation class
claims_class = ClientMetadataClaims

def __init__(self, server):
self.server = server

def __call__(self, request):
return self.create_configuration_response(request)

def create_configuration_response(self, request):
# This request is authenticated by the registration access token issued
# to the client.
token = self.authenticate_token(request)
if not token:
raise InvalidTokenError()
raise AccessDeniedError()

request.credential = token

Expand All @@ -24,13 +37,13 @@ def create_configuration_response(self, request):
# If the client does not exist on this server, the server MUST respond
# with HTTP 401 Unauthorized and the registration access token used to
# make this request SHOULD be immediately revoked.
self.revoke_access_token(request)
raise InvalidTokenError()
self.revoke_access_token(request, token)
raise InvalidClientError(status_code=401)

if not self.check_permission(client, request):
# If the client does not have permission to read its record, the server
# MUST return an HTTP 403 Forbidden.
raise AccessDeniedError()
raise UnauthorizedClientError(status_code=403)

request.client = client

Expand All @@ -46,22 +59,10 @@ def create_endpoint_request(self, request):

def create_read_client_response(self, client, request):
body = self.introspect_client(client)
info = self.generate_client_registration_info(client, request)
body.update(info)
body.update(self.generate_client_registration_info(client, request))
return 200, body, default_json_headers

def create_delete_client_response(self, client, request):
"""To deprive itself on the authorization server, the client makes
an HTTP DELETE request to the client configuration endpoint. This
request is authenticated by the registration access token issued to
the client.
The following is a non-normative example request::
DELETE /register/s6BhdRkqt3 HTTP/1.1
Host: server.example.com
Authorization: Bearer reg-23410913-abewfq.123483
"""
self.delete_client(client, request)
headers = [
('Cache-Control', 'no-store'),
Expand All @@ -70,66 +71,109 @@ def create_delete_client_response(self, client, request):
return 204, '', headers

def create_update_client_response(self, client, request):
""" To update a previously registered client's registration with an
authorization server, the client makes an HTTP PUT request to the
client configuration endpoint with a content type of "application/
json".
The following is a non-normative example request::
PUT /register/s6BhdRkqt3 HTTP/1.1
Accept: application/json
Host: server.example.com
Authorization: Bearer reg-23410913-abewfq.123483
{
"client_id": "s6BhdRkqt3",
"client_secret": "cf136dc3c1fc93f31185e5885805d",
"redirect_uris": [
"https://client.example.org/callback",
"https://client.example.org/alt"
],
"grant_types": ["authorization_code", "refresh_token"],
"token_endpoint_auth_method": "client_secret_basic",
"jwks_uri": "https://client.example.org/my_public_keys.jwks",
"client_name": "My New Example",
"client_name#fr": "Mon Nouvel Exemple",
"logo_uri": "https://client.example.org/newlogo.png",
"logo_uri#fr": "https://client.example.org/fr/newlogo.png"
}
"""
# The updated client metadata fields request MUST NOT include the
# "registration_access_token", "registration_client_uri",
# "client_secret_expires_at", or "client_id_issued_at" fields
# 'registration_access_token', 'registration_client_uri',
# 'client_secret_expires_at', or 'client_id_issued_at' fields
must_not_include = (
'registration_access_token', 'registration_client_uri',
'client_secret_expires_at', 'client_id_issued_at',
'registration_access_token',
'registration_client_uri',
'client_secret_expires_at',
'client_id_issued_at',
)
for k in must_not_include:
if k in request.data:
return
raise InvalidRequestError()

# The client MUST include its "client_id" field in the request
# The client MUST include its 'client_id' field in the request
client_id = request.data.get('client_id')
if not client_id:
raise
raise InvalidRequestError()
if client_id != client.get_client_id():
raise
raise InvalidRequestError()

# If the client includes the "client_secret" field in the request,
# If the client includes the 'client_secret' field in the request,
# the value of this field MUST match the currently issued client
# secret for that client.
if 'client_secret' in request.data:
if not client.check_client_secret(request.data['client_secret']):
raise
raise InvalidRequestError()

client = self.save_client(client, request)
client_metadata = self.extract_client_metadata(request)
client = self.update_client(client, client_metadata, request)
return self.create_read_client_response(client, request)

def extract_client_metadata(self, request):
json_data = request.data.copy()
options = self.get_claims_options()
claims = self.claims_class(json_data, {}, options, self.get_server_metadata())

try:
claims.validate()
except JoseError as error:
raise InvalidClientMetadataError(error.description)
return claims.get_registered_claims()

def get_claims_options(self):
metadata = self.get_server_metadata()
if not metadata:
return {}

scopes_supported = metadata.get('scopes_supported')
response_types_supported = metadata.get('response_types_supported')
grant_types_supported = metadata.get('grant_types_supported')
auth_methods_supported = metadata.get('token_endpoint_auth_methods_supported')
options = {}
if scopes_supported is not None:
scopes_supported = set(scopes_supported)

def _validate_scope(claims, value):
if not value:
return True
scopes = set(scope_to_list(value))
return scopes_supported.issuperset(scopes)

options['scope'] = {'validate': _validate_scope}

if response_types_supported is not None:
response_types_supported = set(response_types_supported)

def _validate_response_types(claims, value):
return response_types_supported.issuperset(set(value))

options['response_types'] = {'validate': _validate_response_types}

if grant_types_supported is not None:
grant_types_supported = set(grant_types_supported)

def _validate_grant_types(claims, value):
return grant_types_supported.issuperset(set(value))

options['grant_types'] = {'validate': _validate_grant_types}

if auth_methods_supported is not None:
options['token_endpoint_auth_method'] = {'values': auth_methods_supported}

return options

def introspect_client(self, client):
return {**client.client_info, **client.client_metadata}

def generate_client_registration_info(self, client, request):
"""Generate ```registration_client_uri`` and ``registration_access_token``
for RFC7592. This method returns ``None`` by default. Developers MAY rewrite
this method to return registration information."""
for RFC7592. By default this method returns the values sent in the current
request. Developers MUST rewrite this method to return different registration
information.::
def generate_client_registration_info(self, client, request):{
access_token = request.headers['Authorization'].split(' ')[1]
return {
'registration_client_uri': request.uri,
'registration_access_token': access_token,
}
:param client: the instance of OAuth client
:param request: formatted request instance
"""
raise NotImplementedError()

def authenticate_token(self, request):
Expand All @@ -145,15 +189,37 @@ def authenticate_token(self, request):
raise NotImplementedError()

def authenticate_client(self, request):
"""Read a client from the request payload.
Developers MUST implement this method in subclass::
def authenticate_client(self, request):
client_id = request.data.get('client_id')
return Client.get(client_id=client_id)
:return: client instance
"""
raise NotImplementedError()

def revoke_access_token(self, request):
def revoke_access_token(self, token, request):
"""Revoke a token access in case an invalid client has been requested.
Developers MUST implement this method in subclass::
def revoke_access_token(self, token, request):
token.revoked = True
token.save()
"""
raise NotImplementedError()

def check_permission(self, client, request):
raise NotImplementedError()
"""Checks wether the current client is allowed to be accessed, edited
or deleted. Developers MUST implement it in subclass, e.g.::
def introspect_client(self, client):
def check_permission(self, client, request):
return client.editable
:return: boolean
"""
raise NotImplementedError()

def delete_client(self, client, request):
Expand All @@ -168,5 +234,25 @@ def delete_client(self, client, request):
"""
raise NotImplementedError()

def save_client(self, client, request):
def update_client(self, client, client_metadata, request):
"""Update the client in the database. Developers MUST implement this method
in subclass::
def update_client(self, client, client_metadata, request):
client.set_client_metadata({**client.client_metadata, **client_metadata})
client.save()
return client
:param client: the instance of OAuth client
:param client_metadata: a dict of the client claims to update
:param request: formatted request instance
:return: client instance
"""

raise NotImplementedError()

def get_server_metadata(self):
"""Return server metadata which includes supported grant types,
response types and etc.
"""
raise NotImplementedError()
1 change: 1 addition & 0 deletions docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ Version 1.2.0
- Use ``flask.g`` instead of ``_app_ctx_stack``, via :gh:`issue#482`.
- Add ``headers`` parameter back to ``ClientSecretJWT``, via :gh:`issue#457`.
- Always passing ``realm`` parameter in OAuth 1 clients, via :gh:`issue#339`.
- Implemented RFC7592 Dynamic Client Registration Management Protocol, via :gh:`PR#505`.


Version 1.1.0
Expand Down
1 change: 1 addition & 0 deletions docs/specs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ works.
rfc7519
rfc7523
rfc7591
rfc7592
rfc7636
rfc7638
rfc7662
Expand Down
Loading

0 comments on commit a7ac27a

Please sign in to comment.