c# - 无法为用户设置角色
问题描述
我目前正在使用 .NET Core,并且正在尝试为用户分配/验证角色。例如,一个名为 admin 的管理员Robert
登录到系统,一个名为的角色admin
将分配给他。我尝试过ClaimsPrincipal
这样做,但它对我不起作用。我可以给点建议吗?
以下是我尝试过的代码:
public ActionResult Login (User user)
{
if (!AuthenticateUser(user.username, user.password, out ClaimsPrincipal principal))
{
//Error Message
}
else
{
HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
principal,
new AuthenticationProperties
{
IsPersistent = user.rememberMe
});
}
return RedirectToAction("Index", "Home");
}
private bool AuthenticateUser(string username, string password, out ClaimsPrincipal principal)
{
principal = null;
DataTable ds = DatabaseUtil.GetTable(SQL, username, password);
if (ds.Rows.Count == 1)
{
principal =
new ClaimsPrincipal(
new ClaimsIdentity(
new Claim[] {
new Claim(ClaimTypes.NameIdentifier, username),
new Claim(ClaimTypes.Name, ds.Rows[0][username].ToString()),
new Claim(ClaimTypes.Role, ds.Rows[0][role].ToString())
}, "Basic"
)
);
return true;
}
return false;
}
我什至尝试使用这组代码来检查当前用户是否被分配/真实。但是,当我进行调试时,它显示Authenticate: False
.
System.Security.Claims.ClaimsPrincipal currentUser = this.User;
bool IsAdmin = currentUser.IsInRole("admin");
解决方案
推荐阅读
- machine-learning - 我们可以只使用 model.fit 而不是 model.fit_generator 吗?
- python - 如何在 CSV 文件中关联来自网络抓取的特定行?
- java - 如何在 Android MainActivity 类中实现线程?
- spring - Spring reactor doOnNext,它正在执行吗?
- javascript - 设置内容类型nodejs的最佳方法
- c# - 尝试在 gridview 中编辑行(C# ASP.NET MVC)
- r - R的switch语句不是特殊形式,是不是很慢?
- qgis - 导入 qgis 的航拍图像歪了
- jpa - JPA - 如何将相同的查询添加到存储库两次
- python - 删除直到特定行的所有行