Код: Выделить всё
[Authorize]
[Route("[controller]")]
public class FastaController : Controller
{
[HttpGet()]
public async Task Get(int page = 1, string search = "", int pageSize = 25)
{
// retrieve data here
}
}
Параметры JwtTokenSettings моего файла appsettings.json следующие:
Код: Выделить всё
"JwtTokenSettings": {
"Key": "fc746b61cde4f6665d3f9791446cd5395661860c0075a905ed9810b7391af467",
"Issuer": "Comply",
"Audience": "comply",
"ExpiryHours": 24
}
Токен JWT создается вызов GenerateToken из JwtTokenService, который я написал:
Код: Выделить всё
public class JwtTokenService : IJwtTokenService
{
private readonly IOptions jwtTokenSettings;
public JwtTokenService(IOptions jwtTokenSettings)
{
this.jwtTokenSettings = jwtTokenSettings;
}
public string GenerateToken(Guid userId, string userEmail)
{
string secretKey = jwtTokenSettings.Value.Key;
string issuer = jwtTokenSettings.Value.Issuer;
string audience = jwtTokenSettings.Value.Audience;
var expiryHours = jwtTokenSettings.Value.ExpiryHours;
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, userId.ToString()),
new Claim(JwtRegisteredClaimNames.Email, userEmail),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var token = new JwtSecurityToken(
issuer: issuer,
audience: audience,
claims: claims,
expires: DateTime.UtcNow.AddHours(expiryHours),
signingCredentials: credentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
Код: Выделить всё
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure(
configuration.GetSection("JwtTokenSettings")
);
var jwtSettings = builder.Configuration.GetSection("JwtTokenSettings");
var key = Encoding.UTF8.GetBytes(jwtSettings["Key"]);
builder.Services.AddSingleton();
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = jwtSettings["Issuer"],
ValidAudience = jwtSettings["Audience"],
IssuerSigningKey = new SymmetricSecurityKey(key)
};
});
Код: Выделить всё
var services = this.HttpContext.RequestServices;
var httpContextAccessor = (IHttpContextAccessor)services.GetService(typeof(IHttpContextAccessor));
var userId = httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
Я надеюсь, что все соответствующие фрагменты находятся здесь. Кто-нибудь может помочь обнаружить проблему? Я ОЧЕНЬ ценю помощь!
Подробнее здесь: https://stackoverflow.com/questions/793 ... thenticate