I want to create Authentication based on Role using Form Authentication. Please Find my controller code below:-
[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;
}
While redirecting my code as follows:-
[Authorize(Users="B,Test")] // This is working
//[Authorize(Roles="Admin")] This is not working
public ActionResult InsertProduct()
{
return View();
}
Authentication based on Users is working but when I do it on Roles it is not working.
Please tell the changes I have to make in my code so that it can work.
Thanks,
Rahul
Found an answer, Just added the following code in Global.asax.cs