asp.net - IIdentity、IPrincipal、OWIN、IdentityUser 和 IUser<string> 如何组合在一起?

标签 asp.net .net asp.net-mvc authentication owin

我正在努力找出哪些 .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 而不是 FormsAuthenticationModuleCookieAuthenticationMiddleware 仍然使用身份验证票证创建 cookie,但格式不同。使用CookieAuthenticationMiddleware,一切都是从头开始为声明而设计的。因此,默认情况下,您会获得带有 ClaimsIdentityClaimsPrincipal,尽管这些类实现了 IPrincipalIIdentity

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

Request.GetOwinContext().Authentication.User 返回 ClaimsPrincipal Request.GetOwinContext().Request.User 返回与上面相同的结果,但与 IPrincipal

在 Controller 中,您可以使用 User(即 IPrincipal),它再次从上下文中返回一个。

关于asp.net - IIdentity、IPrincipal、OWIN、IdentityUser 和 IUser<string> 如何组合在一起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27392677/

相关文章:

javascript - 无法读取未定义/TypeError : event is undefined 的属性 'target'

jquery - Tabcontrol 选项卡文本未完全显示

asp.net - 字段集在 Twitter Bootstrap 下无法正确呈现

c# - Powershell正则表达式从日志文件中的行中提取圆括号之间的字符串

.net - 在调用方法的同一行实例化一个类是不好的做法吗?

c# - 启用迁移-ContextTypeName 错误 : Cannot find parameter

javascript - 将值从 Default.aspx.cs 页面发送到 Default.aspx 页面 javascript 函数

asp.net - ASP.NET 的机器 key 验证 key 的用途是什么

.net - 我无法发布到 Windows Azure 上的云服务。我收到安全 token 验证错误。我该如何修复它?

c# - 无法在数据库更新时保存更改。可能有奇怪的延迟加载行为?