[Authorize] 添加到 Controller 后,我总是从中得到 401。在调试时,我看到 return AuthenticateResult.Success 被到达,但 Controller 的代码从来没有。
我究竟做错了什么?

下面是我的 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));
    }
}

最佳答案

该问题是由您在 ClaimsIdentity 中创建 CustomAuthHandler.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));

关于c# - .Net Core 2.0 授权总是返回 401,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48382456/

10-15 09:29