ASP.NET Core 1.0。 Bearer Token,无法访问自定义声明

时间:2016-01-27 13:02:26

标签: authentication asp.net-core jwt bearer-token aspnet-contrib

我尝试使用ASP.NET Core 1.0为SPA设置承载身份验证。我几乎已经使用OpenIdConnect服务器为JwtToken工作,但是有一个问题是我的自定义声明没有随令牌一起返回。

我的Startup.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都是成功生成的,当在Authorization标头系统中传递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;
}

我的声明未从令牌传递或提取的原因是什么?

1 个答案:

答案 0 :(得分:2)

  

我的声明未从令牌传递或提取的原因是什么?

安全。

OAuthAuthorizationServerMiddleware不同,ASOS不会假设访问令牌始终由您自己的资源服务器使用(尽管我同意这是常见的情况)并且拒绝序列化未明确指定“目标”的声明避免将机密数据泄露给未授权方。

由于JWT是ASOS beta4(but not in the next beta)中的默认格式,您还必须记住,即使是客户端应用程序(或用户)也可以读取您的访问令牌。

因此,您必须在声明中明确附加“目的地”:

identity.AddClaim(ClaimTypes.Name, "Pinpoint", destination: "id_token token");

指定id_token以序列化身份令牌中的声明,token以在访问令牌中对其进行序列化,或两者都将其序列化为两个令牌(没有等效的授权码或刷新令牌,因为它们始终是加密的,只有授权服务器本身才能读取)

相关问题