为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
炎炎设计 2023-07-09 17:51:34
我已经为此奋斗了几个小时,似乎无法找出为什么我对[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 前端,看起来不错。
查看完整描述

1 回答

?
江户川乱折腾

TA贡献1851条经验 获得超5个赞

你已经在那里了,但是curl有一个拼写错误,更改AuthorisationAuthorization

curl -X GET“ https://localhost:44370/api/accounts ”-H“接受:application/json”-H“授权:Bearer eyJ.....


查看完整回答
反对 回复 2023-07-09
  • 1 回答
  • 0 关注
  • 91 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信