C# 无法为用户设置角色
我目前正在使用.NET Core,我正在尝试为用户分配/验证一个角色。例如,一个名为C# 无法为用户设置角色,c#,asp.net-mvc,authentication,.net-core,C#,Asp.net Mvc,Authentication,.net Core,我目前正在使用.NET Core,我正在尝试为用户分配/验证一个角色。例如,一个名为Robert的管理员登录到系统,一个名为admin的角色将分配给他。我尝试使用ClaimsPrincipal来实现这一点,但它对我不起作用。能给我一些建议吗 以下是我尝试过的代码: public ActionResult Login (User user) { if (!AuthenticateUser(user.username, user.password, out C
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");
您可以分享如何在startup.cs上设置标识配置吗?var claims=new[]{new Claim(JwtRegisteredClaimNames.Sub,user.madv),new Claim(JwtRegisteredClaimNames.Typ,user.titleid.ToString()),newclaim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString()),newclaim(ClaimTypes.Role,user.roleid.ToString())//检查角色};链接:@LuttiCoelho我在Startup.cs服务中有这组代码。AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)。AddCookie(选项=>{options.LoginPath=“/user/Login/);options.AccessDeniedPath=“/Home/Error/”;});