Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add claims to windows user

I have a dotnet core api app with windows app enabled. We have bunch of users which have special permission 'admin' and are stored in database, rest all have default permission 'user'. I want users to have extra claims who all are in database. Also I want to store more information like emailid, employee number(which I have to query from LDAP manually)

What I thought is I will have one api, say api/auth which will capture the current user and add claims based on database and ldap query and other api end points can use it.

But I am not able to get how to add and persist claims between different api end points.

Is it possible, and or is it a good way? I have second option to hit the database on each api call.

Edit 1: I have written a middleware which intercepts all api request and searches LDAP/database, creates an ClaimsIndentity and add it to Users.Identity. Then it is available through rest of the call.

Edit 2: When I am @Ondra Starenko's answer, I am not able to reference IClaimsTransformer or app.UseClaimsTransformation. Is there something else I need to include.

Platform: .NET core 2.1.3

like image 277
Priyesh Kumar Avatar asked Jun 12 '18 18:06

Priyesh Kumar


People also ask

What are claims in user?

Claims are pieces of information about a user that have been packaged, signed into security tokens and sent by an issuer or identity provider to relying party applications through a security token service (STS).

Where are user claims stored?

By default, a user's claims are stored in the authentication cookie. If the authentication cookie is too large, it can cause the app to fail because: The browser detects that the cookie header is too long.


1 Answers

You can add Claims to windows user in the ClaimsTransformer class.

public class ClaimsTransformer : IClaimsTransformer
{
   public Task<ClaimsPrincipal> TransformAsync(ClaimsTransformationContext context)
   {
      //add new claim
      var ci = (ClaimsIdentity) context.Principal.Identity;
      var c = new Claim(ClaimTypes.Role, "admin");
      ci.AddClaim(c);

      return Task.FromResult(context.Principal);
   }
}

And add this line to Startup:

app.UseClaimsTransformation(o => new ClaimsTransformer().TransformAsync(o));

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
   loggerFactory.AddConsole(LogLevel.Debug);
   loggerFactory.AddDebug();

   app.UseClaimsTransformation(o => new ClaimsTransformer().TransformAsync(o));

   app.UseStaticFiles();

   app.UseMvc();
}

For more information see this: add claims to windows identity.

like image 200
Ondra Starenko Avatar answered Oct 07 '22 17:10

Ondra Starenko