多服务架构中实现JWT跨服务验证:AdministrationService自动调用UserService校验Token
Got it, let's walk through how to make your AdministrationService automatically check token validity with UserService when the DeleteUser endpoint is called. Here's a step-by-step breakdown:
First, set up JWT bearer authentication in your AdministrationService's Startup.cs (or Program.cs for .NET 6+). This config will tie into UserService for token validation, plus let you add custom checks via a direct API call.
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; // In Startup.cs -> ConfigureServices, or Program.cs for minimal APIs services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { // Base URL of your UserService instance options.Authority = "https://your-userservice-base-url"; // Audience identifier your AdministrationService expects in tokens options.Audience = "administration-service"; // Basic token validation rules options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = "https://your-userservice-base-url", ValidateAudience = true, ValidAudience = "administration-service", ValidateLifetime = true, ClockSkew = TimeSpan.Zero // Optional: tightens tolerance for time drift }; // Add custom logic to call UserService's token validation endpoint options.Events = new JwtBearerEvents { OnTokenValidated = async context => { // Grab an HTTP client from the service provider var httpClient = context.HttpContext.RequestServices .GetRequiredService<IHttpClientFactory>() .CreateClient(); // Extract the raw token from the validated security token var jwtToken = context.SecurityToken as JwtSecurityToken; if (jwtToken == null) { context.Fail("Invalid token format"); return; } // Call UserService's token validation API var validationResponse = await httpClient.PostAsJsonAsync( "https://your-userservice-base-url/api/tokens/validate", new { Token = jwtToken.RawData }); // Reject the request if UserService marks the token as invalid if (!validationResponse.IsSuccessStatusCode) { context.Fail("Token rejected by UserService"); } } }; });
Make sure to add these middleware components to your request pipeline so validation runs before hitting your endpoint:
// For .NET 5 and earlier (Startup.cs -> Configure method) app.UseAuthentication(); app.UseAuthorization(); // For .NET 6+ (Program.cs) app.UseAuthentication(); app.UseAuthorization();
Configure the "Administrator" policy to enforce the required role/claims, working alongside token validation to restrict access to DeleteUser:
services.AddAuthorization(options => { options.AddPolicy("Administrator", policy => { // Adjust this to match the claim type/value your UserService issues for admins policy.RequireClaim("Role", "Administrator"); }); });
Double-check that your DeleteUser endpoint has the [Authorize] attribute with the Administrator policy applied:
[ApiController] [Route("api/users")] public class UserAdministrationController : ControllerBase { [HttpDelete("{userId}")] [Authorize(Policy = "Administrator")] public async Task<IActionResult> DeleteUser(int userId) { // Your user deletion logic goes here return Ok($"User {userId} deleted successfully"); } }
How It All Works
When you send a request from Postman to DeleteUser with a JWT in the Authorization header (formatted as Bearer <your-token>):
- The JwtBearer middleware first validates the token's signature, expiration, issuer, and audience against UserService's authority.
- If basic validation passes, the
OnTokenValidatedevent triggers, calling UserService's custom validation endpoint to confirm the token is still valid (e.g., not revoked). - Only if both checks pass will the request reach your DeleteUser logic. Any failure returns a
401 Unauthorizedor403 Forbiddenresponse automatically.
内容的提问来源于stack exchange,提问作者Juanker

