Eddie
Eddie

Reputation: 54421

How can a Python Microservice verify requests using a JWT in an Authorization header?

The various python libraries for OpenID 2 or OIDC seem to be focused on full web clients implemented in Python which participate in the full OAUTH2 dance for login. How can an API microservice implemented in Python and Flask validate incoming requests that have a JWT provided as a Bearer token in an Authorization header, and then pull claim information out of the JWT?

Upvotes: 1

Views: 861

Answers (2)

Kavindu Dodanduwa
Kavindu Dodanduwa

Reputation: 13069

Adding some insight from protocol perspective.

JWT validation is defined by JWT specification itself. RFC7519 JSON Web Token (JWT) contains section 7.2. Validating a JWT which specify what you must do in token receiving endpoint. I welcome you to go through it so you have correct understanding and won't create security loopholes.

Of course, language implementations are readily available as other answers. But in summary these are the steps.

  • Extract JWT parts : Header, Body and signature
  • Go through Header contents and identify JWT type and it's type (JWS vs JWE)
  • Validate signature OR validate encryption
  • Decode and read body with custom or desired validations

Once you have claims from body, it's up to you to decide. But if you are receiving OIDC ID token, then validate it against specification's guide

Upvotes: 1

see sharper
see sharper

Reputation: 12055

JWTs are actually pretty simple things, so it's fairly straightforward to write your own code for dealing with them. That said, why reinvent the wheel? I'd suggest the pyjwt library (https://pyjwt.readthedocs.io/en/latest/). Does most everything you could want.

Upvotes: 2

Related Questions