Implement Role Based Authorization Using .NET MVC 5

I would like to implement role-based authorization in my web application that I am creating. The way I imagined this was to create 3 tables in my DB, for example:

1. Roles 2. UserRoles (many to many table) 3. Users 

After that, each user will have a role assigned to him. Now ... My question is: how to allow or deny access to certain views / controllers inside my .NET MVC application. I came across this:

 [Authorize(Roles = "HrAdmin, CanEnterPayroll")] [HttpPost] public ActionResult EnterPayroll(string id) { // . . . Enter some payroll . . . } 

The Authorize property seems to restrict specific controllers / actions to specific roles ... But what if I read the user roles from the UserRoles table, as in my case? How will my application know what role the user plays in the system?

Can someone help me with this?

+6
source share
3 answers

Let's pretend that you saved your username and role in the session:

 [AllowAnonymous] [HttpGet] public ActionResult Login() { . . . . string userName = (string)Session["UserName"]; string[] userRoles = (string[])Session["UserRoles"]; ClaimsIdentity identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userName)); userRoles.ToList().ForEach((role) => identity.AddClaim(new Claim(ClaimTypes.Role, role))); identity.AddClaim(new Claim(ClaimTypes.Name, userName)); AuthenticationManager.SignIn(identity); . . . . } 
+7
source

if you authorize the role to access the controller (at the class level) or to the action (functional level), they will have access to the role. otherwise access is denied.

if you use only the Authorize keyword without specifying roles or users, all authenticated users will have access.

I hope I clarify everything clearly?

to use an identifier based on requirements refer to the following

https://msdn.microsoft.com/en-gb/library/ee517291.aspx

https://msdn.microsoft.com/en-gb/library/ff359101.aspx

it's on core

What are the claims in ASP.NET Identity

+1
source

Here are some snippets of code on how you can achieve this using Azure Active Directory. Application setup in Startup.cs:

 public void ConfigureApplication(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { ... app.UseIISPlatformHandler(); app.UseStaticFiles(); app.UseCookieAuthentication(options => { options.AutomaticAuthenticate = true; }); app.UseOpenIdConnectAuthentication(options => { options.AutomaticChallenge = true; options.ClientId = Configuration.Get<string>("Authentication:AzureAd:ClientId"); options.Authority = Configuration.Get<string>("Authentication:AzureAd:AADInstance") + "Common"; options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false, RoleClaimType = "roles" }; options.Events = new OpenIdConnectEvents { OnAuthenticationValidated = (context) => Task.FromResult(0), OnAuthenticationFailed = (context) => { context.Response.Redirect("/Home/Error"); context.HandleResponse(); // Suppress the exception return Task.FromResult(0); }, OnRemoteError = (context) => Task.FromResult(0) }; }); app.UseMvc(routes => { routes.MapRoute(name: "default", template: "{controller=Dashboard}/{action=Index}/{id?}"); }); DatabaseInitializer.InitializaDatabaseAsync(app.ApplicationServices).Wait(); } 

And here is the use:

 [Authorize(Roles = "SuperAdmin, Worker")] public ActionResult Index() { ViewBag.Message = "Hello"; return View(); } 

and:

 public ActionResult Submit(FormCollection formCollection) { if (User.IsInRole("SuperAdmin") || User.IsInRole("Worker")) { ... } if (User.IsInRole("Admin")) { //do some admin tasks } return RedirectToAction("Index", "Tasks"); } 

Here is my blog post: http://www.eidias.com/blog/2016/1/16/using-azure-active-directory-application-roles . You can find how to configure the above roles in AAD.

0
source

Source: https://habr.com/ru/post/1011759/


All Articles