Я использую JWT впервые. Извините за немного глупый вопрос.
Этот метод ниже генерирует корректно токен, но этот токен не добавляется в заголовки при аутентификации. Может ли кто-нибудь сказать мне, что я делаю не так? Когда я вручную добавил токен аутентификации в Почтальон, он работает правильно. Мой вопрос, почему 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();
}