Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form Authentication : Roles (MVC 4) C#

I am trying to implement Forms Authentication in my Application. I various examples and looked at the samples and questions provided in this forum and ASP.net MVC but I just can't get it to work.

I manage to authenticate my user but the roles does not seem to work :-(

I have setup my Web.Config as follow :

<authentication mode="Forms"> <forms loginUrl="~/Account/Login" timeout="2880" /> </authentication>

In my Controller I set the Index page to AllowAnonymous and then check in there if the user is authenticated. If not then redirect to the login page..

[AllowAnonymous]
    public ActionResult Index(string sortOrder, string searchString,string currentFilter, int? page)
    {
        if (!Request.IsAuthenticated)
        {

            return RedirectToAction("Login", "Account");

        }
//Find all the employees
        var employees = from s in db.Employees
                       select s;
//Pass employees to the view (All works fine)
return View(employees.ToPagedList(pageNumber, pageSize));
}

This all is working 100%

My Login code looks like this :

 [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(User user, string returnUrl)
    {
        var myUser = db.Users.Where(b => b.UserName == user.UserName).FirstOrDefault();
        if(myUser != null)
        {
            if(myUser.Password==user.Password)
            {
                //These session values are just for demo purpose to show the user details on master page
                //Session["User"] = user;
                ICollection<UserAccessLevel> levels = db.UserAccessLevels.Where(b => b.UserId == myUser.UserId).ToList();
                //Session["levels"] = levels;

                //Let us now set the authentication cookie so that we can use that later.
                FormsAuthentication.SetAuthCookie(user.UserName, false);

                return RedirectToAction("Index","Employee");
            }
        }
        ViewBag.Message = "Invalid User name or Password.";
        return View(user);
    }

I also have the following code in the Global.asax file :

 protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
    {
        if (FormsAuthentication.CookiesSupported == true)
        {
            if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
            {
                try
                {
                    //let us take out the username now                
                    string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
                    string roles = string.Empty;

                    using (TrainingContext entities = new TrainingContext())
                    {
                        User user = entities.Users.SingleOrDefault(u => u.UserName == username);

                        roles = "admin";//user.Roles;
                    }
                    //Let us set the Pricipal with our user specific details
                    e.User = new System.Security.Principal.GenericPrincipal(
                       new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
                }
                catch (Exception)
                {
                    //somehting went wrong
                }
            }
        }
    }

When I log in my FormsAuthentication_OnAuthenticate executes and everything looks good. My User is set and my roles in the session is also there...

But when I click on the details of my Employee/Index screen it takes me back to the login screen (I expect it to take me to the details of the employee I clicked because I am logged in and I am setup as an admin role)

Please can you assist me to try and get to the problem. I sat for more than 18 hours already trying to figure this out.

I already looked at these solutions and as you can see most of my code comes from there... codeproject.com/Articles/578374/AplusBeginner-27splusTutorialplusonplusCustomplusF codeproject.com/Articles/342061/Understanding-ASP-NET-Roles-and-Membership-A-Begin codeproject.com/Articles/408306/Understanding-and-Implementing-ASP-NET-Custom-Form

in case you need more detail about my code you can also download it from GitHub https://github.com/Ruandv/Training/tree/FormsAuthentication

I will appreciate your assistance.

like image 675
Gremlin1708 Avatar asked Oct 20 '22 19:10

Gremlin1708


1 Answers

If you go to your Database and look for the table that assigns roles to users (probably generated by SimpleMembership?), does your user have an "admin" role?

Looks like you're only assigning the role in the FormsAuthentication_OnAuthenticate method without actually setting it in the DB.

// Your method (...)
User user = entities.Users.SingleOrDefault(u => u.UserName == username);
roles = "admin";//user.Roles;

And, although I'm not entirely sure, [Authorize(Roles = "admin")] may be using your Role Provider and checking if the user has/doesn't have the role in the database.

like image 64
user1987392 Avatar answered Nov 16 '22 13:11

user1987392