CodexBloom - Programming Q&A Platform

Integrating ASP.NET Core with a microservice architecture for user authentication - Need guidance on JWT setup

๐Ÿ‘€ Views: 0 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-09-12
asp.net-core jwt microservices authentication identityserver csharp

I'm upgrading from an older version and I'm having trouble with I tried several approaches but none seem to work... I'm working on a personal project and During development of a new application, I've been tasked with integrating user authentication across multiple microservices using ASP.NET Core. The goal is to implement a JWT token-based authentication system that allows the main application to interact seamlessly with several backend services. I've set up my IdentityServer for issuing tokens, but Iโ€™m struggling with validating these tokens in my API services. Hereโ€™s a brief overview of what I've done so far: 1. Configured IdentityServer in my `Startup.cs` like so: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddIdentityServer() .AddInMemoryClients(Config.GetClients()) .AddInMemoryApiResources(Config.GetApiResources()) .AddInMemoryIdentityResources(Config.GetIdentityResources()) .AddInMemoryApiScopes(Config.GetApiScopes()) .AddDeveloperSigningCredential(); } ``` 2. My API service is set up to validate the bearer tokens using the following code: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.Authority = "https://localhost:5001"; options.Audience = "api1"; }); } ``` Despite these configurations, I keep receiving a `401 Unauthorized` error when accessing my secured endpoints. Iโ€™ve confirmed that tokens are issued successfully from IdentityServer, but the APIs fail at the authentication step. I've tried including the `ValidIssuer` and `ValidateIssuerSigningKey` options in the JWT configuration, but the results remain unchanged: ```csharp options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = "https://localhost:5001", ValidateAudience = true, ValidAudience = "api1", ValidateLifetime = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("my_secret_key")) }; ``` Iโ€™ve also double-checked the issuer and audience in the token payload to ensure they match what I have in my configurations. Would anyone be able to shed light on potential oversights or best practices to follow in this scenario? Any insights on troubleshooting JWT setups in ASP.NET Core would be greatly appreciated! I'm working on a application that needs to handle this. Am I missing something obvious? I'm working on a application that needs to handle this. Am I approaching this the right way?