I've a code using JWT Bearer to authenticate some tokens as below.
private string GetToken()
{
var issuer = _factory.Configuration.GetValue<string>("JwtSettings:Issuer");
DateTime expiryDate = DateTime.UtcNow.Add(TimeSpan.FromMinutes(1));
var jwtSecurityToken = new JwtSecurityToken(
issuer: issuer,
claims: new List<Claim>()
{
new Claim("a claim", "a claim value")
},
expires: expiryDate,
signingCredentials: new SigningCredentials(
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_factory.Configuration.GetValue<string>
("JwtSettings:Secret"))),
SecurityAlgorithms.RsaSha256Signature
)
);
return new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
}
private HttpClient GetClient()
{
var client = _factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false,
});
var token = GetToken();
client.DefaultRequestHeaders.Add(HttpRequestHeader.Authorization.ToString(), $"Bearer {token}");
return client;
}
But it doesn't work and I don't have any idea cuz I'm new to C-sharp and.Net
It gives me the error of couldn't create the signature
Please Help.
In your code, you have specified SecurityAlgorithms.RsaSha256Signature which is asymmetric key algorithm which requires two keys (private and public key)
For code to work, change SecurityAlgorithms.RsaSha256Signature to SecurityAlgorithms.HmacSha256Signature
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.