繁体   English   中英

IIdentity,IPrincipal,OWIN,IdentityUser和IUser如何 <string> 适合在一起?

[英]How do IIdentity, IPrincipal, OWIN, IdentityUser and IUser<string> fit together?

我正在努力弄清楚哪些.Net认证概念在OWIN的世界中仍然相关,现在已经过时了。 从OWIN之前的ASP.Net时代开始,我习惯于处理.Net结构:FormsAuthentication,FormsAuthCookie,IPrincipal,IIdentity以及IPrincipal的自定义实现(继承自GenericPrincipal)。 使用最新版本的MVC(5),许多身份验证似乎已经改为基于OWIN。 我特别想要了解的两件事:

1)IPrincipal和IIdentity以及GenericPrincipal在哪里适合? 使用FormsAuthentication,自定义数据可以存储在FormsAuth cookie中。 然后,可以在ASP.Net PostAuthenticate事件中使用它来创建CustomPrincipal对象,并覆盖HTTPContext上的默认IPrincipal(下面的代码示例)。 OWIN如何(或确实)改变了这个?:

protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) 
{
    //Decrypt forms authentication cookie and retrieve some userdata        

    ...

    //Create CustomPrincipal (which inherits from GenericPrincipal)
    var principal = new CustomPrincipal(userId, roles, someAdditionalUserDataFromCookie);

    //Replace standard IPrincipal object on HTTPContext with custom principal
    HttpContext.Current.User = newUser
}

2)哪里可以存储自定义身份验证数据? 在OWIN之前的日子里,我使用AuthCookie的UserData值来存储自定义标识信息(除了用户名) - 例如OrgID。 现在可以将它存储为ClaimsIdentity对象中的声明吗? 这是一个好主意吗? 它仍然可以存储在AuthenticationTicket中吗? 我看这一切都错了吗?!

谢谢你的帮助。

您将使用CookieAuthenticationMiddleware而不是FormsAuthenticationModule CookieAuthenticationMiddleware仍然使用身份验证票证创建cookie,但格式不同。 使用CookieAuthenticationMiddleware ,可以从头开始设计索赔。 因此,默认情况下,您使用ClaimsIdentity获取ClaimsPrincipal ,尽管这些类实现了IPrincipalIIdentity

关于自定义身份验证数据,将它们存储为身份的声明部分。 关于新世界的一个好处是,您不再需要使用PostAuthenticate根据PostAuthenticate中的自定义数据来恢复您的主体。 如果您在调用SignIn之前使用所有必需的声明创建您的身份, CookieAuthenticationMiddleware负责将声明中的声明部分序列化到cookie中的CookieAuthenticationMiddleware单中并完整地返回到身份中。 此外,您不会使用HttpContext.Current.User来读取主体。 您将使用请求对象上可用的扩展方法从OWIN上下文中读取,如下所示。

Request.GetOwinContext().Authentication.User返回ClaimsPrincipal Request.GetOwinContext().Request.User返回与上面相同但作为IPrincipal

从控制器,您可以使用IPrincipal User ,它再次从上下文返回一个。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM