Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to add claims in an ASP.NET Core middleware after Authentication?

I have this in my startup:

public void Configure(IApplicationBuilder app, IHostingEnvironment env) {     if (env.IsDevelopment())     {         app.UseDeveloperExceptionPage();     }     else     {         app.UseHsts();     }      app.UseHttpsRedirection();     app.UseStaticFiles();     app.UseSwaggerWithUi();      app.UseAuthentication();     app.UseMiddleware<SomeMiddleware>();      app.UseMvc(); } 

I need to add some additional claims AFTER the user is authenticated, but the middleware Invoke function always fires before Auth (HttpContext.User.Identity.IsAuthenticated is false). But when it hits the controller the user is authenticated fine.

Any idea what to do here? I've tried to put "app.UseAuthentication()" after calling app.UseMiddleware but it has no affect.

I'm currently using multiple Authentication schemes. I'm not sure if that has an affect.

like image 214
Yodacheese Avatar asked Nov 14 '18 02:11

Yodacheese


People also ask

How can add additional claims in core identity in asp net?

Extend or add custom claims using IClaimsTransformation The IClaimsTransformation interface can be used to add extra claims to the ClaimsPrincipal class. The interface requires a single method TransformAsync. This method might get called multiple times.

How would you implement claims based authentication in .NET Core?

The claims-based authorization works by checking if the user has a claim to access an URL. In ASP.NET Core we create policies to implement the Claims-Based Authorization. The policy defines what claims that user must process to satisfy the policy. We apply the policy on the Controller, action method, razor page, etc.


1 Answers

Yes it's possible, but instead of adding to the list of existing claims you have to add a new identity of type ClaimsIdentity.

public class SomeMiddleware {     private readonly RequestDelegate _next;      public SomeMiddleware(RequestDelegate next)     {         _next = next;     }      public async Task InvokeAsync(HttpContext httpContext)     {         if (httpContext.User != null && httpContext.User.Identity.IsAuthenticated)         {             var claims = new List<Claim>             {                 new Claim("SomeClaim", "SomeValue")             };              var appIdentity = new ClaimsIdentity(claims);             httpContext.User.AddIdentity(appIdentity);                         }          await _next(httpContext);     } } 
like image 50
Alexey Andrushkevich Avatar answered Sep 29 '22 11:09

Alexey Andrushkevich