添加身份验证Jwt令牌

时间:2019-01-05 00:27:48

标签: c# asp.net-mvc jwt

我是第一次使用JWT。很抱歉有一个愚蠢的问题。 下面的此方法可以正确生成令牌,但是此令牌不会作为身份验证添加到标头中。谁能告诉我我做错了什么?当我在Postman中手动添加身份验证令牌时,它可以正常工作。我的问题是为什么client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", tokenHandler.WriteToken(securityToken));  不会自动添加验证承载。

 public User Authenticate(User user)
    {
        var tokenHandler = new JwtSecurityTokenHandler();
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.Id.ToString()) }),
            Expires = DateTime.Now.AddHours(1),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_settings.SecurityKey)), SecurityAlgorithms.HmacSha256Signature)
        };
        var securityToken = tokenHandler.CreateToken(tokenDescriptor);

        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", tokenHandler.WriteToken(securityToken));
        }

        return new User { Id = user.Id, Name = user.Name, Password = "", Email = user.Email };
    }

我的Startup.cs文件。

public void ConfigureServices(IServiceCollection services)
    {
        var appSettingsSection = Configuration.GetSection("Settings");
        var appSettings = appSettingsSection.Get<Settings>();
        services.Configure<Settings>(appSettingsSection);

        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(x =>
        {
            x.RequireHttpsMetadata = false;
            x.SaveToken = true;
            x.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(appSettings.SecurityKey)),
                ValidateIssuer = false,
                ValidateAudience = false,
            };
        });

        services.AddDbContext<BlogContext>(opt => opt.UseInMemoryDatabase("BlogDb"));
        services.AddScoped<UserService>();
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseAuthentication();
        app.UseMvc();
    }

0 个答案:

没有答案