Я реализовал JWT для. net основного клиента, но когда я добавляю атрибут авторизации, он каждый раз дает мне 401 несанкционированный ответ. Я попытался упомянуть имя схемы в атрибуте. Изменяет последовательность промежуточного программного обеспечения. прошел через множество ссылок из переполнения стека.
Ниже приведен файл startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerDocumentation();
services.ConfigureCors();
services.ConfigureIISIntegration();
services.ConfigureLoggerService();
services.ConfigureSqlContext(Configuration);
services.ConfigureRepositoryWrapper();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "http://localhost:5000",
ValidAudience = "http://localhost:4200/",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@345"))
};
});
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerManager logger)
{
app.UseSwaggerDocumentation();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpStatusCodeExceptionMiddleware();
app.UseCors("CorsPolicy");
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.All
});
app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == 404
&& !Path.HasExtension(context.Request.Path.Value))
{
context.Request.Path = "/index.html";
await next();
}
});
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc();
}
Ниже приведен код инициализации JWT
if (userInfo.Any(c => c.ValidUser == "Y"))
{
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@345"));
var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, vsecGetPasswordByUserName.LoginId),
new Claim(ClaimTypes.Role, "Admin")
};
var tokeOptions = new JwtSecurityToken(
issuer: "http://localhost:5000",
audience: "http://localhost:4200",
claims: claims,
expires: DateTime.Now.AddMinutes(5),
signingCredentials: signinCredentials
);
var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);
return Ok(new { UserInfo = userInfo, TokenString = tokenString });
}
else
{
throw new HttpStatusCodeException(StatusCodes.Status401Unauthorized, @"User not valid");
}
}
и это код контроллера, в котором упоминается атрибут авторизации
[Authorize]
[EnableCors("CorsPolicy")]
[ApiController]
[Route("api/Utility")]
public class UtilityController : ControllerBase