我正在尝试使用 Core 1.0 为 SPA 设置持有者身份验证 ASP.NET。我几乎已经让它适用于带有OpenIdConnect Server的JwtToken,但是有一个问题,即我的自定义声明未随令牌一起返回。
我的启动.cs身份验证逻辑如下:
private void ConfigureAuthentication(IApplicationBuilder app)
{
app.UseJwtBearerAuthentication(options =>
{
options.AutomaticAuthenticate = true;
options.Authority = "http://localhost:53844";
options.Audience = "http://localhost:53844";
options.RequireHttpsMetadata = false;
});
app.UseOpenIdConnectServer(options =>
{
options.TokenEndpointPath = "/api/v1/token";
options.AllowInsecureHttp = true;
options.AuthorizationEndpointPath = PathString.Empty;
options.Provider = new OpenIdConnectServerProvider
{
OnValidateClientAuthentication = context =>
{
context.Skipped();
return Task.FromResult<Object>(null);
},
OnGrantResourceOwnerCredentials = async context =>
{
var usersService = app.ApplicationServices.GetService<IUsersService>();
User user = usersService.getUser(context.Username, context.Password);
var identity = new ClaimsIdentity(new List<Claim>(), OpenIdConnectServerDefaults.AuthenticationScheme);
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));
identity.AddClaim(new Claim(ClaimTypes.Name, user.Id.ToString()));
identity.AddClaim(new Claim("myclaim", "4815162342"));
var ticket = new AuthenticationTicket(
new ClaimsPrincipal(identity),
new AuthenticationProperties(),
context.Options.AuthenticationScheme);
ticket.SetResources(new[] { "http://localhost:53844" });
ticket.SetAudiences(new [] {"http://localhost:53844"});
ticket.SetScopes(new [] {"email", "offline_access" });
context.Validated(ticket);
}
};
});
}
access_token 和 refresh_token 都成功生成,并且在授权标头系统中传递access_token时,将请求视为已授权。
唯一的问题是,除 NameIdentifier 之外的所有声明都不会传递。
我使用以下代码接收经过身份验证的请求的声明:
public class WebUserContext : IUserContext
{
private readonly IHttpContextAccessor contextAccessor;
public WebUserContext(IHttpContextAccessor contextAccessor)
{
this.contextAccessor = contextAccessor;
}
public long UserId
{
get
{
ClaimsIdentity identity = Principal?.Identity as ClaimsIdentity;
if (identity == null)
{
return -1;
}
Claim claim = identity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name); // There is no such claim in claims collection
return long.Parse(claim.Value);
}
}
private ClaimsPrincipal Principal => contextAccessor.HttpContext.User as ClaimsPrincipal;
}
我的声明未从令牌中传递或提取的原因是什么?
我的声明未从令牌中传递或提取的原因是什么?
安全。
与OAuthAuthorizationServerMiddleware
不同,ASOS 不假设访问令牌总是由您自己的资源服务器使用(尽管我同意这是一种常见情况),并且拒绝序列化未明确指定"目的地"的声明,以避免将机密数据泄露给未经授权的各方。
由于 JWT 是 ASOS beta4 中的默认格式(但在下一个测试版中不是),您还必须记住,即使是客户端应用程序(或用户)也可以读取您的访问令牌。
因此,您必须在声明中明确附加"目标":
identity.AddClaim(ClaimTypes.Name, "Pinpoint", destination: "id_token token");
指定id_token
以序列化标识令牌中的声明,token
指定在访问令牌中序列化声明,或同时指定两者以在两个令牌中序列化声明(授权代码或刷新令牌没有等效项,因为它们始终是加密的,并且只能由授权服务器本身读取)