添加身份后使用AspNet.Security.OpenIdConnect.Server的基于令牌的安全性停止工作

时间:2018-12-11 20:29:41

标签: c# asp.net-core asp.net-identity openid-connect

我创建了一个小型的.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

0 个答案:

没有答案