Click here to Skip to main content
15,894,106 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have gone through many websites and Youtube videos. but couldn't understood and implemented in my project properly. Can anybody please tell me how to work with authorization(Not authentication) in asp.net mvc 5 web application?

What I have tried:

I have provided annotations like [Authorize] & [AllowAnonymous] to Controller's method which can be accessed by admin only. But i am not able to do it. Even admin can't access these pages.
Posted
Updated 23-Nov-16 21:20pm

1 solution

Since you stored the roles of the users in the database, you have to check to the database.
So try to include this method in the global.asax
protected void Application_AuthenticateRequest(object sender, EventArgs args)
    {
        if (Context.User != null)
        {
            IEnumerable<role> roles = new UsersService.UsersClient().GetUserRoles(
                                                    Context.User.Identity.Name);


            string[] rolesArray = new string[roles.Count()];
            for (int i = 0; i < roles.Count(); i++)
            {
                rolesArray[i] = roles.ElementAt(i).RoleName;
            }

            GenericPrincipal gp = new GenericPrincipal(Context.User.Identity, rolesArray);
            Context.User = gp;
        }
    }
</role>


Then you could use this on top of the actionResult methods in the controllers.
[Authorize(Roles = "Administrator")]


Hope this helps.
 
Share this answer
 
Comments
Member 12867998 1-Dec-16 1:58am    
Sorry, but i am not storing User's roles into database table. Because my TL told me to not to store roles into that. I have hard-coded encrypted credentials for admin.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900