errors.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. # coding=utf-8
  2. """
  3. oauthlib.oauth2.rfc6749.errors
  4. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  5. Error used both by OAuth 2 clients and providers to represent the spec
  6. defined error responses for all four core grant types.
  7. """
  8. from __future__ import unicode_literals
  9. import json
  10. from oauthlib.common import urlencode, add_params_to_uri
  11. class OAuth2Error(Exception):
  12. error = None
  13. status_code = 400
  14. description = ''
  15. def __init__(self, description=None, uri=None, state=None, status_code=None,
  16. request=None):
  17. """
  18. description: A human-readable ASCII [USASCII] text providing
  19. additional information, used to assist the client
  20. developer in understanding the error that occurred.
  21. Values for the "error_description" parameter MUST NOT
  22. include characters outside the set
  23. x20-21 / x23-5B / x5D-7E.
  24. uri: A URI identifying a human-readable web page with information
  25. about the error, used to provide the client developer with
  26. additional information about the error. Values for the
  27. "error_uri" parameter MUST conform to the URI- Reference
  28. syntax, and thus MUST NOT include characters outside the set
  29. x21 / x23-5B / x5D-7E.
  30. state: A CSRF protection value received from the client.
  31. request: Oauthlib Request object
  32. """
  33. self.description = description or self.description
  34. message = '(%s) %s' % (self.error, self.description)
  35. if request:
  36. message += ' ' + repr(request)
  37. super(OAuth2Error, self).__init__(message)
  38. self.uri = uri
  39. self.state = state
  40. if status_code:
  41. self.status_code = status_code
  42. if request:
  43. self.redirect_uri = request.redirect_uri
  44. self.client_id = request.client_id
  45. self.scopes = request.scopes
  46. self.response_type = request.response_type
  47. self.grant_type = request.grant_type
  48. if not state:
  49. self.state = request.state
  50. def in_uri(self, uri):
  51. return add_params_to_uri(uri, self.twotuples)
  52. @property
  53. def twotuples(self):
  54. error = [('error', self.error)]
  55. if self.description:
  56. error.append(('error_description', self.description))
  57. if self.uri:
  58. error.append(('error_uri', self.uri))
  59. if self.state:
  60. error.append(('state', self.state))
  61. return error
  62. @property
  63. def urlencoded(self):
  64. return urlencode(self.twotuples)
  65. @property
  66. def json(self):
  67. return json.dumps(dict(self.twotuples))
  68. class TokenExpiredError(OAuth2Error):
  69. error = 'token_expired'
  70. class InsecureTransportError(OAuth2Error):
  71. error = 'insecure_transport'
  72. description = 'OAuth 2 MUST utilize https.'
  73. class MismatchingStateError(OAuth2Error):
  74. error = 'mismatching_state'
  75. description = 'CSRF Warning! State not equal in request and response.'
  76. class MissingCodeError(OAuth2Error):
  77. error = 'missing_code'
  78. class MissingTokenError(OAuth2Error):
  79. error = 'missing_token'
  80. class MissingTokenTypeError(OAuth2Error):
  81. error = 'missing_token_type'
  82. class FatalClientError(OAuth2Error):
  83. """Errors during authorization where user should not be redirected back.
  84. If the request fails due to a missing, invalid, or mismatching
  85. redirection URI, or if the client identifier is missing or invalid,
  86. the authorization server SHOULD inform the resource owner of the
  87. error and MUST NOT automatically redirect the user-agent to the
  88. invalid redirection URI.
  89. Instead the user should be informed of the error by the provider itself.
  90. """
  91. pass
  92. class InvalidRequestFatalError(FatalClientError):
  93. """For fatal errors, the request is missing a required parameter, includes
  94. an invalid parameter value, includes a parameter more than once, or is
  95. otherwise malformed.
  96. """
  97. error = 'invalid_request'
  98. class InvalidRedirectURIError(InvalidRequestFatalError):
  99. description = 'Invalid redirect URI.'
  100. class MissingRedirectURIError(InvalidRequestFatalError):
  101. description = 'Missing redirect URI.'
  102. class MismatchingRedirectURIError(InvalidRequestFatalError):
  103. description = 'Mismatching redirect URI.'
  104. class InvalidClientIdError(InvalidRequestFatalError):
  105. description = 'Invalid client_id parameter value.'
  106. class MissingClientIdError(InvalidRequestFatalError):
  107. description = 'Missing client_id parameter.'
  108. class InvalidRequestError(OAuth2Error):
  109. """The request is missing a required parameter, includes an invalid
  110. parameter value, includes a parameter more than once, or is
  111. otherwise malformed.
  112. """
  113. error = 'invalid_request'
  114. class MissingResponseTypeError(InvalidRequestError):
  115. description = 'Missing response_type parameter.'
  116. class AccessDeniedError(OAuth2Error):
  117. """The resource owner or authorization server denied the request."""
  118. error = 'access_denied'
  119. status_code = 401
  120. class UnsupportedResponseTypeError(OAuth2Error):
  121. """The authorization server does not support obtaining an authorization
  122. code using this method.
  123. """
  124. error = 'unsupported_response_type'
  125. class InvalidScopeError(OAuth2Error):
  126. """The requested scope is invalid, unknown, or malformed."""
  127. error = 'invalid_scope'
  128. status_code = 401
  129. class ServerError(OAuth2Error):
  130. """The authorization server encountered an unexpected condition that
  131. prevented it from fulfilling the request. (This error code is needed
  132. because a 500 Internal Server Error HTTP status code cannot be returned
  133. to the client via a HTTP redirect.)
  134. """
  135. error = 'server_error'
  136. class TemporarilyUnavailableError(OAuth2Error):
  137. """The authorization server is currently unable to handle the request
  138. due to a temporary overloading or maintenance of the server.
  139. (This error code is needed because a 503 Service Unavailable HTTP
  140. status code cannot be returned to the client via a HTTP redirect.)
  141. """
  142. error = 'temporarily_unavailable'
  143. class InvalidClientError(OAuth2Error):
  144. """Client authentication failed (e.g. unknown client, no client
  145. authentication included, or unsupported authentication method).
  146. The authorization server MAY return an HTTP 401 (Unauthorized) status
  147. code to indicate which HTTP authentication schemes are supported.
  148. If the client attempted to authenticate via the "Authorization" request
  149. header field, the authorization server MUST respond with an
  150. HTTP 401 (Unauthorized) status code, and include the "WWW-Authenticate"
  151. response header field matching the authentication scheme used by the
  152. client.
  153. """
  154. error = 'invalid_client'
  155. status_code = 401
  156. class InvalidGrantError(OAuth2Error):
  157. """The provided authorization grant (e.g. authorization code, resource
  158. owner credentials) or refresh token is invalid, expired, revoked, does
  159. not match the redirection URI used in the authorization request, or was
  160. issued to another client.
  161. """
  162. error = 'invalid_grant'
  163. status_code = 401
  164. class UnauthorizedClientError(OAuth2Error):
  165. """The authenticated client is not authorized to use this authorization
  166. grant type.
  167. """
  168. error = 'unauthorized_client'
  169. status_code = 401
  170. class UnsupportedGrantTypeError(OAuth2Error):
  171. """The authorization grant type is not supported by the authorization
  172. server.
  173. """
  174. error = 'unsupported_grant_type'
  175. class UnsupportedTokenTypeError(OAuth2Error):
  176. """The authorization server does not support the revocation of the
  177. presented token type. I.e. the client tried to revoke an access token
  178. on a server not supporting this feature.
  179. """
  180. error = 'unsupported_token_type'
  181. class FatalOpenIDClientError(FatalClientError):
  182. pass
  183. class OpenIDClientError(OAuth2Error):
  184. pass
  185. class InteractionRequired(OpenIDClientError):
  186. """The Authorization Server requires End-User interaction to proceed.
  187. This error MAY be returned when the prompt parameter value in the
  188. Authentication Request is none, but the Authentication Request cannot be
  189. completed without displaying a user interface for End-User interaction.
  190. """
  191. error = 'interaction_required'
  192. status_code = 401
  193. class LoginRequired(OpenIDClientError):
  194. """The Authorization Server requires End-User authentication.
  195. This error MAY be returned when the prompt parameter value in the
  196. Authentication Request is none, but the Authentication Request cannot be
  197. completed without displaying a user interface for End-User authentication.
  198. """
  199. error = 'login_required'
  200. status_code = 401
  201. class AccountSelectionRequried(OpenIDClientError):
  202. """The End-User is REQUIRED to select a session at the Authorization Server.
  203. The End-User MAY be authenticated at the Authorization Server with
  204. different associated accounts, but the End-User did not select a session.
  205. This error MAY be returned when the prompt parameter value in the
  206. Authentication Request is none, but the Authentication Request cannot be
  207. completed without displaying a user interface to prompt for a session to
  208. use.
  209. """
  210. error = 'account_selection_required'
  211. class ConsentRequired(OpenIDClientError):
  212. """The Authorization Server requires End-User consent.
  213. This error MAY be returned when the prompt parameter value in the
  214. Authentication Request is none, but the Authentication Request cannot be
  215. completed without displaying a user interface for End-User consent.
  216. """
  217. error = 'consent_required'
  218. status_code = 401
  219. def raise_from_error(error, params=None):
  220. import inspect
  221. import sys
  222. kwargs = {
  223. 'description': params.get('error_description'),
  224. 'uri': params.get('error_uri'),
  225. 'state': params.get('state')
  226. }
  227. for _, cls in inspect.getmembers(sys.modules[__name__], inspect.isclass):
  228. if cls.error == error:
  229. raise cls(**kwargs)