You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多服务架构中实现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:

1. Configure JWT Authentication in AdministrationService

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");
                }
            }
        };
    });
2. Enable Authentication & Authorization Middleware

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();
3. Set Up the Administrator Authorization Policy

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");
    });
});
4. Secure the DeleteUser Endpoint

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>):

  1. The JwtBearer middleware first validates the token's signature, expiration, issuer, and audience against UserService's authority.
  2. If basic validation passes, the OnTokenValidated event triggers, calling UserService's custom validation endpoint to confirm the token is still valid (e.g., not revoked).
  3. Only if both checks pass will the request reach your DeleteUser logic. Any failure returns a 401 Unauthorized or 403 Forbidden response automatically.

内容的提问来源于stack exchange,提问作者Juanker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:54:41