ASP.net Core 2自定义身份验证(IsAuthenticated = false)

时间:2018-07-27 17:04:46

标签: c# asp.net-core

我正在寻找一个最小的示例,以基于API密钥的C#语言编写的asp.net core 2的自定义身份验证。

Mircosoft对于使用Cookie做到这一点非常documentation,但这不是我想要的。由于我想使用API​​密钥(由http-header,GET或Cookie提供,...),因此我从未致电HttpContext.SignInAsync,这也许是我找不到/搜索到的Google问题。

我构建了一个简单的AuthenticationHandler(基于this-因为我读到自定义中间件已经不行了),它看起来像这样:

internal class CustomAuthHandler : AuthenticationHandler<CustomAuthOptions>
{
    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        // parse cookies to find APIKEY
        if(Context.Request.Cookies.ContainsKey("APIKEY"))
        {
            string APIKEY = Request.Cookies["APIKEY"];
            // ... checking DB for APIKEY ...

            // creating claims
            var claims = new[]
            {
                new Claim( /* ... */ ),
                // ...
            };

            var claimsIdentity = new ClaimsIdentity(claims);
            var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
            var ticket = new AuthenticationTicket(claimsPrincipal, new AuthenticationProperties(), "Custom Scheme");
            return AuthenticateResult.Success(ticket); // this line gets called
        }

        return AuthenticateResult.NoResult();
    }
}

但是当我有一个仅具有[Authorize]属性的API端点时,DenyAnonymousAuthorizationRequirement拒绝该请求是因为不允许用户(因为IsAuthenticated == false是只读的,所有声明均正确显示)

1 个答案:

答案 0 :(得分:0)

var claimsIdentity = new ClaimsIdentity(claims);更改为var claimsIdentity = new ClaimsIdentity(claims, "Password");(当然,使用最适合您情况的AuthenticationType代替“密码”。

此处有类似问题:Why is my ClaimsIdentity IsAuthenticated always false (for web api Authorize filter)?