.Net Core 2.0授权总是返回401

时间:2018-01-22 13:15:50

标签: c# authentication asp.net-core asp.net-core-2.0

[Authorize]添加到控制器之后,我总是从中获得401。在调试时,我看到return AuthenticateResult.Success已到达,但控制器的代码永远不会 我做错了什么?

以下是我的Startup类和Custom auth类的代码。

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // ...

        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy", builder => builder
                .AllowAnyHeader()
                .AllowAnyMethod()
                .AllowAnyOrigin()
                .AllowCredentials());
        });

        services.Configure<MvcOptions>(options =>
        {
            options.Filters.Add(new RequireHttpsAttribute());
        });

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = "Custom Scheme";
            options.DefaultChallengeScheme = "Custom Scheme";
        }).AddCustomAuth(o => { });

        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseCors("CorsPolicy");

        var options = new RewriteOptions().AddRedirectToHttps();
        app.UseRewriter(options);

        app.UseAuthentication();

        app.UseMvc();
    }
}
public class CustomAuthOptions : AuthenticationSchemeOptions
{
    public ClaimsIdentity Identity { get; set; }

    public CustomAuthOptions()
    {

    }
}

public static class CustomAuthExtensions
{
    public static AuthenticationBuilder AddCustomAuth(this AuthenticationBuilder builder, Action<CustomAuthOptions> configureOptions)
    {
        return builder.AddScheme<CustomAuthOptions, CustomAuthHandler>("Custom Scheme", "Custom Auth", configureOptions);
    }
}

internal class CustomAuthHandler : AuthenticationHandler<CustomAuthOptions>
{
    public CustomAuthHandler(IOptionsMonitor<CustomAuthOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
    {

    }

    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        string token = Request.Headers["Authorization"];
        if (string.IsNullOrEmpty(token))
            return AuthenticateResult.Fail("Failing string");

        // Using external service to validate token and get user id
        int Id = GetUserId(token);

        return AuthenticateResult.Success(
            new AuthenticationTicket(
                new ClaimsPrincipal(
                    new ClaimsIdentity(
                        new List<Claim>() { new Claim(ClaimTypes.Sid, Id.ToString()) })),
                        Scheme.Name));
    }
}

1 个答案:

答案 0 :(得分:7)

问题是由ClaimsIdentityCustomAuthHandler.HandleAuthenticateAsync()的实例创建方式引起的。 principal.Identity.IsAuthenticated的值为false,使AuthorizeAttribute无需考虑您的请求。

详细描述了IsAuthenticated设置为false的原因here。要修复它,只需使用ClaimsIdentity

authenticationType构造函数重载
return AuthenticateResult.Success(
    new AuthenticationTicket(
        new ClaimsPrincipal(
            new ClaimsIdentity(
                new List<Claim>() { new Claim(ClaimTypes.Sid, Id.ToString()) }, Scheme.Name)),
        Scheme.Name));