gpt4 book ai didi

c# - 使用 JWT 承载 token 的身份验证 Swagger

转载 作者:太空狗 更新时间:2023-10-29 20:02:26 34 4
gpt4 key购买 nike

我们正在开发具有 JWT Bearer 身份验证的 .Net Core 2.1 Web API。应用程序本身将生成并分发要发送到后端的 token 。

虽然我们已启动并运行所有内容,即我们可以从 Angular 发送不记名 token 并使用 Postman 对其进行测试,但 Swagger 不会发送不记名 token 。我们添加了 Swagger 配置以使用 SecurityDefinition,如下所示,我将发布完整的 ConfigureServices 方法:

public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddCors(options =>
{
options.AddPolicy("AllowAllOrigins",
policy => policy.WithOrigins("*").AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
});
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAllOrigins"));
});

ServiceInstaller.Install(services, Configuration);

// api user claim policy
services.AddAuthorization(options =>
{
var authorizationPolicy = new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser().Build();
options.AddPolicy("Bearer", authorizationPolicy);
});
// add identity
var builder = services.AddIdentityCore<AppUser>(o =>
{
// configure identity options
o.Password.RequireDigit = false;
o.Password.RequireLowercase = false;
o.Password.RequireUppercase = false;
o.Password.RequireNonAlphanumeric = false;
o.Password.RequiredLength = 6;
});
builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
builder.AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();

var keyByteArray = Encoding.ASCII.GetBytes("placekeyhere");
var signingKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(keyByteArray);
services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(
options =>
{
options.TokenValidationParameters = new TokenValidationParameters()
{
IssuerSigningKey = signingKey,
ValidAudience = "Audience",
ValidIssuer = "Issuer",
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
ClockSkew = TimeSpan.FromMinutes(0)
};
});
// Configure JwtIssuerOptions
services.Configure<JwtIssuerOptions>(options =>
{
options.Issuer = "Issuer";
options.Audience = "Audience";
options.SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
});

// Register the Swagger generator, defining one or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "AppName", Version = "v1" });
c.OperationFilter<UploadOperation>();
c.AddSecurityDefinition("Authorization", new ApiKeyScheme
{
Description =
"JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
Name = "Authorization",
In = "header",
Type = "apiKey",
});
});
}

这确实将身份验证选项添加到屏幕顶部。在配置方法中,我们告诉应用程序实际使用身份验证:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
if (env.IsDevelopment())
{
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseCors();
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "AppName"); });
}
app.UseMvc();
}

但是,当我们使用 token 对自己进行身份验证时,该函数的 curl 不会显示 Bearer token 。看起来 Swagger 不会将 token 发送到后端。

我们使用 .Net Core 2.1 和 Swagger 2.3。任何帮助将不胜感激,谢谢。

最佳答案

更新 - Swagger 规范已更改。检查下面@nilay 的回答以获得正确的解决方案。

我遇到了同样的问题。

需要两件事

  1. 你必须输入 "bearer <token-here>"像这样。仅放置 token 是行不通的。

要使其在 swagger 2.x 中运行,您需要在方案定义中附上相应的要求,以表明该方案适用于 API 中的所有操作:

c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
{
{ "Bearer", new string[] { } }
});

完整定义:

services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "Some API", Version = "v1" });
c.AddSecurityDefinition("Bearer", new ApiKeyScheme()
{
Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
Name = "Authorization",
In = "header",
Type = "apiKey"
});
c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
{
{ "Bearer", new string[] { } }
});
});

关于c# - 使用 JWT 承载 token 的身份验证 Swagger,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49379943/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com