|
| 1 | +"""This OAuth2 client implementation aims to be spec-compliant, and generic.""" |
| 2 | +# OAuth2 spec https://tools.ietf.org/html/rfc6749 |
| 3 | + |
| 4 | +try: |
| 5 | + from urllib.parse import urlencode, parse_qs |
| 6 | +except ImportError: |
| 7 | + from urlparse import parse_qs |
| 8 | + from urllib import urlencode |
| 9 | + |
| 10 | +import requests |
| 11 | + |
| 12 | + |
| 13 | +class Client(object): |
| 14 | + # This low-level interface works. Yet you'll find those *Grant sub-classes |
| 15 | + # more friendly to remind you what parameters are needed in each scenario. |
| 16 | + def __init__( |
| 17 | + self, client_id, |
| 18 | + client_credential=None, # Only needed for Confidential Client |
| 19 | + authorization_endpoint=None, token_endpoint=None): |
| 20 | + self.client_id = client_id |
| 21 | + self.client_credential = client_credential |
| 22 | + self.authorization_endpoint = authorization_endpoint |
| 23 | + self.token_endpoint = token_endpoint |
| 24 | + |
| 25 | + def authorization_url(self, response_type, **kwargs): |
| 26 | + params = {'client_id': self.client_id, 'response_type': response_type} |
| 27 | + params.update(kwargs) |
| 28 | + params = {k: v for k, v in params.items() if v is not None} # clean up |
| 29 | + sep = '&' if '?' in self.authorization_endpoint else '?' |
| 30 | + return "%s%s%s" % (self.authorization_endpoint, sep, urlencode(params)) |
| 31 | + |
| 32 | + def get_token(self, grant_type, **kwargs): |
| 33 | + data = {'client_id': self.client_id, 'grant_type': grant_type} |
| 34 | + data.update(kwargs) |
| 35 | + # We don't need to clean up None values here, because requests lib will. |
| 36 | + |
| 37 | + # Quoted from https://tools.ietf.org/html/rfc6749#section-2.3.1 |
| 38 | + # Clients in possession of a client password MAY use the HTTP Basic |
| 39 | + # authentication. |
| 40 | + # Alternatively, (but NOT RECOMMENDED,) |
| 41 | + # the authorization server MAY support including the |
| 42 | + # client credentials in the request-body using the following |
| 43 | + # parameters: client_id, client_secret. |
| 44 | + auth = None |
| 45 | + if self.client_credential and not 'client_secret' in data: |
| 46 | + auth = (self.client_id, self.client_credential) # HTTP Basic Auth |
| 47 | + |
| 48 | + resp = requests.post( |
| 49 | + self.token_endpoint, headers={'Accept': 'application/json'}, |
| 50 | + data=data, auth=auth) |
| 51 | + if resp.status_code>=500: |
| 52 | + resp.raise_for_status() # TODO: Will probably retry here |
| 53 | + # The spec (https://tools.ietf.org/html/rfc6749#section-5.2) says |
| 54 | + # even an error response will be a valid json structure, |
| 55 | + # so we simply return it here, without needing to invent an exception. |
| 56 | + return resp.json() |
| 57 | + |
| 58 | + |
| 59 | +class AuthorizationCodeGrant(Client): |
| 60 | + |
| 61 | + def authorization_url( |
| 62 | + self, redirect_uri=None, scope=None, state=None, **kwargs): |
| 63 | + """Generate an authorization url to be visited by resource owner. |
| 64 | +
|
| 65 | + :param response_type: MUST be set to "code" or "token". |
| 66 | + :param scope: It is a space-delimited, case-sensitive string. |
| 67 | + Some ID provider can accept empty string to represent default scope. |
| 68 | + """ |
| 69 | + return super(AuthorizationCodeGrant, self).authorization_url( |
| 70 | + 'code', redirect_uri=redirect_uri, scope=scope, state=state, |
| 71 | + **kwargs) |
| 72 | + # Later when you receive the response at your redirect_uri, |
| 73 | + # validate_authorization() may be handy to check the returned state. |
| 74 | + |
| 75 | + def get_token(self, code, redirect_uri=None, client_id=None, **kwargs): |
| 76 | + """Get an access token. |
| 77 | +
|
| 78 | + See also https://tools.ietf.org/html/rfc6749#section-4.1.3 |
| 79 | +
|
| 80 | + :param code: The authorization code received from authorization server. |
| 81 | + :param redirect_uri: |
| 82 | + Required, if the "redirect_uri" parameter was included in the |
| 83 | + authorization request, and their values MUST be identical. |
| 84 | + :param client_id: Required, if the client is not authenticating itself. |
| 85 | + See https://tools.ietf.org/html/rfc6749#section-3.2.1 |
| 86 | + """ |
| 87 | + return super(AuthorizationCodeGrantFlow, self).get_token( |
| 88 | + 'authorization_code', code=code, |
| 89 | + redirect_uri=redirect_uri, client_id=client_id, **kwargs) |
| 90 | + |
| 91 | + |
| 92 | +def validate_authorization(params, state=None): |
| 93 | + """A thin helper to examine the authorization being redirected back""" |
| 94 | + if not isinstance(params, dict): |
| 95 | + params = parse_qs(params) |
| 96 | + if params.get('state') != state: |
| 97 | + raise ValueError('state mismatch') |
| 98 | + return params |
| 99 | + |
| 100 | + |
| 101 | +class ImplicitGrant(Client): |
| 102 | + # This class is only for illustrative purpose. |
| 103 | + # You probably won't implement your ImplicitGrant flow in Python anyway. |
| 104 | + def authorization_url(self, redirect_uri=None, scope=None, state=None): |
| 105 | + return super(ImplicitGrant, self).authorization_url('token', **locals()) |
| 106 | + |
| 107 | + def get_token(self): |
| 108 | + raise NotImplemented("Token is already issued during authorization") |
| 109 | + |
| 110 | + |
| 111 | +class ResourceOwnerPasswordCredentialsGrant(Client): |
| 112 | + |
| 113 | + def authorization_url(self, **kwargs): |
| 114 | + raise NotImplemented( |
| 115 | + "You should have already obtained resource owner's password") |
| 116 | + |
| 117 | + def get_token(self, username, password, scope=None, **kwargs): |
| 118 | + return super(ResourceOwnerPasswordCredentialsGrant, self).get_token( |
| 119 | + "password", username=username, password=password, scope=scope, |
| 120 | + **kwargs) |
| 121 | + |
| 122 | + |
| 123 | +class ClientCredentialGrant(Client): |
| 124 | + def authorization_url(self, **kwargs): |
| 125 | + # Since the client authentication is used as the authorization grant |
| 126 | + raise NotImplemented("No additional authorization request is needed") |
| 127 | + |
| 128 | + def get_token(self, scope=None, **kwargs): |
| 129 | + return super(ClientCredentialGrant, self).get_token( |
| 130 | + "client_credentials", scope=scope, **kwargs) |
| 131 | + |
0 commit comments