MVC用户使用Web API进行身份验证

时间:2014-11-05 21:18:33

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

我为用户登录构建了一个WebAPI,如果用户提供了正确的UserName和密码,webAPI可以生成Access Token。我的问题是如何将用户角色信息传递给MVC应用程序。

例如,

我下面有一个MVC app控制器,如何通过角色' Admin,UserEditor'来自Web API?我知道我可以使用另一个WebAPI调用来检查用户角色,但这样做并不是一个好主意。

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

2 个答案:

答案 0 :(得分:7)

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

第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)

步骤3添加授权提示。给控制器。

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

当登录的用户想要访问此操作时,该角色的所有权将匹配并访问声明。

答案 1 :(得分:1)

您需要使用2种身份验证机制(承载令牌和Cookie),因为您使用Cookie使用令牌和MVC 5控制器来保护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);
    }

注意Web API的oAuthIdentity和MVC应用的cookiesIdentity