I'm looking to use Windows Authentication in an ASP.NET 3.0 MVC app with roles I pull from a SQL database for API security. I will decorate the API controller methods with something like [Authorize(Roles = "Admin")]
A lot of what I have here, I've picked up from this site, but I'm stuck on the last part. I can see that the role is applied to the user, but can't get the authorization to work.
To do this, I first start with a ClaimsTransformer, which will be used to apply roles through claims to my users.
ClaimsTransformer.cs
public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
//This sample will automatically apply the Admin role to the user
//In the real app, I will check the user against my DB and apply all roles (as claims) here
var ci = (ClaimsIdentity)principal.Identity;
var c = new Claim(ci.RoleClaimType, "Admin");
ci.AddClaim(c);
return await Task.FromResult(principal);
}
Startup.cs - ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
//Register the ClaimsTransformer here
services.AddSingleton<IClaimsTransformation, ClaimsTransformer>();
//Use windows authentication
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddAuthorization();
}
Starup.cs - Configure
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
DataController.cs
In the API controller, I can set up a method with no authorization like this and see the result showing true when I check if User.IsInRole("Admin");
[HttpGet]
public async Task<IActionResult> GetData1()
{
var result = User.IsInRole("Admin");
return Ok(result);
}
However, if I decorate the controller method with [Authorize(Roles = "Admin")]
like this, then I get a Forbidden response on calls to this method.
[HttpGet]
[Authorize(Roles = "Admin")]
public async Task<IActionResult> GetData1()
{
var result = User.IsInRole("Admin");
return Ok(result);
}