0

I have User and Employees Models. I am authenticating User using session variable. Means if user is not logged in I'm sending him on login form. Once he logs in he will be authenticated just as a logged in user.

public void OnAuthentication(AuthenticationContext filterContext)
    {
        if (string.IsNullOrEmpty(Convert.ToString(filterContext.HttpContext.Session["Username"])))
        {
            filterContext.Result = new HttpUnauthorizedResult();
        }
    }

    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
    {
        if (filterContext.Result == null || filterContext.Result is HttpUnauthorizedResult)
        {
            //Redirecting the user to the Login View of Account Controller  
            filterContext.Result = new RedirectToRouteResult(
            new RouteValueDictionary
            {
                 { "controller", "Account" },
                 { "action", "Login" }
            });
        }
    }

Now I have to authenticate this user based on his Role to access Employee data, controller etc. If he is admin he will have access. Otherwise he will get Unauthorized message.

I have User model and have Roles as a string column in the same table as below.

   public class User
   {
      public int UserId { get; set; }
      [Display(Name = "User Name")]
      public string UserName { get; set; }
      public string Password { get; set; }
      public string Email { get; set; }
      public string Role { get; set; }
  }

Now I want to add these Roles into an Identity object in my CustomAutheticationFilter class, So that I will be able to use [Authorize(Roles="Admin,SuperAdmin")] attribute on my EmployeeController like below.

[CustomAuthenticationFilter]
 [Authorize(Roles = "Admin,SuperAdmin")]
 public class EmployeesController : Controller
 {
 }
Sam
  • 471
  • 2
  • 5
  • 9

0 Answers0