我们正在使用 React 和 ASP.Net 核心 Web API 构建 SPA。
React 会将 Auth_Token 传递给 ASP.Net 核心 Web API 以进行身份验证,这有效。
As App Registration is done for the
front-end application
along withScope & Roles
, I am not sure how to implement Authentication for Swagger in ASP.Net core Web API.
目前我有如下swagger配置
private void AddSwagger(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "Track Management API",
});
var xmlCommentsFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlCommentsFullPath = Path.Combine(AppContext.BaseDirectory, xmlCommentsFile);
c.IncludeXmlComments(xmlCommentsFullPath);
var jwtSecurityScheme = new OpenApiSecurityScheme
{
Scheme = "bearer",
BearerFormat = "JWT",
Name = "JWT Authentication",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Description = "Put **_ONLY_** your JWT Bearer token on textbox below!",
Reference = new OpenApiReference
{
Id = JwtBearerDefaults.AuthenticationScheme,
Type = ReferenceType.SecurityScheme
}
};
c.AddSecurityDefinition(jwtSecurityScheme.Reference.Id, jwtSecurityScheme);
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{ jwtSecurityScheme, Array.Empty<string>() }
});
});
}
目前,我们必须在 ASP.Net 核心 Web API 之外获取 Auth_Token 并将其传递给它。
开发者能否直接从Swagger页面生成所需的Auth_Token来简化这个过程?
更新:下面的 Swagger 配置尝试获取所需的 auth_code,但是它使用 Web API URL 作为重定向 URL
但失败了。我想要的是它应该使用前端 URL 作为重定向 URL 来生成 auth_code 但将其传递给 Web API?
c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Description = "OAuth2.0 Auth Code with PKCE",
Name = "oauth2",
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows
{
AuthorizationCode = new OpenApiOAuthFlow
{
AuthorizationUrl = new Uri($"https://login.microsoftonline.com/{this.Configuration.GetValue<string>("AzureAd:TenantId")}/oauth2/authorize"),
TokenUrl = new Uri($"https://login.microsoftonline.com/{this.Configuration.GetValue<string>("AzureAd:TenantId")}/v2.0/token"),
Scopes = new Dictionary<string, string>
{
{ this.Configuration.GetValue<string>("AzureAd:ApiScope"), "Allows Read and Write" }
}
}
}
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" }
},
new[] { this.Configuration.GetValue<string>("AzureAd:ApiScope") }
}
});
我看到的另一个选项是将 Web API URL 添加为较低环境的应用程序注册中的重定向 URL。
最佳答案
您需要配置身份提供者并将新的允许重定向 Uri 添加到 /swagger/oauth2-redirect.html
示例:
"RedirectUris": [
"https://localhost:3379/authentication/login-callback", // for blazor client
"https://localhost:3379/swagger/oauth2-redirect.html" // for swagger client
]
关于c# - SPA 的 Asp.net 核心 Web API - 如何实现 Swagger 身份验证而无需在 Web API 外部获取访问 token 并传递它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73747234/