【译】Asp.Net Identity与Owin,到底谁是谁?

简介: 送给正在学习Asp.Net Identity的你 :-)原文出自 trailmax 的博客AspNet Identity and Owin. Who is who.Recently I have found an excellent question on Stackoverflow.

送给正在学习Asp.Net Identity的你 :-)

原文出自 trailmax 的博客AspNet Identity and Owin. Who is who.

Recently I have found an excellent question on Stackoverflow. The OP asks why does claim added to Idenetity after calling AuthenticationManager.SignIn still persist to the cookie.

最近我在StackOverflow发现一个非常好的(妙啊)问题,OP提出的问题是,在调用AuthenticationManager.SignIn之后再向Identity添加Claim ,这些后添加的Claim仍然被保存在了Cookies里。

The sample code was like this:

代码是这样的

ClaimsIdentity identity = UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie );

var claim1 = new Claim(ClaimTypes.Country, "Arctica");
identity.AddClaim(claim1);

AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true }, identity );

var claim2 = new Claim(ClaimTypes.Country, "Antartica");
identity.AddClaim(claim2);

Yeah, why does claim2 is available after cookie is already set.

噢耶,为什么在已经设置cookie之后claim2仍然是有效的呢?

After much digging I have discovered that AspNet Identity framework does not set the cookie. OWIN does. And OWIN is part of Katana Project which has open source code. Having the source code available is always nice – you can find out yourself why things work or don’t work the way you expect.

在我深度挖掘之后,我发现 AspNet Identity framework 并没有真的去设置cookie,是Owin做的。Owin是开源项目Katana的一部分(译者注:katana微软对于Owin的实现,Owin的实现还有其它的)。能看源代码总是一件很棒的事,因为你能自己去寻找为什么事情是这样的或者为什么结果和预期的不一致的答案。

In this case I have spent a few minutes navigating Katana project and how AuthenticationManager works. Turned out that SingIn method does not set a cookie. It saves Identity objects into memory until time comes to set response cookies. And then claims are converted to a cookie and everything magically works :-)

在这件事里,我花了几分钟时间找到Katana的源码寻找AuthenticationManager的工作原理。原来SignIng方法并没有设置Cookie。直到设置相应cookie之前,它只是将Identity对象放在了内存里。然后 claims被转换成cookie,并且,神奇的事情发生了:-D(应该是这么翻译吧...)

译者注:下面是SignIn的源码,源码地址

public void SignIn(AuthenticationProperties properties, params ClaimsIdentity[] identities)
{
    AuthenticationResponseRevoke priorRevoke = AuthenticationResponseRevoke;
    if (priorRevoke != null)
    {
        // Scan the sign-outs's and remove any with a matching auth type.
        string[] filteredSignOuts = priorRevoke.AuthenticationTypes
            .Where(authType => !identities.Any(identity => identity.AuthenticationType.Equals(authType, StringComparison.Ordinal)))
            .ToArray();
        if (filteredSignOuts.Length < priorRevoke.AuthenticationTypes.Length)
        {
            if (filteredSignOuts.Length == 0)
            {
                AuthenticationResponseRevoke = null;
            }
            else
            {
                AuthenticationResponseRevoke = new AuthenticationResponseRevoke(filteredSignOuts);
            }
        }
    }

    AuthenticationResponseGrant priorGrant = AuthenticationResponseGrant;
    if (priorGrant == null)
    {
        AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(identities), properties);
    }
    else
    {
        ClaimsIdentity[] mergedIdentities = priorGrant.Principal.Identities.Concat(identities).ToArray();

        if (properties != null && !object.ReferenceEquals(properties.Dictionary, priorGrant.Properties.Dictionary))
        {
            // Update prior properties
            foreach (var propertiesPair in properties.Dictionary)
            {
                priorGrant.Properties.Dictionary[propertiesPair.Key] = propertiesPair.Value;
            }
        }

        AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(mergedIdentities), priorGrant.Properties);
    }
}

This sparked another question. At the moment Identity does not have open source, but what is the role of OWIN in Identity and how Claims work here?

这引发了另一个问题,此时 Identity还没有开源,但是Identity中OWIN的Role是什么,并且,Claims是如何工作(译者注:发挥作用)的?

Turns out that Identity framework deals only with user persistence, password hashing, validating if the password is correct, sending out email tokens for password reset, etc. But Identity does not actually authenticate users or create cookies. Cookies are handled by OWIN.

原来Identity framework做的事只有用户持久化存储、密码Hash、验证密码是否是正确的、为重置密码发送带有Token的电子邮件等等。但是identity 没有真正的认证用户或者创建Cookie。Owin在处理Cookie。

Take a look on this code for signing in:

我们来看一下SignIng的代码:

public async Task SignInAsync(Microsoft.Owin.Security.IAuthenticationManager authenticationManager, ApplicationUser applicationUser, bool isPersistent)
{
    authenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);

    ClaimsIdentity identity = await UserManager.CreateIdentityAsync(applicationUser, DefaultAuthenticationTypes.ApplicationCookie);

    authenticationManager.SignIn(new Microsoft.Owin.Security.AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}

Identity only creates ClaimsIdentity which you can study on ReferenceSource site. And ClaimsIdentity is part of .Net framework, not some nuget-package from the interwebz. Then this claimsIdentity is passed to OWIN AuthenticationManager where a callback is set to assign cookies on when time comes to write headers on the response.

Identity只是创建了ClaimsIdentity,你可以在ReferenceSource (译者注:查看.Net源码的地方,微软官办,没保存的同学快快收藏吧!)上学习他的代码。而且ClaimsIdentity是.Net Freamwork的一部分,不是从互联网上下载的Nuget包(实在不懂interwebz是什么意思 Orz)。然后claimsIdentity被传给了OWIN AuthenticationManager,(断句)OWIN AuthenticationManager是设置在派送Cookie(assign cookies)上的一个Callcack回调,(断句)这个assign cookies是放在一个什么东西上,当到了向Response写Header的时候就搞这个东西(这句话太难翻译了,你一定要看看原话,我不保证这句话翻译正确 (:逃)

So far, so good, we have 3 parts here: Identity framework creating a ClaimsIdentity, OWIN creating a cookie from this ClaimsIdentity. And .Net framework which holds the class for ClaimsIdentity.

目前看来还不错。我们知道了这里有3个部分:

  • Identity framework 创建了一个ClaimsIdentity
  • Owin为ClaimsIdentity创建了cookie
  • 持有 ClaimsIdentity的class的是.Net framework

When in your classes you access ClaimsPrincipal.Current, you only use .Net framework, no other libraries are used. And this is very handy!

当你在你的代码中访问ClaimsPrincipal.Current时,你只用的了.Net framework,没有其它库(library)被用到,这是非常方便的。

Default Claims

Identity framework does a nice thing for you. By default it adds a number of claims to a principal when user is logged in. Here is the list:

Identity framework帮你做了很多有用的事。默认情况下,在用户登录的时候,她会添加一些claims到principal(译者注:看一下Mvc中的HttpContext.User的类型,就是IPrincipal)。接下来是列表:

  • User.Id is added as claim type “http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier” or by ClaimTypes.NameIdentifier

  • User.Id的claims类型是“http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier” 或者通过ClaimTypes.NameIdentifier指定(译者注:ClaimTypes.NameIdentifier的定义如下public const string NameIdentifier = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier";

  • Username is added as claim type “http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name” or by ClaimTypes.Name

  • UserName 的claims类型是“http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name” 或者由ClaimTypes.Name指定

  • “ASP.NET Identity” is saved as claim type “http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider”. This is useful if you are using OpenId to do the authentication. Not much use if you are using only users stored in our database. See this page for more details.

  • “ASP.NET Identity”对应的claim类型type是“http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider”。如果你使用OpenId来做认证 (authentication),那么它很有用,如果你只是用你自己的数据库来存储用户信息,那么它对你没有太大帮助。相关信息请查阅此页面

  • Guid containing User’s Security Stamp is persisted in claim with type “AspNet.Identity.SecurityStamp“. Security Stamp is basically a snapshot of user state. If password/method of authentication, email, etc. is changed, Security Stamp is changed. This allows to “logout everywhere” on credentials change. Read more about what is security stamp in Hao Kung’s answer.

  • 包含用户Security Stamp的Guid被存在type为“AspNet.Identity.SecurityStamp”的claim里。 Security Stamp 总的来说是用户状态(user state)快照(snapshot),如果用于认证的 密码/method (译者注:用于认证的其他方式)、email等等这些信息改变了。Security Stamp也会变。这就允许当credentials(凭证)改变时,在所有已登录的地方登出。了解更多请关于Security Stamp 请看Hao Kung(看起来像个中国人)在SO上的答案

  • The most useful claims added by default are role. All roles assigned to the user are saved as ClaimTypes.Role or by “http://schemas.microsoft.com/ws/2008/06/identity/claims/role“. So next time you need to check current user’s roles, check the claims. This does not hit the database and is very quick. And in fact, if you call .IsInRole("RoleName") on ClaimsPrincipal, the framework goes into claims and checks if Role claims with this value is assigned.

  • 默认添加的最有用的claims就是role了,所有赋予这个用户的的role都被存储为type为 ClaimTypes.Role 或者 “http://schemas.microsoft.com/ws/2008/06/identity/claims/role”。所以以后你想检查当前用户的Role你就可以直接检查这些claims。(译者注:在登陆时存储在Identity数据库中的所有关于user的role,以及claim会被转换成claim。IsInRole方法也是在判断claim,详情可查阅源代码)。这些操作都不访问数据库所以非常快。而且事实上,如果你使用.IsInRole("RoleName") on ClaimsPrincipal,框架会去检查claim中的role claim是否含有指定的值。

You can find the list of framework claim types on .Net Reference site. However, this list is not complete. You can make up your own claim types as you are pleased – this is just a string.

你能够在.Net Reference网站上找到claim type的列表。然而,这个列表并不完整。如果你喜欢,你完全可以制造你自己的claim type,因为它只是一个字符串而已。

If you want to add your own claim types, I recommend to use your own notation for the claim types. Something like “MyAppplication:GroupId” and keep all the claim types in one class as constants:

如果你想添加你自己的claim type ,我建议你在claim type上加上你自己独特的标记。比如:“MyAppplication:GroupId”,然后将它们作为 constants存在某个类里面。

public class MyApplicationClaimTypes
{
    public string const GroupId = "MyAppplication:GroupId";
    public string const PersonId = "MyAppplication:PersonId";
    // other claim types
} 

This way you can always find where the claims are used and will not clash with the framework claim types. Unless the claim you use matches framework claim types exactly, like ClaimTypes.Email.

这种方式让你能够找到哪里引用了这些claims,并且不会和framework中的claim type发生冲突。除非你使用的claim type的framework中的claim type精确匹配,例如:ClaimTypes.Email

Adding default claims 添加默认的claims

I always add user’s email to the list of claims. I do that on user sign-in, same way the first code snippet adds claim1 and claim2:

我总是使用和第一个添加claim1和claim2相同的方式在用户登录时将用户的email添加到claims列表里。

public async Task SignInAsync(IAuthenticationManager authenticationManager, ApplicationUser applicationUser, bool isPersistent)
{
    authenticationManager.SignOut(
        DefaultAuthenticationTypes.ExternalCookie,
        DefaultAuthenticationTypes.ApplicationCookie);

    var identity = await this.CreateIdentityAsync(applicationUser, DefaultAuthenticationTypes.ApplicationCookie);

    // using default claim type from the framework
    identity.AddClaim(new Claim(ClaimTypes.Email, applicationUser.Email));

    authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}

You can add your default claims to all users here as well. But there is IClaimsIdentityFactory class that is assigned in UserManager. There is only one method there:

你可可以向所有用户添加默认的claims。但是在UserManager中有一个IClaimsIdentityFactory的类,它只定义了一个方法。

public interface IClaimsIdentityFactory<TUser, TKey> where TUser : class, IUser<TKey> where TKey : IEquatable<TKey>
{
    /// <summary>
    /// Create a ClaimsIdentity from an user using a UserManager
    /// </summary>
    Task<ClaimsIdentity> CreateAsync(UserManager<TUser, TKey> manager, TUser user, string authenticationType);
}

Default AspNet Identity implementation creates ClaimsIdentity, adds the default claims described above, adds claims stored in the database for the user: IdentityUserClaims. You can override this implementation and slip-in your own logic/claims:

默认的Asp.Net Identity实现创建ClaimsIdentity,添加之前提到的默认claims,添加存储在satabase中的属于这个用户的claims:IdentityUserClaims。你可以重写这个实现类,然后放进你自己的 logic/claims.
public class MyClaimsIdentityFactory : ClaimsIdentityFactory

        claimsIdentity.AddClaim(new Claim("MyApplication:GroupId", "42"));

        return claimsIdentity;
    }
}

and assign it in UserManager:

将它赋值给UserManager:

public UserManager(MyDbContext dbContext)
    : base(new UserStore<ApplicationUser>(dbContext))
{
    // other configurations

    // Alternatively you can have DI container to provide this class for better application flexebility
    this.ClaimsIdentityFactory = new MyClaimsIdentityFactory();
}

正文结束

补充一些译者的话

如果你注意到文中提到登陆的代码authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
在新的Mvc项目中勾选个人身份认证时所生成的基本代码已经变成了var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false); ,我试过使用文中的方法,是可以正常登陆的。

因为最终SignInManager的PasswordSignInAsync方法几经辗转也调用了IAuthenticationManager实例的Sign方法完成登陆。

目录
相关文章
|
4月前
|
存储 开发框架 算法
ASP.NET Core 标识(Identity)框架系列(四):闲聊 JWT 的缺点,和一些解决思路
ASP.NET Core 标识(Identity)框架系列(四):闲聊 JWT 的缺点,和一些解决思路
113 1
|
4月前
|
开发框架 JSON .NET
ASP.NET Core 标识(Identity)框架系列(三):在 ASP.NET Core Web API 项目中使用标识(Identity)框架进行身份验证
ASP.NET Core 标识(Identity)框架系列(三):在 ASP.NET Core Web API 项目中使用标识(Identity)框架进行身份验证
|
4月前
|
存储 开发框架 JSON
ASP.NET Core 标识(Identity)框架系列(二):使用标识(Identity)框架生成 JWT Token
ASP.NET Core 标识(Identity)框架系列(二):使用标识(Identity)框架生成 JWT Token
107 0
|
4月前
|
开发框架 .NET 数据库连接
ASP.NET Core 标识(Identity)框架系列(一):如何使用 ASP.NET Core 标识(Identity)框架创建用户和角色?
ASP.NET Core 标识(Identity)框架系列(一):如何使用 ASP.NET Core 标识(Identity)框架创建用户和角色?
|
存储 SQL 开发框架
ASP.NET Core MVC 从入门到精通之Identity入门
ASP.NET Core MVC 从入门到精通之Identity入门
165 0
|
开发框架 关系型数据库 MySQL
Asp.Net Core Identity+EFCore + Mysql踩坑记录
Asp.Net Core Identity+EFCore + Mysql踩坑记录
154 0
|
存储 开发框架 前端开发
ASP.NET Identity 使用 RoleManager 进行角色管理 (VS2013RC)
最近做一个Web平台系统,系统包含3个角色,“管理员, 企业用户, 评审专家”, 分别有不同的功能。一直以来都是使用微软封装好的Microsoft.AspNet.Identity.dll程序集来进行身份验证和角色控制。
ASP.NET Identity 使用 RoleManager 进行角色管理 (VS2013RC)
|
开发框架 前端开发 .NET
使用Asp.Net Identity 2.0 认证邮箱激活账号(附DEMO)
一个星期前,也就是3月20日,微软发布了Asp.Net Identity 2.0 RTM。功能更加强大,也更加稳定。Identity这个东西现在版本还比较低,每次发布新版本都会有较多改动。
|
开发框架 .NET 数据库
ASP.NET Core Identity自定义数据库结构和完全使用Dapper而非EntityFramework Core
ASP.NET Core Identity自定义数据库结构和完全使用Dapper而非EntityFramework Core前言原本本节内容是不存在的,出于有几个人问到了我:我想使用ASP.NET Core Identity,但是我又不想使用默认生成的数据库表,想自定义一套,我想要使用ASP.NE Core Identity又不想使用EntityFramework Core。
1142 0
|
.NET 中间件 数据库
ASP.NET Core Identity 框架 - ASP.NET Core 基础教程 - 简单教程,简单编程
原文:ASP.NET Core Identity 框架 - ASP.NET Core 基础教程 - 简单教程,简单编程 ASP.NET Core Identity 框架 前面我们使用了 N 多个章节,终于是把 ASP.NET Core MVC 经常使用的功能大略的过了一遍。
2399 0