Asp.Net Core自定义授权始终以401 Unauthorized

时间:2017-08-04 06:28:55

标签: asp.net-core asp.net-core-mvc asp.net-core-security

我正在尝试使用asp.net核心实现自定义身份验证/授权流程,但未能这样做。身份验证似乎工作正常:如果我逐步调试,我可以看到AuthenticationTicket是从ClaimsPrincipal创建的,其中包含isAuthenticated为true的身份:

public class MyAuthHandler : AuthenticationHandler<MyAuthOptions>
{
    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        // grab stuff from the HttpContext
        string authHeader = Request.Headers["Authorization"];
        // do some stuff that are successfull in my tests
        var cp = DoTokenBasedAuthentication(authHeader);

        var ticket = new AuthenticationTicket(cp,
            new AuthenticationProperties(), Options.AuthenticationScheme);
        return Task.FromResult(AuthenticateResult.Success(ticket));
    }
}

但是,我尝试在此之后添加一个伪AuthorizationHandler:

public class MyRequirement : IAuthorizationRequirement
{
    public MyRequirement()
    {
    }
}

public class MyAuthRequirement : AuthorizationHandler<MyRequirement>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MyRequirement requirement)
    {
        context.Succeed(requirement);
        return Task.CompletedTask;
    }
}

在我的启动文件中使用此代码:

services.AddAuthorization(options =>
{
   options.AddPolicy("My",
      policy => policy.Requirements.Add(new MyRequirement()));
});

但每当我在控制器上添加“[Authorize(”My“)]”时,所有调用总是返回401.而且我的AuthorizationHandler永远不会到达。 此问题看起来与Asp.Net Core policy based authorization ends with 401 Unauthorized类似,但略有不同,因为在我的情况下,我有一个经过身份验证的用户。我正在努力调试到asp.net MVC源代码,所以我真的不知道发生了什么。

1 个答案:

答案 0 :(得分:7)

Your authorization handler doesn't appear to be plugged in. You can try to add the following line to your Startup.ConfigureServices method :

services.AddSingleton<IAuthorizationHandler, MyAuthRequirement>();