ASP.NET Core 使用带有 cookieauthentication 的自定义身份验证处理程序

sev*_*rin 6 c# asp.net security authentication asp.net-core

我正在尝试创建自己的 AuthenticationHandler 并与 cookie 身份验证一起使用:

services.AddAuthentication(options =>
  {
  options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
  options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
  options.DefaultChallengeScheme = MyAuth.Scheme;
  })
  .AddCookie()
  .AddScheme<MyAuthenticationOptions, MyAuthenticationHandler>(MyAuth.Scheme, "My auth scheme", options => { });
Run Code Online (Sandbox Code Playgroud)

.

public MyAuthenticationHandler(...) : base(...) {}

    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        throw new NotImplementedException();  
    }    

    protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
    {                     
        var myUser = await DoAuth();

        if (!myUser.IsAuthenticated)
        {
            if (Context.Request.Query.ContainsKey("isRedirectedFromSSO"))
            {
                Context.Response.Redirect("/unauthorized");
                return;
            }
            else
            {
                Context.Response.Redirect("url to sso");
                return;
            }              
        }    

        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.NameIdentifier, user.Username),            
        };

        var identity = new ClaimsIdentity(claims, MyAuth.Scheme);
        var claimsPrincipal = new ClaimsPrincipal(identity);

        var authProperties = new AuthenticationProperties {};

        await Context.SignInAsync(
            CookieAuthenticationDefaults.AuthenticationScheme,
            claimsPrincipal,
            authProperties);

        Context.Response.Redirect(Request.GetEncodedUrl());
    }
}
Run Code Online (Sandbox Code Playgroud)
  1. 如果存在有效的身份验证 cookie,则使用该身份验证
  2. 如果没有有效的身份验证 cookie,请使用我的身份验证进行挑战,如果成功则创建一个身份验证 cookie

这在实践中有效,但我发现它有点奇怪,我正在执行实际的身份验证HandleChallenge并在失败时重定向。从另一个 (MyAuthenticationHandler) 调用一个 AuthenticationHandler (cookie) 对我来说也很奇怪。

我怎样才能正确设置它以便我在做实现HandleAuthenticate 在我当前的实现中,该方法实际上从未被调用过。

另外,可以从另一个调用一个身份验证处理程序吗?

PS 我已经查看了其他几篇文章和文章(包括这篇这篇这篇),但我无法通过查看它们来找到我的问题的答案。任何帮助,将不胜感激。

Joh*_*nes 5

我认为您所追求的可能会通过 ASP.NET Core 2.1 中的一些新部分来解决

<PackageReference Include="Microsoft.AspNetCore.Authentication" Version="2.1.0-rc1-final" />

以下是如何根据 httpcontext 数据“选择”身份验证方案的示例:

builder.AddPolicyScheme("scheme", "scheme", opts =>
{
    opts.ForwardDefaultSelector = ctx =>
    {
        if (ctx.Request.Query.ContainsKey("isRedirectedFromSSO"))
        {               
            return null; // or ctx.ForbidAsync(), not sure here.
        }

        return OpenIdConnectDefaults.AuthenticationScheme; // or your own sso scheme, whatever it may be here.
    };
})
.AddCookie()
.AddOpenIdConnect();
Run Code Online (Sandbox Code Playgroud)

看看这个 GitHub 线程