【问题标题】:ASP.NET Core. How can i create an auth cookie without an identity user account?ASP.NET 核心。如何在没有身份用户帐户的情况下创建身份验证 cookie?
【发布时间】:2021-02-07 10:19:17
【问题描述】:

我的应用创建了一个Guid 事件令牌

客户像这样访问事件的 url。 https://example.com/event/a3b2e538-e87c-4444-a655-5171f263ac70

然后客户被重定向到登录表单以提供活动密码。

如果密码匹配事件令牌客户将能够看到该事件。 我可以在没有身份用户帐户的情况下完成此操作吗? (在这种情况下,我不希望遵循经典的用户身份登录方法)。

也许像创建一个 auth cookie 并在即将到来的请求中使用它。

[HttpPost]
[Route("validate/{code}")]
public IActionResult Cookie(string code)
{
    var user = true;  //Validate event token against event password supplied by user 
    if (user == true)
    {
        var ident = _userManager.CreateAuthCookie(user, DefaultAuthenticationTypes.ApplicationCookie);

        HttpContext.GetOwinContext().Authentication.SignIn(new AuthenticationProperties { IsPersistent = false }, ident);
        
        return Redirect("Wherever");
    }
    ModelState.AddModelError("", "Invalid login attempt");
    return View();
}

【问题讨论】:

  • 目标是创建一个身份验证令牌,对吧?可以通过验证 GUID 或身份用户帐户来实现。
  • @MiteshPrajapati 实际上不会有用户帐户。目标是使用用户提供的 url 令牌和密码创建一个 auth cookie(如果该组合匹配)
  • 您可以创建 JWT 令牌,而不是设置 GUID,您可以将所有信息放入其中。在登录而不是针对数据库进行验证时,您可以针对 JWT 令牌进行验证,如果所有内容都得到验证,则创建实际的身份验证令牌。
  • 我当然希望您不要在code...中以纯文本形式发送密码...

标签: c# asp.net-mvc asp.net-core


【解决方案1】:

我想,我明白你的意思。您想创建一个自定义的 Owin 身份验证框架。使用 JWT 令牌可以实现相同的目的。它比 OWIN Authentication 更有优势。

但是如果你想使用 OWIN 设计这样的东西,请注意这些:

  • 首先也是最重要的一点,url 中传递的参数不应该有任何密码或敏感值。 URL 令牌应该被编码(编码你可以参考https://www.nuget.org/packages/Microsoft.Owin.Security/)并且编码的令牌可以携带这个信息。在编码时,您可以对一些 ID(不是电子邮件地址)、一些 sourcecd(告诉令牌来自有效来源)、一些时间限制以及该令牌有效的次数进行编码。

现在,当您收到对 API 端点的调用时,您可以解码该令牌、验证然后提取该 someID,并调用您的数据库以了解用户是否有效。

重要:编码和解码算法在这里起着非常重要的作用。因此,您的编码和解码令牌不应暴露在任何地方。

如果他是有效用户,则创建一个 claimIdentity 对象。

ClaimsIdentity identity = new ClaimsIdentity();
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, identity.FindFirst("sub").Value));
identity.AddClaim(new Claim("Name", <<add your claims like this>>));
identity = new ClaimsIdentity(identity.Claims, "ApplicationCookie");

AuthenticationProperties properties = new AuthenticationProperties();
AuthenticationManager.SignIn(properties, identity);

在您的控制器或单独的文件中设置身份验证类对象:

using Microsoft.Owin.Security;

        private IAuthenticationManager authenticationManager;
        public IAuthenticationManager AuthenticationManager
        {
            get
            {
                if (authenticationManager == null)
                    authenticationManager = HttpContext.GetOwinContext().Authentication;
                return authenticationManager;
            }
            set { authenticationManager = value; }
        }

您还应该在中间层中配置 OWIN 层。您可以基于 .Net framework 或 .Net Core 配置 OWIN 中间层

【讨论】:

    猜你喜欢
    • 2014-08-09
    • 2021-06-26
    • 1970-01-01
    • 2011-01-10
    • 2023-02-02
    • 2018-06-17
    • 1970-01-01
    • 1970-01-01
    • 2015-10-09
    相关资源
    最近更新 更多