Reputation: 33
I am trying to add authentication to a web api with .Net 5 but I get the error above in the method I am creating the token.
private string CreateToken(User user)
{
List<Claim> claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.Username)
};
// The underlined error is on the line below on the GetSection method.
SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.GetSection("AppSettings:Token").Value));
SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.Now.AddDays(1),
SigningCredentials = creds
};
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
I have done this in a previous project before and it worked fine. Added the same packages in the same version of .Net.
Not sure what else could be causing this.
Thanks.
Upvotes: 0
Views: 931
Reputation: 463
The IConfiguration
interface should come from the Microsoft.Extensions.Configuration
library.
In this case the IConfiguration
interface was a definition from AutoMapper.Configuration
.
Perhaps the Microsoft.Extensions.Options.ConfigurationExtensions
library also may be required because of IOptions<>
.
Upvotes: 2