首页 > 解决方案 > 使用 AspNet.Security.OpenIdConnect.Server 的基于令牌的安全性在添加身份后停止工作

问题描述

我创建了一个小型 .NET Core 网站,允许用户使用 AspNet.Security.OpenIdConnect.Server 获取不记名令牌。它按预期工作,直到我添加services.AddDefaultIdentity<IdentityUser>();

添加身份后,日志不会显示任何令牌验证迹象,并且HttpContext.User.Identity.IsAuthenticated始终为false. 仍然会生成令牌 - 似乎只是跳过了验证。

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddAuthentication(OAuthValidationDefaults.AuthenticationScheme)
        .AddOAuthValidation(OAuthValidationDefaults.AuthenticationScheme)
        .AddOpenIdConnectServer(options =>
        {
            options.TokenEndpointPath = "/token";
            options.AllowInsecureHttp = true;
            options.ApplicationCanDisplayErrors = true;

            options.Provider.OnValidateTokenRequest = context =>
            {
                context.Validate();

                return Task.CompletedTask;
            };

            options.Provider.OnHandleTokenRequest = context =>
            {
                var identity = new ClaimsIdentity(context.Scheme.Name,
                    OpenIdConnectConstants.Claims.Name,
                    OpenIdConnectConstants.Claims.Role);

                identity.AddClaim(OpenIdConnectConstants.Claims.Subject, "[unique id]");

                var ticket = new AuthenticationTicket(
                                    new ClaimsPrincipal(identity),
                                    new AuthenticationProperties(),
                                    context.Scheme.Name);

                context.Validate(ticket);

                return Task.CompletedTask;
            };
        });

    // When the following line is uncommented the bearer token isn't validated anymore
    //services.AddDefaultIdentity<IdentityUser>();

    services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseDeveloperExceptionPage();

    app.UseAuthentication();

    app.UseStaticFiles();

    app.UseMvc();
}

一个示例控制器操作可能是这样的:

public bool Get() => HttpContext.User.Identity.IsAuthenticated;

如果我添加Authorize属性,我将收到 404:

[Authorize]
public bool Get() => HttpContext.User.Identity.IsAuthenticated;

要创建令牌,我会执行以下操作:

POST http://localhost:5005/token HTTP/1.1
User-Agent: Fiddler
Host: localhost:5005
Content-Length: 69
Content-Type: application/x-www-form-urlencoded

client_id=web&grant_type=password&username=username&password=password

带有不记名令牌的请求如下所示:

GET http://localhost:5005/customer HTTP/1.1
User-Agent: Fiddler
Host: localhost:5005
Authorization: Bearer <the token received in the previous call>

整个程序可以在这里下载: https ://gist.github.com/nielslbeck/e454cc1b79aa56948c96f4a24438b34e

标签: c#asp.net-coreasp.net-identityopenid-connect

解决方案


推荐阅读