(OK – I only included OAuth2 in the title to get your attention – this applies to whatever framework or technology you use to work with JSON web tokens aka JWTs)
For validating a JWT you need to specify three items:
- The name of the issuer that you expect the JWT to come from (an identity provider or authorization server)
- The expected audience (a symbolic name of the service consuming the JWT)
- The key material to validate the signature (either a symmetric key or a X.509 certificate)
The following method adds a mapping for an incoming Authorization header with a scheme of Bearer – the response will also contain the Bearer scheme. The key used is a symmetric key:
The current extension methods of IdentityModel uses my own JWT implementation – but in the sample (as well as in the latest IdentityServer version) I have already switched to Microsoft’s JWT handler. The signature of the extension methods stay the same.
Given the flexibility of the AuthenticationHandler, you can also fetch the JWT from other places like an alternative header or a query string. Another emerging pattern is to return the audience of the service and the URL of the token endpoint in the 401 response – again – easy to accomplish: