【问题标题】:MVC user Authentication using Web API使用 Web API 的 MVC 用户身份验证
【发布时间】:2015-01-02 05:48:45
【问题描述】:

我已经建立了一个用于用户登录的 WebAPI,如果用户提供了正确的用户名和密码,该 webAPI 可以生成访问令牌。我的问题是如何将用户角色信息也传递给 MVC 应用程序。

例如,

我在下面有一个 MVC 应用程序控制器,如何从 Web API 传递角色“管理员、用户编辑器”?我知道我可以使用另一个 WebAPI 调用来检查用户角色,但这不是一个好主意。

[Authorized("Admin,UserEditor")]
ActionResult EditUser(int? Id)
{
........
} 

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-web-api


    【解决方案1】:

    您可以从声明中读取角色信息。

    Step-1 创建角色

    我创建了它的种子,但您的选择可能不同。

    public static class MyDbInitializer
        {
            public static void Seed(this ModelBuilder builder)
            {
                Guid adminRoleId = Guid.Parse("90a5d1bb-2cf0-4014-9f1a-2d9f644a2e22");
    
                builder.Entity<IdentityRole<Guid>>().HasData(
                    new IdentityRole<Guid>
                    {
                        Id = adminRoleId,
                        Name = RoleIdentifier.admin,
                        NormalizedName = RoleIdentifier.admin.ToUpper(CultureInfo.GetCultureInfo("en-GB"))
                    });
    
            }
        }
    

    第 2 步声明

      public static class RoleIdentifier
        {
            public const string admin = "admin";
            public const string user = "user";
        }
    
    public static class JwtClaimIdentifier
        {
            public const string UserId = "user_id";
            public const string UserName = "user_name";
            public const string Role = "role";
        }
    

    在您生成令牌的地方,将角色名称添加到声明信息中。

    ...
    ... string role = await _userService.GetRole(userId);
    ... identity.FindFirst(JwtClaimIdentifier.Role)
    

    Step-3 添加授权 att.到控制器。

     [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = RoleIdentifier.admin)]
        public class FooController
        {
        }
    

    当登录的用户想要访问这个动作时,这个角色的占有将匹配和访问声明。

    【讨论】:

      【解决方案2】:

      您需要使用 2 种身份验证机制(不记名令牌和 Cookie),因为您使用令牌和 MVC 5 控制器使用 Cookie 保护 Web API 端点。我建议您检查选择了 MVC 核心依赖项的 VS 2013 Web 模板。它包含您的案例所需的所有代码。在GrantResourceOwnerCredentials 方法中,您会发现类似于以下内容:

              public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
          {
              var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
      
              ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
      
              if (user == null)
              {
                  context.SetError("invalid_grant", "The user name or password is incorrect.");
                  return;
              }
      
              ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
                 OAuthDefaults.AuthenticationType);
              ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                  CookieAuthenticationDefaults.AuthenticationType);
      
              AuthenticationProperties properties = CreateProperties(user.UserName);
              AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
              context.Validated(ticket);
              context.Request.Context.Authentication.SignIn(cookiesIdentity);
          }
      

      注意oAuthIdentity 用于 Web API,cookiesIdentity 用于 MVC 应用程序。

      【讨论】:

      • 感谢您的回复!你的意思是我必须自定义 GrantResourceOwnerCredentials 并检查 cookie 中的 AccessToken 吗?我在这里遇到了另一个问题,我的 MVC 应用程序如何从 WebAPI 获取声明信息。如果WebAPI和MVC不在同一个域,是否需要共享机器密钥?
      猜你喜欢
      • 2016-07-03
      • 2014-05-02
      • 1970-01-01
      • 2018-03-19
      • 2017-03-03
      • 2013-12-09
      • 2015-09-17
      • 2012-07-28
      相关资源
      最近更新 更多