MVC5 Claims version of the Authorize attribute

后端 未结 5 681
情书的邮戳
情书的邮戳 2020-11-29 16:39

I\'m trying out some of the new stuff in VS2013 RC with MVC5 and the new OWIN authentication middleware.

So, I\'m used to using the [Authorize] attribut

5条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 17:12

    I found that you can still use the Authorization attribute with roles and users, with claims.
    For this to work, your ClaimsIdentity have to include 2 specific claim types:

        ClaimTypes.Name
    

    and

        ClaimTypes.Role
    

    Then in your class derived from OAuthAuthorizationServerProvider, in the GrantXX methods you use, when you create your ClaimsIdentity, add these 2 claims.

    Example:

        var oAuthIdentity = new ClaimsIdentity(new[]
        {
            new Claim(ClaimTypes.Name, context.ClientId),
            new Claim(ClaimTypes.Role, "Admin"),
        }, OAuthDefaults.AuthenticationType);
    

    Then on any action you can use [Authorize(Roles ="Admin")] to restrict access.

提交回复
热议问题