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

ASP.NET-Boilerplate Host项目中如何通过Swagger完成登录认证?

Fixing Swagger UI "Needs Login" Issue After Authorization in ASP.NET Boilerplate Event Host

Hey there! I’ve built several projects with ASP.NET Boilerplate (ABP) and run into this exact Swagger UI issue before—let’s walk through the most common fixes:

1. Verify Swagger Security Configuration

First, make sure your Swagger setup properly recognizes Bearer token authentication. In your SwaggerConfig.cs (usually in the Web.Core project), check that you’ve added the security definition and requirement:

public static void Register(HttpConfiguration config)
{
    config.EnableSwagger(c =>
    {
        c.SingleApiVersion("v1", "Event Host API");
        
        // Add Bearer token security definition
        c.AddSecurityDefinition("Bearer", new ApiKeyScheme
        {
            Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
            Name = "Authorization",
            In = "header",
            Type = "apiKey"
        });
        
        // Require the Bearer token for all endpoints
        c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
        {
            { "Bearer", new string[] {} }
        });
        
        // Other Swagger configs...
    })
    .EnableSwaggerUi(c =>
    {
        // Swagger UI configs...
    });
}

2. Ensure Token Storage & Request Interception Works

ABP’s Event Host example might not automatically attach the token to Swagger requests after login. You need to configure Swagger UI to read the token from storage (like localStorage) and inject it into every request header.

Option 1: Add a Request Interceptor in Swagger UI

Update your EnableSwaggerUi section to include a request interceptor that pulls the token from storage:

.EnableSwaggerUi(c =>
{
    c.RequestInterceptor = request =>
    {
        // Get the token stored after login (ABP uses "Abp.AuthToken" by default)
        var token = localStorage.getItem("Abp.AuthToken");
        
        if (!string.IsNullOrEmpty(token))
        {
            request.headers["Authorization"] = $"Bearer {token}";
        }
        
        return request;
    };
    
    // Other UI configs...
});

Option 2: Use a Custom JavaScript Injection

If the interceptor doesn’t work, inject a custom JS file to handle authorization:

  1. Add a swagger-auth.js file to your Web.Core project (set its "Copy to Output Directory" property to "Copy if newer"):
(function() {
    // Override the authorize button behavior to attach the token
    const originalAuthorize = window.uiAuthorize;
    window.uiAuthorize = function() {
        originalAuthorize();
        
        const token = localStorage.getItem("Abp.AuthToken");
        if (token) {
            const swaggerUi = window.swaggerUi;
            swaggerUi.api.clientAuthorizations.add(
                "Bearer",
                new window.SwaggerClient.ApiKeyAuthorization("Authorization", `Bearer ${token}`, "header")
            );
        }
    };
})();
  1. Inject this file into Swagger UI:
.EnableSwaggerUi(c =>
{
    c.InjectJavaScript(typeof(SwaggerConfig).Assembly, "YourProjectName.Web.Core.Scripts.swagger-auth.js");
});

3. Validate ABP Token Auth Configuration

Double-check your TokenAuthConfig in Startup.cs (Web.Core project) to ensure the JWT settings match what Swagger expects:

public void ConfigureServices(IServiceCollection services)
{
    // Other services...
    
    services.Configure<TokenAuthConfiguration>(configuration =>
    {
        configuration.Issuer = configuration["Authentication:JwtBearer:Issuer"];
        configuration.Audience = configuration["Authentication:JwtBearer:Audience"];
        configuration.SigningKey = configuration["Authentication:JwtBearer:SecurityKey"];
        configuration.Expiration = TimeSpan.FromDays(1);
    });
}

4. Check for CORS Issues (If Applicable)

If your Swagger UI is hosted on a different domain than your API, make sure your CORS policy allows the Authorization header:

services.AddCors(options =>
{
    options.AddPolicy("AllowAll", builder =>
    {
        builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader()
               .AllowCredentials();
    });
});

Start with the first two steps—they’re the most likely culprits. After making these changes, restart your app, log in via Swagger’s "Authorize" button, and test an endpoint—you should no longer see the "needs login" prompt.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:48:55