ASP.NET Core 2.0 api中JWT令牌中的自定义声明

时间:2018-01-23 03:52:52

标签: angular asp.net-core jwt

在asp.net core web api中,如何检索JWT令牌的自定义用户属性?

我可以使用本教程https://fullstackmark.com/post/13/jwt-authentication-with-aspnet-core-2-web-api-angular-5-net-core-identity-and-facebook-login进行身份验证,但希望在我网站的标题中显示用户的全名和链接到他们的个人资料照片。

我已将AppUser模型扩展为包含这些字段,并将它们保存在数据库中。

从JWT令牌中,我可以获取用户ID或电子邮件,然后查找数据库获取他们的全名和个人资料图片,但认为将此作为自定义声明更有效,尽管我不喜欢我知道该怎么做。

这是我的startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddSingleton<IConfiguration>(Configuration);
        services.AddSingleton<IJwtFactory, JwtFactory>();

        services.AddIdentity<AppUser, IdentityRole>
            (options =>
            {
                // configure identity options
                options.Password.RequireDigit = false;
                options.Password.RequireLowercase = false;
                options.Password.RequireUppercase = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequiredLength = 6;
            })
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();



        // jwt wire up
        // Get options from app settings
        var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));

        // Configure JwtIssuerOptions
        services.Configure<JwtIssuerOptions>(options =>
        {
            options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
            options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
            options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
        });

        var tokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],

            ValidateAudience = true,
            ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],

            ValidateIssuerSigningKey = true,
            IssuerSigningKey = _signingKey,

            RequireExpirationTime = false,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.Zero
        };

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

        }).AddJwtBearer(configureOptions =>
        {
            configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
            configureOptions.TokenValidationParameters = tokenValidationParameters;
            configureOptions.SaveToken = true;
        });

        // api user claim policy
        services.AddAuthorization(options =>
        {
            options.AddPolicy("ApiUser", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.ApiAccess));
        });


        services.AddMvc();

    }


}

1 个答案:

答案 0 :(得分:0)

如果您点击了// POST api/auth/login的网址后面的链接,您会找到以下内容:

var identity = await GetClaimsIdentity(credentials.UserName, credentials.Password);

这将生成稍后在令牌中使用的标识。在这里,您可以添加自己的声明:

identity.AddClaim(new Claim(ClaimTypes.Name, "the name"));