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

标签 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 => { });

.

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());
    }
}
  1. 如果存在有效的身份验证 cookie,则使用该身份验证
  2. 如果没有有效的 auth cookie,使用我的 auth 进行挑战,如果成功则创建一个 auth cookie

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

我如何才能正确设置它,以便我在 HandleAuthenticate 中执行实现? 在我当前的实现中,该方法实际上从未被调用过。

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

附言我查看了其他几篇文章和文章(包括 thisthisthis ),但无法从中找到问题的答案。任何帮助将不胜感激。

最佳答案

我认为您所追求的可以通过 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();

看看this GitHub thread .

关于c# - ASP.NET Core 使用带有 cookieauthentication 的自定义身份验证处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50370935/

相关文章:

asp.net - 使用 ASP.NET 备份 SQL Server

c# - 在 asp.net mvc 中执行 Powershell 和 Powercli 命令时如何设置超时

asp.net - 将数据从数据集绑定(bind)到 <asp :Table>

regex - 从文件中读取正则表达式是否安全?

c# - 在 MVC C# 中关闭了 html 条件编译

c# - 为什么可空的模式匹配会导致语法错误?

c# - 可以同时使用两个windows phone 摄像头吗?

c# - 编写分页的通用方法

security - 我怎样才能在我的安全站点上获得那个巨大的安全图标?

Android - 连接 MySQL 数据库的最安全方式