【问题标题】:.Net Core 2.0 Authorization always returning 401.Net Core 2.0 Authorization 总是返回 401
【发布时间】:2018-07-01 03:15:33
【问题描述】:

[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));
    }
}

【问题讨论】:

  • 启用日志记录并查看内部系统在做什么,您可能会在那里看到一些有用的信息

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


【解决方案1】:

问题是由您在CustomAuthHandler.HandleAuthenticateAsync() 中创建ClaimsIdentity 实例的方式引起的。 principal.Identity.IsAuthenticated 的值将是 false,这使得 AuthorizeAttribute 认为您的请求未经授权。

IsAuthenticated 设置为 false 的原因在here 中有详细描述。要修复它,只需使用采用 authenticationTypeClaimsIdentity 构造函数重载:

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

【讨论】:

  • 感谢您的回答,我正在创建带有ClaimType.AuthenticationScheme 的声明列表,但授权失败,在搜索了很多内容后,您的答案刚刚解决了我的问题(我在 ASP .net 核心 2.1)
猜你喜欢
  • 2021-11-12
  • 2020-05-05
  • 2011-02-21
  • 2020-05-27
  • 2020-03-28
  • 2018-08-04
  • 2020-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多