简体   繁体   English

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

[英]Custom claims in JWT token in ASP.NET Core 2.0 api

In asp.net core web api, how can I retrieve custom user properties for a JWT token? 在asp.net核心Web API中,如何检索JWT令牌的自定义用户属性?

I can authenticate using this tutorial https://fullstackmark.com/post/13/jwt-authentication-with-aspnet-core-2-web-api-angular-5-net-core-identity-and-facebook-login , but would like to show the users full name and link to their profile pic in the header of my site. 我可以使用本教程https://fullstackmark.com/post/13/jwt-authentication-with-aspnet-core-2-web-api-angular-5-net-core-identity-and-facebook-login进行身份验证,但想在我的网站标题中显示用户的全名并链接到他们的个人资料照片。

I've extended the AppUser model to include these fields and they are being saved in the database. 我已经扩展了AppUser模型,以包括这些字段,它们被保存在数据库中。

From the JWT token, I can get the users id or email and then do a database looked up get their full name and profile picture, but thought it would be more efficient to get this as a custom claim, although I don't know how to do that. 从JWT令牌中,我可以获取用户ID或电子邮件,然后查找数据库以获取其全名和个人资料图片,但我认为将其作为自定义声明会更有效,尽管我不知道如何要做到这一点。

This is my startup.cs 这是我的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();

    }


}

If you followed the link, under the web api for // POST api/auth/login , you find the following line: 如果您点击了链接,则在// POST api/auth/login的Web api下,您会找到以下行:

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

This generates the identity that is later used in the token. 这将生成稍后在令牌中使用的身份。 Here you can add your own claims: 您可以在此处添加自己的声明:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.Net Core 3.0 JWT Bearer Token 没有可用的 SecurityTokenValidator - ASP.Net Core 3.0 JWT Bearer Token No SecurityTokenValidator available jwt令牌到期时间(asp.net核心) - jwt token expiration time (asp.net core) 带有ASP.NET Core 2.0的Angular 4在JWT(CORS)上返回了401错误 - Angular 4 with ASP.NET Core 2.0 is giving back 401 error on JWT (CORS) Jwt 和 ASP.NET CORE 授权 AspNetRoleClaims - Jwt and ASP.NET CORE Authorization AspNetRoleClaims 在 angular 6 的 asp.net 核心中一次性使用 Jwt 令牌进行电子邮件验证 - Single time use Jwt Token for email verification in asp.net core with angular 6 ASP.NET 4.5 Web API 2.0,JWT消息处理程序将状态0返回到Angular 7 HTTP拦截器 - ASP.NET 4.5 Web API 2.0, JWT Message Handler Returns Status 0 to Angular 7 HTTP Interceptors 在Angular ASP.NET Core 2.0应用程序中使用LinkedIn api和Oauth 2.0进行身份验证 - Authentication with LinkedIn api and Oauth 2.0 in Angular ASP.NET Core 2.0 Application ASP.NET Core 2.0 (Angular) 到 CloudFoundry - ASP.NET Core 2.0 (Angular) to CloudFoundry 如何使用EF Core处理ASP.NET Core 2.0分块式Web Api调用 - How to deal with ASP.NET Core 2.0 Chunked Web Api Call with EF Core 来自ionic 3的ASP.NET Core 2.0 Web API接收/发送Json请求 - ASP.NET Core 2.0 Web API Receiving/Sending Json requests from ionic 3
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM