问题描述
我的应用创建了一个Guid
事件令牌
客户如此访问事件的网址。 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();
}
解决方法
我想,我理解你的意思。您要创建自定义的Owin身份验证框架。使用JWT令牌可以实现相同的目的。与OWIN身份验证相比,它具有优势。
但是,如果您想使用OWIN设计类似的东西,请注意以下几点:
- 首先也是最重要的一点,URL中传递的参数不应具有任何密码或敏感值。 URL令牌应进行编码(要进行编码,您可以参考https://www.nuget.org/packages/Microsoft.Owin.Security/),并且该编码的令牌可以携带此信息。编码时,您可以编码someID(不是电子邮件地址),一些sourcecd(告诉令牌来自有效源),一些时间限制以及该令牌有效的次数。
现在,当您获得对API端点的调用时,可以解码该令牌,进行验证,然后提取该someID,然后调用您的数据库以了解用户是否有效。
重要:编码和解码算法在这里起着非常重要的作用。因此,您的编码和解码令牌不应在任何地方公开。
如果他是有效用户,则创建一个ClaimsIdentity对象。
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框架或.Net Core配置OWIN中间层