Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Roles to Windows Authentication in ASP.NET Core

I created an asp.net core project in visual studio 2015 with windows authentication. I can't figure out how to add roles to the Identity.

I have a table with usernames for the windows account. And when the user opens the website the user is added to the Identity (I assume that's what happens, because I can display the username by User.Identity.Name) and I want to pull out Roles from another table and assign them to the user, is this possible? Or perhaps is there a better way to do it? (Why?, How?)

I couldn't find any examples specific examples related to windows authentication, but I have read the documentation and went through this guide. And I'm still stuck.

like image 628
Anton Toshik Avatar asked Oct 23 '16 20:10

Anton Toshik


1 Answers

With Windows Authentication the roles come from Active Directory, not a database.

You could use Claims Transformation to change the inbound identity on every request to pull extra roles from your database.

public class ClaimsTransformer : IClaimsTransformer
{
    public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        ((ClaimsIdentity)principal.Identity).AddClaim(
            new Claim("ExampleClaim", "true"));
        return Task.FromResult(principal);
    }
}

And then wire it up with

app.UseClaimsTransformation(new ClaimsTransformationOptions
{
    Transformer = new ClaimsTransformer()
});

Note that in the current incarnation there's no DI support, so you'll have to manually pull out your database information from DI if that's where it is.

like image 68
blowdart Avatar answered Oct 05 '22 08:10

blowdart