我已经为用户登录构建了WebAPI,如果用户提供了正确的UserName和密码,则webAPI可以生成访问令牌。我的问题是如何将用户角色信息也传递给MVC应用程序。
例如,
我下面有一个MVC应用程序控制器,如何从Web API传递角色“ Admin,UserEditor”?我知道我可以使用另一个WebAPI调用来检查用户角色,但这不是一个好主意。
[Authorized("Admin,UserEditor")]
ActionResult EditUser(int? Id)
{
........
}
您需要使用2种身份验证机制(承载者令牌和Cookies),因为您正在使用令牌保护Web API端点,并使用Cookies来保护MVC 5控制器。我建议您检查选中了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
。