使用JWT承载令牌进行身份验证Swagger

时间:2018-03-20 09:00:32

标签: c# .net jwt token swagger

我们正在开发具有JWT承载认证的.Net Core 2.1 Web API。应用程序本身将生成并分发要发送到后端的令牌。

虽然我们已经启动并运行了一切,即我们可以从Angular发送持有者令牌并使用Postman进行测试,但Swagger不会发送承载令牌。 我们已经添加了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",
            });
        });
    }

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

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();
    }

但是,当我们使用令牌验证自己时,该函数的卷曲不会显示Bearer令牌。看起来Swagger不会将令牌发送到后端。

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

2 个答案:

答案 0 :(得分:10)

我遇到了同样的问题。

有两件事是必要的

1)你必须像这样放"bearer <token-here>"。 只放置令牌不起作用。

2) 要使其在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[] { } }
                });
            });

答案 1 :(得分:4)

我也面临同样的问题,但是我正在使用基于OpenAPI的Swagger新版本。因此,我必须在下面的代码段中使用相同的代码。

var securityScheme = new OpenApiSecurityScheme()
{
    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
    Name = "Authorization",
    In = ParameterLocation.Header,
    Type = SecuritySchemeType.Http,
    Scheme = "bearer",
    BearerFormat = "JWT"
};

var securityRequirement = new OpenApiSecurityRequirement
{
    {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "bearerAuth"
                }
            },
            new string[] {}
    }
};

options.AddSecurityDefinition("bearerAuth", securityScheme);
options.AddSecurityRequirement(securityRequirement);