Fix jwt token
This commit is contained in:
@@ -1,9 +1,11 @@
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using System.Text.Json.Serialization;
|
||||
using HealthChecks.UI.Client;
|
||||
using Managing.Api.Authorization;
|
||||
using Managing.Api.Filters;
|
||||
using Managing.Api.HealthChecks;
|
||||
using Managing.Application.Abstractions.Services;
|
||||
using Managing.Application.Hubs;
|
||||
using Managing.Bootstrap;
|
||||
using Managing.Common;
|
||||
@@ -155,20 +157,70 @@ builder.Services.Configure<PrivySettings>(builder.Configuration.GetSection(Const
|
||||
builder.Services.AddControllers().AddJsonOptions(options =>
|
||||
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));
|
||||
|
||||
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
|
||||
{
|
||||
o.SaveToken = true;
|
||||
o.TokenValidationParameters = new TokenValidationParameters
|
||||
builder.Services
|
||||
.AddAuthentication(options =>
|
||||
{
|
||||
ValidIssuer = builder.Configuration["Authentication:Schemes:Bearer:ValidIssuer"],
|
||||
ValidAudience = builder.Configuration["Authentication:Schemes:Bearer:ValidAudiences"],
|
||||
IssuerSigningKey = new SymmetricSecurityKey
|
||||
(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Secret"])),
|
||||
ValidateIssuer = false,
|
||||
ValidateAudience = false,
|
||||
ValidateIssuerSigningKey = true
|
||||
};
|
||||
});
|
||||
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||
})
|
||||
.AddJwtBearer(o =>
|
||||
{
|
||||
o.SaveToken = true;
|
||||
o.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidIssuer = builder.Configuration["Authentication:Schemes:Bearer:ValidIssuer"],
|
||||
ValidAudience = builder.Configuration["Authentication:Schemes:Bearer:ValidAudiences"],
|
||||
IssuerSigningKey = new SymmetricSecurityKey
|
||||
(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Secret"])),
|
||||
ValidateIssuer = false,
|
||||
ValidateAudience = false,
|
||||
ValidateIssuerSigningKey = true
|
||||
};
|
||||
o.Events = new JwtBearerEvents
|
||||
{
|
||||
OnMessageReceived = context =>
|
||||
{
|
||||
// If you want to get the token from a custom header or query string
|
||||
// var accessToken = context.Request.Query["access_token"];
|
||||
// if (!string.IsNullOrEmpty(accessToken) &&
|
||||
// context.HttpContext.Request.Path.StartsWithSegments("/hub"))
|
||||
// {
|
||||
// context.Token = accessToken;
|
||||
// }
|
||||
return Task.CompletedTask;
|
||||
},
|
||||
OnAuthenticationFailed = context =>
|
||||
{
|
||||
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
|
||||
{
|
||||
context.Response.Headers.Add("Token-Expired", "true");
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
},
|
||||
// --- IMPORTANT: Attach User to Context Here ---
|
||||
OnTokenValidated = async context =>
|
||||
{
|
||||
var userService = context.HttpContext.RequestServices.GetRequiredService<IUserService>();
|
||||
// Assuming your JWT token contains a 'nameid' claim (or similar) for the user ID
|
||||
var userId = context.Principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||
|
||||
if (!string.IsNullOrEmpty(userId))
|
||||
{
|
||||
// Fetch the full user object from your service
|
||||
var user = await userService.GetUserByAddressAsync(userId);
|
||||
if (user != null)
|
||||
{
|
||||
// Attach the user object to HttpContext.Items
|
||||
context.HttpContext.Items["User"] = user;
|
||||
}
|
||||
}
|
||||
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
// --- END IMPORTANT ---
|
||||
};
|
||||
});
|
||||
|
||||
builder.Services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
|
||||
{
|
||||
@@ -251,14 +303,9 @@ app.UseSentryDiagnostics();
|
||||
// Using shared GlobalErrorHandlingMiddleware from core project
|
||||
app.UseMiddleware<GlobalErrorHandlingMiddleware>();
|
||||
|
||||
app.UseMiddleware<JwtMiddleware>();
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
app.UseRouting();
|
||||
|
||||
app.UseAuthentication();
|
||||
|
||||
app.UseAuthorization();
|
||||
|
||||
app.UseEndpoints(endpoints =>
|
||||
@@ -280,5 +327,4 @@ app.UseEndpoints(endpoints =>
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
app.Run();
|
||||
Reference in New Issue
Block a user