services.PyOIDCHandler

src/idserver/services/PyOIDCHandler.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import base64
import json

import logging
from oic.oic import Client, RegistrationResponse, AuthorizationResponse, \
    AccessTokenResponse, TokenErrorResponse, AuthorizationErrorResponse
from oic.oic.message import ProviderConfigurationResponse
from oic.utils.authn.client import CLIENT_AUTHN_METHOD
from typing import MutableMapping
from .IdentityProviderContext import IdentityProviderContext

logger = logging.getLogger(__name__)


class _ClientAuthentication:
    def __init__(self, client_id: str, client_secret: str):
        self._client_id = client_id
        self._client_secret = client_secret

    def __call__(self, method: str, request: MutableMapping[str, str]):
        """
        Args:
            method (str): Client Authentication Method. Only 'client_secret_basic' and 'client_secret_post' is
                supported.
            request (MutableMapping[str, str]): Token request parameters. This may be modified, i.e. if
                'client_secret_post' is used the client credentials will be added.

        Returns:
            (Mapping[str, str]): HTTP headers to be included in the token request, or `None` if no extra HTTPS headers
            are required for the token request.
        """
        if method == 'client_secret_post':
            request['client_id'] = self._client_id
            request['client_secret'] = self._client_secret
            return None  # authentication is in the request body, so no Authorization header is returned

        # default to 'client_secret_basic'
        credentials = '{}:{}'.format(self._client_id, self._client_secret)
        basic_auth = 'Basic {}'.format(base64.urlsafe_b64encode(credentials.encode('utf-8')).decode('utf-8'))
        return {'Authorization': basic_auth}


class PyOIDCHandler:
    """
    Wrapper around pyoidc library, coupled with config for a simplified API for flask-pyoidc.
    """

    def __init__(self, address, identity_provider_context: IdentityProviderContext):
        """
        Args:
            provider_configuration (flask_pyoidc.provider_configuration.ProviderConfiguration)
        """
        self.address = address
        self.identity_provider_context = identity_provider_context
        self._client = Client(client_authn_method=CLIENT_AUTHN_METHOD)

        provider_metadata = identity_provider_context.ensure_provider_metadata()
        self._client.handle_provider_config(ProviderConfigurationResponse(**provider_metadata.to_dict()), # type: ignore
                                            provider_metadata['issuer'])

        if self.identity_provider_context.registered_client_metadata:
            client_metadata = self.identity_provider_context.registered_client_metadata.to_dict()
            registration_response = RegistrationResponse(**client_metadata)
            self._client.store_registration_info(registration_response)

        self.redirect_uri = "{0}/{1}".format(self.address.rstrip('/'), identity_provider_context.redirect_uri_endpoint)

    def is_registered(self):
        return bool(self.identity_provider_context.registered_client_metadata)

    def register(self, extra_registration_params=None):
        client_metadata = self.identity_provider_context.register_client([self.redirect_uri], extra_registration_params)
        logger.debug('client registration response: %s', client_metadata)
        self._client.store_registration_info(RegistrationResponse(**client_metadata.to_dict()))

    def authentication_request(self, state, nonce, extra_auth_params):
        """

        :param state:
        :param nonce:
        :param extra_auth_params:
        Returns:
            str: Authentication request as a URL to redirect the user to the provider.
        """
        args = {
            'client_id': self._client.client_id,
            'response_type': 'code',
            'scope': ['openid'],
            'redirect_uri': self.redirect_uri,
            'state': state,
            'nonce': nonce,
        }

        args.update(self.identity_provider_context.auth_request_params)
        args.update(extra_auth_params)
        auth_request = self._client.construct_AuthorizationRequest(request_args=args)
        logger.debug('sending authentication request: %s', auth_request.to_json())

        return auth_request.request(self._client.authorization_endpoint)

    def parse_authentication_response(self, response_params):
        """
        Args:
            response_params (Mapping[str, str]): authentication response parameters
        Returns:
            Union[AuthorizationResponse, AuthorizationErrorResponse]: The parsed authorization response
        """
        auth_resp = self._parse_response(response_params, AuthorizationResponse, AuthorizationErrorResponse)
        if 'id_token' in response_params:
            auth_resp['id_token_jwt'] = response_params['id_token']
        return auth_resp

    def token_request(self, authorization_code):
        """
        Makes a token request.  If the 'token_endpoint' is not configured in the provider metadata, no request will
        be made.

        Args:
            authorization_code (str): authorization code issued to client after user authorization

        Returns:
            Union[AccessTokenResponse, TokenErrorResponse, None]: The parsed token response, or None if no token
            request was performed.
        """
        if not self._client.token_endpoint:
            return None

        request = {
            'grant_type': 'authorization_code',
            'code': authorization_code,
            'redirect_uri': self.redirect_uri
        }

        logger.debug('making token request: %s', request)
        client_auth_method = self._client.registration_response.get('token_endpoint_auth_method', 'client_secret_basic')
        auth_header = _ClientAuthentication(self._client.client_id, self._client.client_secret)(client_auth_method,
                                                                                                request)
        resp = self.identity_provider_context.requests_session \
            .post(self._client.token_endpoint,
                  data=request,
                  headers=auth_header) \
            .json()
        logger.debug('received token response: %s', json.dumps(resp))

        token_resp = self._parse_response(resp, AccessTokenResponse, TokenErrorResponse)
        if 'id_token' in resp:
            token_resp['id_token_jwt'] = resp['id_token']
        if 'refresh_token' in resp:
            token_resp['refresh_token'] = resp['refresh_token']

        return token_resp

    def userinfo_request(self, access_token):
        """
        Args:
            access_token (str): Bearer access token to use when fetching userinfo

        Returns:
            oic.oic.message.OpenIDSchema: UserInfo Response
        """
        http_method = self.identity_provider_context.userinfo_endpoint_method
        if not access_token or http_method is None or not self._client.userinfo_endpoint:
            return None

        logger.debug('making userinfo request')
        userinfo_response = self._client.do_user_info_request(method=http_method, token=access_token)
        logger.debug('received userinfo response: %s', userinfo_response.to_json())

        return userinfo_response

    @property
    def session_refresh_interval_seconds(self):
        return self.identity_provider_context.session_refresh_interval_seconds

    @property
    def provider_end_session_endpoint(self):
        provider_metadata = self.identity_provider_context.ensure_provider_metadata()
        return provider_metadata.get('end_session_endpoint')

    @property
    def post_logout_redirect_uris(self):
        return self._client.registration_response.get('post_logout_redirect_uris')

    def _parse_response(self, response_params, success_response_cls, error_response_cls):
        if 'error' in response_params:
            response = error_response_cls(**response_params)
        else:
            response = success_response_cls(**response_params)
            response.verify(keyjar=self._client.keyjar)
        return response