在 Identity Server 4 中验证 JWT 持有者令牌

Validate the JWT Bearer Token In Identity Server 4

我有一个基于 IdentityServer 4 的 Identity Server 运行,我有一个 ASP.NET WebAPI 内置 ASP.Net Core Web API。我在身份服务器的 /connect/token 端点上成功登录。我想检查在我的 API 请求的 header 中发送的 JWT 不记名令牌的有效性。

这是我启动API项目中的配置:

在配置服务中:

services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
        .AddIdentityServerAuthentication(options =>
        {
            //base-address of my identityserver
            options.Authority = "https://localhost:5000/";

            //name of the API resource
            options.ApiName = "API_Resource_Name";
            });

在配置中:

 app.UseAuthentication();

注意: 我已将授权注释添加到我的控制器

为您的 API Startup.cs ConfigureServices 添加身份验证和授权:

            services.AddAuthentication("bearer")
            .AddJwtBearer("bearer", options =>
            {
                options.Authority = Configuration["Authority"];                    
                options.Events = new Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {

                        var accessToken = context.Request.Query["access_token"];

                        var path = context.HttpContext.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/chathub")))
                        {
                            context.Token = accessToken;
                        }
                        return Task.CompletedTask;
                    },
                    OnTokenValidated = context =>
                    {
                        var token = context.SecurityToken as JwtSecurityToken;
                        if (token != null)
                        {
                            ClaimsIdentity identity = context.Principal.Identity as ClaimsIdentity;
                            if (identity != null)
                            {
                                identity.AddClaim(new Claim("access_token", token.RawData));
                            }
                        }

                        return Task.CompletedTask;
                    }
                };

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience = false,
                    NameClaimType = "name",
                    RoleClaimType = "role"
                };
            });

然后...

services.AddAuthorization(options =>
        {
            options.AddPolicy("ApiScope", policy =>
            {
                policy.RequireAuthenticatedUser();
                policy.RequireClaim("scope", "SignalR.API");
            });
        });

内部配置...

app.UseAuthentication();
app.UseAuthorization();