I have this in my startup:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperE
It depends on what do you want to do and which scheme you use.
For example, if you use JwtBearer
then you could utilize JwtBearerOptions.Events
to handle particular events raised by the middleware. You need to set that in your ConfigureServices
method of Startup
class.
That would give you more granular control of what precise case you want to have your Claims added to, for example, OnTokenValidated
.
The preferred way for .NET Core 2.x is to use IClaimsTransformation, this has a single method TransformAsync(ClaimsPrincipal) with the note
Provides a central transformation point to change the specified principal. Note: this will be run on each AuthenticateAsync call, so its safer to return a new ClaimsPrincipal if your transformation is not idempotent.
Depending on the nature of the enrichment I add the claims to the existing authenticated identity or create a new identity with and mark that as authenticated. With the second idea you can make your method idempotent by checking for your custom identity before attempting the enrichment.
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);
}
}
You can add another middleware immediately after the UseAuthentication()
to add claims :
app.UseAuthentication();
app.Use(async(context, next)=>{
if(context.User !=null && context.User.Identity.IsAuthenticated){
// add claims here
context.User.Claims.Append(new Claim("type-x","value-x"));
}
await next();
});
// call other middlewares
app.UseMiddleware<SomeMiddleware>();
You could write your own middleware to add new claims.
public class YourCustomMiddleware
{
private readonly RequestDelegate _next;
public YourCustomMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext httpContext)
{
if (httpContext.User != null && httpContext.User.Identity.IsAuthenticated)
{
httpContext.User.Identities.FirstOrDefault().AddClaim(new Claim("your claim", "your field"));
}
await _next(httpContext);
}
}
and in your app startup
app.UseAuthentication();
app.UseMiddleware<YourCustomMiddleware>();