decode_jwt.js 1.1 KB

1234567891011121314151617181920212223242526272829303132
  1. import { decode as base64url } from './base64url.js';
  2. import { decoder } from '../lib/buffer_utils.js';
  3. import isObject from '../lib/is_object.js';
  4. import { JWTInvalid } from './errors.js';
  5. export function decodeJwt(jwt) {
  6. if (typeof jwt !== 'string')
  7. throw new JWTInvalid('JWTs must use Compact JWS serialization, JWT must be a string');
  8. const { 1: payload, length } = jwt.split('.');
  9. if (length === 5)
  10. throw new JWTInvalid('Only JWTs using Compact JWS serialization can be decoded');
  11. if (length !== 3)
  12. throw new JWTInvalid('Invalid JWT');
  13. if (!payload)
  14. throw new JWTInvalid('JWTs must contain a payload');
  15. let decoded;
  16. try {
  17. decoded = base64url(payload);
  18. }
  19. catch {
  20. throw new JWTInvalid('Failed to base64url decode the payload');
  21. }
  22. let result;
  23. try {
  24. result = JSON.parse(decoder.decode(decoded));
  25. }
  26. catch {
  27. throw new JWTInvalid('Failed to parse the decoded payload as JSON');
  28. }
  29. if (!isObject(result))
  30. throw new JWTInvalid('Invalid JWT Claims Set');
  31. return result;
  32. }