Here is some pieces of code how you can achieve that using Azure Active Directory. Configuring the application 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 usage:
[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 on that: http://www.eidias.com/blog/2016/1/16/using-azure-active-directory-application-roles. You can find there how to configure above roles in AAD.