Asked by:
asp.net mvc login authentication

Question
-
User-1097602101 posted
I'm trying to create 2 types of users in ASP.NET MVC, for admin and users, as admin will be allowed to see all pages and user defined. I think I did have two types of users, but when I try to log in through admin and see the page that should see it, it does nothing for the users
class users.cs
public class users { public virtual int id_user { get; set; } public virtual string user_name { get; set; } public virtual string employee { get; set; } public virtual string user_level { get; set; } public virtual string password { get; set; } }
Class for Authorize
public class AuthLogAttribute : AuthorizeAttribute { public AuthLogAttribute() { View = "AuthorizeFailed"; } public string View { get; set; } /// <summary> /// Check for Authorization /// </summary> /// <param name="filterContext"></param> public override void OnAuthorization(AuthorizationContext filterContext) { base.OnAuthorization(filterContext); IsUserAuthorized(filterContext); } /// <summary> /// Method to check if the user is Authorized or not /// if yes continue to perform the action else redirect to error page /// </summary> /// <param name="filterContext"></param> private void IsUserAuthorized(AuthorizationContext filterContext) { // If the Result returns null then the user is Authorized if (filterContext.Result == null) return; //If the user is Un-Authorized then Navigate to Auth Failed View if (filterContext.HttpContext.User.Identity.IsAuthenticated) { // var result = new ViewResult { ViewName = View }; var vr = new ViewResult(); vr.ViewName = View; ViewDataDictionary dict = new ViewDataDictionary(); dict.Add("Message", "Sorry you are not Authorized to Perform this Action"); vr.ViewData = dict; var result = vr; filterContext.Result = result; } } } HomeController public ActionResult Index() { return View(); } [AuthLog(Roles = "ADMIN")] public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } [AuthLog(Roles = "user")] public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } public ActionResult Login() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Login(users u) { if (ModelState.IsValid) { using (ISession session = NhibernateSession.OpenSession()) { var v = session.Query<users>().Where(a => a.user_name.Equals(u.user_name) && a.password.Equals(u.password)).FirstOrDefault(); if (v != null) { Session["id_user"] = v.id_user.ToString(); Session["employee"] = v.employee.ToString(); return RedirectToAction("AfterLogin"); } } } return View(u); } public ActionResult AfterLogin() { if (Session["id_user"] != null) { return View(); } else { return RedirectToAction("Index"); } } public ActionResult LogOut() { Session.Abandon(); return RedirectToAction("Login", "Home"); }
Login page
@model LOGINAPP.Models.users @{ ViewBag.Title = "Login"; Layout = null; } <h2>Login</h2> @using (Html.BeginForm("Login", "Home", FormMethod.Post)) { //this is for create form tag @Html.AntiForgeryToken() // this is for prevent CSRF attack @Html.ValidationSummary(true) if (@ViewBag.Message != null) { <div style="border: 1px solid red"> @ViewBag.Message </div> } <table> <tr> <td>@Html.LabelFor(a => a.user_name)</td> <td>@Html.TextBoxFor(a => a.user_name)</td> <td>@Html.ValidationMessageFor(a => a.user_name)</td> </tr> <tr> <td> @Html.LabelFor(a => a.password) </td> <td> @Html.PasswordFor(a => a.password) </td> <td> @Html.ValidationMessageFor(a => a.password) </td> </tr> <tr> <td></td> <td> <input type="submit" value="Login" /> </td> <td></td> </tr> </table> }
Monday, August 5, 2019 1:05 PM
All replies
-
User1520731567 posted
Hi sssaa,
According to your code,I find you didn't have a code that distinguishes between ADMIN and user.
So,if the user is authenticated,regardless of the role of the user, the page that jumps is the same.
I suggest you could modify your IsUserAuthorized function,like:
This actually simplifies some logical steps, you can judge the conditions according to the actual situation.
It is best to judge whether the authentication is successful, and then judge that the roles are matched.
if (Roles=="ADMIN" && filterContext.HttpContext.User.Identity.IsAuthenticated && (!User.IsInRole("ADMIN"))) //[AuthLog(Roles = "ADMIN")] {
... filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
{
controller = "yourcontroller",
action = "youraction"
})); }
else if (Roles=="user" && filterContext.HttpContext.User.Identity.IsAuthenticated && (!User.IsInRole("user")))//[AuthLog(Roles = "user")] { ... filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "yourcontroller", action = "youraction" })); }
else
{
...
}Best Reagrds.
Yuki Tao
Tuesday, August 6, 2019 7:13 AM -
User753101303 posted
Hi,
Or for now it seems you could use the built in Authorize attribute first and then enhance as needed.
Tuesday, August 6, 2019 7:20 AM -
User-1097602101 posted
I tried this way but it gives me a context error because I don't use entityframework, a nhibernate.
public override string[] GetRolesForUser(string username)
{
using (ISession session = NhibernateSession.OpenSession())
{
var result = (from user in context.users
join role in context.user_level on user.id_user equals role.id_user
where user.user_name == username
select role.user_level).ToArray();
return result;
}
throw new NotImplementedException();
}Web.confg
<roleManager defaultProvider="myRoleProvider" enabled ="true"> <providers> <clear/> <add name="myRoleProvider" type="HCMDimitar.Models.users"/> </providers> </roleManager>
Tuesday, August 6, 2019 10:35 AM -
User475983607 posted
As suggested above, use ASP.NET's built in security, Identity, if you are unsure how to build a secure application.
Tuesday, August 6, 2019 10:44 AM