使用 JWT Bearer 令牌进行身份验证 Swagger [英] Authentication Swagger with JWT Bearer token

查看:31
本文介绍了使用 JWT Bearer 令牌进行身份验证 Swagger的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

We are developing a .Net Core 2.1 Web API with JWT Bearer authentication. The application itself will generate and hand out tokens which are to be send to the backend.

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

While we have everything up and running, i.e. we can send the bearer token from Angular and test it with Postman, Swagger won't send the Bearer token. We have added the Swagger configuration to use a SecurityDefinition as followed, I will post the complete ConfigureServices method:

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",
            });
        });
    }

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

This does add the Authenticate option to the top of the screen. In the configure method we tell the application to actually use the authentication:

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

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

However when we authenticate ourselves with a token, the curl for the function does not show the Bearer token. It looks like Swagger does not send the token to the backend.

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

We use .Net Core 2.1 and Swagger 2.3. Any help would be appreciated, thank you.

推荐答案

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

我也遇到了同样的问题.

I had the very same problem.

两件事是必要的

  1. 您必须像这样放置 bearer <token-here>".只放令牌是行不通的.

  1. You have to put "bearer <token-here>" like this. Putting only token will not work.

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

to get this to work in swagger 2.x, you need to accompany your scheme definition with a corresponding requirement to indicate that the scheme is applicable to all operations in your 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[] { } }
                });
            });

这篇关于使用 JWT Bearer 令牌进行身份验证 Swagger的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆