.NET 6中Swagger未传递授权信息至控制器问题排查
我按照教程完成应用注册后,已能通过Swagger完成登录,但Swagger并未将授权信息传递至控制器。
Swagger配置代码
config.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "Test", Version = "V1" }); config.AddSecurityDefinition("OAuth2", new Microsoft.OpenApi.Models.OpenApiSecurityScheme { Description = "OAuth2 which uses authorization flow", Name = "OAuth2", Type = SecuritySchemeType.OAuth2, Flows = new OpenApiOAuthFlows { AuthorizationCode = new OpenApiOAuthFlow { AuthorizationUrl = new Uri(builder.Configuration["SwaggerAzureAD:AuthorozationUrl"]), TokenUrl = new Uri(builder.Configuration["SwaggerAzureAD:TokenUrl"]), Scopes = new Dictionary<string, string> { {builder.Configuration["SwaggerAzureAD:Scope"], "Access API as user" } } } } }); config.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference{Type=ReferenceType.SecurityScheme, Id = "oauth2"} }, new [] {builder.Configuration["SwaggerAzureAD:Scope"]} } }); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(c => { c.OAuthClientId(builder.Configuration["SwaggerAzureAD:ClientId"]); c.OAuthUsePkce(); c.OAuthScopeSeparator(" "); }); }
我已成功登录Swagger(登录状态显示正常),但访问控制器端点时仍提示未授权。
控制器代码
namespace WebApplication2.Controllers { [RequiredScope(RequiredScopesConfigurationKey = "AzureAd:Scopes")] [Authorize] [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet(Name = "GetWeatherForecast")] public IEnumerable<WeatherForecast> Get() { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } } }
请问我哪里操作出错了?
问题排查与修复建议
安全方案ID大小写不匹配
你在AddSecurityDefinition中定义的安全方案ID是"OAuth2"(首字母大写),但在AddSecurityRequirement的引用中写的是"oauth2"(全小写)。OpenAPI的安全方案ID是区分大小写的,这会导致SwaggerUI无法正确关联安全要求,不会自动在请求中携带Token。
修复:将AddSecurityRequirement里的Id = "oauth2"改为Id = "OAuth2",保持和定义时一致。配置项拼写错误
Swagger配置中的AuthorozationUrl存在拼写错误,正确的应该是AuthorizationUrl(少了字母i)。虽然你已经能登录,但这个错误可能导致Token获取流程存在潜在问题,建议修正配置项名称,并同步修改配置文件中的对应键名。Scope配置一致性检查
确认SwaggerAzureAD:Scope配置的值,和控制器[RequiredScope]中指定的AzureAd:Scopes配置值完全一致。如果两者不匹配,即使携带了Token,也会因Scope校验不通过而被拒绝访问。SwaggerUI额外配置优化
可以在SwaggerUI配置中添加以下内容,确保请求自动携带Token并保存授权状态:c.OAuthAppName("Test API"); c.EnablePersistAuthorization(); // 刷新页面后无需重新登录
内容的提问来源于stack exchange,提问作者Roelant M

