Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 

61 rinda
2.0 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright 2017 Gehirn Inc.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import json
  17. from typing import AbstractSet
  18. from .exceptions import (
  19. JWSEncodeError,
  20. JWSDecodeError,
  21. JWTEncodeError,
  22. JWTDecodeError,
  23. )
  24. from .jwk import AbstractJWKBase
  25. from .jws import JWS
  26. class JWT:
  27. def __init__(self):
  28. self._jws = JWS()
  29. def encode(self, payload: dict, key: AbstractJWKBase = None, alg='HS256',
  30. optional_headers: dict = None) -> str:
  31. try:
  32. message = json.dumps(payload).encode('utf-8')
  33. except ValueError as why:
  34. raise JWTEncodeError('payload must be able to encode in JSON')
  35. optional_headers = optional_headers and optional_headers.copy() or {}
  36. optional_headers['typ'] = 'JWT'
  37. try:
  38. return self._jws.encode(message, key, alg, optional_headers)
  39. except JWSEncodeError as why:
  40. raise JWTEncodeError('failed to encode to JWT') from why
  41. def decode(self, message: str, key: AbstractJWKBase = None,
  42. do_verify=True, algorithms: AbstractSet[str]=None) -> dict:
  43. try:
  44. message_bin = self._jws.decode(message, key, do_verify, algorithms)
  45. except JWSDecodeError as why:
  46. raise JWTDecodeError('failed to decode JWT') from why
  47. try:
  48. payload = json.loads(message_bin.decode('utf-8'))
  49. return payload
  50. except ValueError as why:
  51. raise JWTDecodeError(
  52. 'a payload of the JWT is not valid JSON') from why