【发布时间】:2023-03-26 20:48:01
【问题描述】:
我想使用表单身份验证创建基于角色的身份验证。请在下面找到我的控制器代码:-
[HttpPost]
public ActionResult Login(tblUser user)
{
DataClasses1DataContext dbcontext = new DataClasses1DataContext();
List<Mvc4API.linqtosql.tblUser> lstuser = dbcontext.tblUsers.ToList();
string message = string.Empty;
bool userlogin = lstuser.Exists(x => x.UserName == user.UserName && x.Password == user.Password);
if (userlogin)
{
FormsAuthentication.SetAuthCookie(user.UserName, true);
//role = "BB";
string Role = GetRoles(user.UserName);
return RedirectToAction("InsertProduct", "Product");
}
else
{
message = "Invalid User";
}
ViewBag.Message = message;
return View(user);
}
private string GetRoles(string UserName)
{
UserEntities userEntities = new Mvc4API.UserEntities();
List<tblUser> lstuser = userEntities.tblUsers.ToList();
List<tblRole> lstrole = userEntities.tblRoles.ToList();
var role = from u in lstuser
join r in lstrole on u.RoleId equals r.Id
where u.UserName == UserName
select r.RoleName.ToString();
string roletype = "";
foreach (var item in role)
{
roletype = item.ToString();
}
return roletype;
}
同时重定向我的代码如下:-
[Authorize(Users="B,Test")] // This is working
//[Authorize(Roles="Admin")] This is not working
public ActionResult InsertProduct()
{
return View();
}
基于用户的身份验证正在工作,但是当我在角色上进行时,它不起作用。
请告诉我必须在我的代码中进行的更改,以便它可以工作。
谢谢,
拉胡尔
【问题讨论】:
-
您从未设置任何角色。
string Role = GetRoles(user.UserName);只是将一个字符串存储在一个未使用的变量中 -
感谢回复,请告诉我如何设置角色
-
您阅读文档了吗?尝试任何课程? SO 不是讨论或教程网站。我是一个关于特定问题的问答网站。你有没有尝试过,代码在哪里?
-
顺便说一句,您最好删除所有这些代码并且永远不要使用它,即使作为演示也不要使用。存储未加密的密码是一个严重的安全漏洞和职业限制sn-p。 MVC 有自己经过良好测试的身份验证和授权机制。创建一个新的MVC应用程序,在
Change Authentication对话框中选择Individual Accounts,查看登录页面是如何工作的 -
我是新手,正在尝试开发测试 MVC 应用程序以供练习
标签: asp.net-mvc form-authentication