我们已经实现了 Google OAuth2,它在 ASPNetUsers 表中创建了用户。这工作正常,我们可以通过 User.Identity.GetUserName() 看到经过身份验证的用户。
如果我们将此用户添加到角色,例如“MyCustomRole”,通过 AspNetRoles 和 AspNetUserRoles 表,任何方法都使用以下方法进行保护:
[Authorize(Roles="MyCustomRole")]
无法访问。应用程序将经过身份验证的用户转发到登录 Controller 。
将这些经过外部身份验证的用户添加到角色的正确机制是什么,使 [Authorize(Roles="")] 属性可以访问这些角色?
最佳答案
不确定是哪个版本的 asp identity
您正在使用,但我使用此代码完成了您想要的操作
[HttpPost]
public async Task<ActionResult> AddUserToRole()
{
var result = await UserManager.AddToRolesAsync(User.Identity.GetUserId(),
new[]{"YourCustomRole"});
if (!result.Succeeded){
return View();
}
else{
return RedirectToAction("index");
}
}
要对此进行测试,您可能需要创建一个空项目,一个空的!然后在 newget 包中运行这个 nuget
PM> Install-Package Microsoft.AspNet.Identity.Samples -Pre
那么你可以把我的行动代码放在UsersAdmin
Controller
关于asp.net - 向通过 Google OAuth2 创建的用户添加角色或声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29991632/