OpenIddict:如何手动检查访问令牌并获取身份
OpenIddict: How to manually check access token and get identity
我正在为 authentication/authorization 使用 OpenIddict。
我需要手动检查访问令牌并获取该令牌背后的用户 (ClaimsPrincipal)。怎么样?
用例:
我正在使用 SignalR。在来自客户端的每个方法调用中,我想检查用户是否已通过身份验证。我的计划是从 Angular 发送访问令牌并在 Hub 方法中检查它。当我在 Controller.
上使用 [Authorize]
属性时,必须发生基本上相同的事情
假设这个问题与有关,我不建议您自己解密 OpenIddict 发布的不透明访问令牌。
如果你真的想自己做,你可以用OpenIddict使用的ASP.NET核心数据保护"purpose strings"手动实例化一个TicketDataFormat
实例:
// 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");
我正在为 authentication/authorization 使用 OpenIddict。
我需要手动检查访问令牌并获取该令牌背后的用户 (ClaimsPrincipal)。怎么样?
用例:
我正在使用 SignalR。在来自客户端的每个方法调用中,我想检查用户是否已通过身份验证。我的计划是从 Angular 发送访问令牌并在 Hub 方法中检查它。当我在 Controller.
[Authorize]
属性时,必须发生基本上相同的事情
假设这个问题与
如果你真的想自己做,你可以用OpenIddict使用的ASP.NET核心数据保护"purpose strings"手动实例化一个TicketDataFormat
实例:
// 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");