如何在.net Core 2.2中实现JWT令牌

我已经为此奋斗了几个小时,似乎无法找出为什么我对[Authorize]启用的端点的所有调用都失败并出现 401。


在我的 .Net Core 2.2 Web API 项目的 Startup.cs 中,我设置了身份验证:


public void ConfigureServices(IServiceCollection services)

        {

            var jwtSettings = new JwtSettings();

            Configuration.Bind(nameof(jwtSettings), jwtSettings);

            services.AddSingleton(jwtSettings);


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);


            // Add the JWT Bearer token configuration

            services.AddAuthentication(x =>

            {

                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;

                x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;

                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

            })

            .AddJwtBearer(x =>

            {

                x.SaveToken = true;

                x.TokenValidationParameters = new TokenValidationParameters

                {

                    ValidateIssuerSigningKey = true,

                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("craigcraigcraigcraigcraigcraig")),//jwtSettings.Secret)),

                    ValidateIssuer = false,

                    ValidateAudience = false,

                    RequireExpirationTime = false,

                    ValidateLifetime = true

                };

            });


            services.AddSwaggerGen(x =>

            {

                x.SwaggerDoc("v1", new Info { Title = "My Backend", Version = "v1" });

                var security = new Dictionary<string, IEnumerable<string>>

                {

                    {"Bearer", new string[0]}

                };

            });

        }

请注意,我对我的密钥进行了硬编码,因为我不确定这是否是问题所在。

该令牌返回到我的 Swagger 前端,看起来不错。


炎炎设计
浏览 127回答 1
1回答

江户川乱折腾

你已经在那里了,但是curl有一个拼写错误,更改Authorisation为Authorization:curl -X GET“&nbsp;https://localhost:44370/api/accounts&nbsp;”-H“接受:application/json”-H“授权:Bearer eyJ.....
打开App,查看更多内容
随时随地看视频慕课网APP