0

I am using OpenIddict for authentication/authorization.
I need to manually check access token and get user (ClaimsPrincipal) behind that token. How?

Use case:
I am using SignalR. On every method call from client I would like to check if user is authenticated. My plan is to send access token from Angular and check it in Hub method. Basically same thing must happened when I use [Authorize] attribute on Controller.

Kévin Chalet
  • 39,509
  • 7
  • 121
  • 131
Makla
  • 9,899
  • 16
  • 72
  • 142

1 Answers1

2

Assuming this question is related to How to authorize SignalR Core Hub method with JWT, I wouldn't recommend decrypting the opaque access tokens issued by OpenIddict yourself.

If you really want to do it yourself, you can manually instantiate a TicketDataFormat instance with the ASP.NET Core Data Protection "purpose strings" used by OpenIddict:

// Resolve the data protection provider from the DI container.
// Depending on where this snippet is used, you must be able
// to directly use constructor injection (e.g in a controller).
var provider = app.ApplicationServices.GetRequiredService<IDataProtectionProvider>();

var protector = provider.CreateProtector(
    nameof(OpenIdConnectServerHandler),
    nameof(OpenIdConnectServerOptions.AccessTokenFormat),
    OpenIdConnectServerDefaults.AuthenticationScheme);

var format = new TicketDataFormat(protector);

// If the access token is not malformed, a non-null value
// is returned. Note that you'll have to manually validate
// the expiration date and the audience of the ticket.
var ticket = format.Unprotect("your access token");
Kévin Chalet
  • 39,509
  • 7
  • 121
  • 131
  • Could you please provide update for openiddict version 3? Current implementation works for version 2 only – Andrew Jun 08 '22 at 19:31