Search code examples
asp.net-coreasp.net-core-webapiasp.net-core-identity

Asp.Net Core 2 Web API 500 internal server error


when I try to access the API via Postman,

Send:

localhost:5050/api/Auth/token

Body:

{ "UserName": "jouverc", "Password": "P@ssw0rd!" }

to this method:

[Produces("application/json")]
[Route("api/Auth")]
public class AuthController : Controller
{

    #region constructor injection

    private readonly IPasswordHasher<User> _hasher;
    private readonly UserManager<User> _userManager;
    private readonly IConfigurationRoot _config;
    private readonly SignInManager<User> _signInManager;

    public AuthController(IPasswordHasher<User> hasher, UserManager<User> userManager, SignInManager<User> signInManager, IConfigurationRoot config)
    {
        _hasher = hasher;
        _userManager = userManager;
        _signInManager = signInManager;
        _config = config;
    }

        #endregion

    #region createToken

    [HttpPost("token")]
    public async Task<IActionResult> CreateToken([FromBody] CredentialModel model)
    {
        try
        {
            var user = await _userManager.FindByNameAsync(model.UserName); 
            if (user != null) 
            {
                if (_hasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) == PasswordVerificationResult.Success)  
                {
                    return Ok(CreateToken(user)); 
                }
            }
        }
        catch (Exception)
        {
            //log 
        }
        return null;
    }

    private async Task<JwtPacket> CreateToken(User user)
    {
        var userClaims = await _userManager.GetClaimsAsync(user); 

        var claims = new[]
        {
            new Claim(JwtRegisteredClaimNames.Sub, user.UserName), 
            new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString()) 
        }.Union(userClaims);


        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
        var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); 
        var token = new JwtSecurityToken(issuer: _config["Tokens:Issuer"], 
            audience: _config["Tokens:Audience"],
            claims: claims,
            expires: DateTime.UtcNow.AddDays(2),
            signingCredentials: cred
        );
        return new JwtPacket
        {
            Token = new JwtSecurityTokenHandler().WriteToken(token),
            Expiration = token.ValidTo.ToString(),
            UserName = user.UserName
        };

    }

    public class JwtPacket
    {
        public string Token;
        public string UserName;
        public string Expiration;
    }

    #endregion

}

I receive a 500 Internal Server Error:

Unable to resolve service for type 'Microsoft.Extensions.Configuration.IConfigurationRoot' while attempting to activate 'WebAPI.Controllers.AuthController

how should i configurate the Startup?

 public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.

Solution

  • Just change IConfigurationRoot to IConfiguration on the constructor for the controller.

    But what might be better is to use the IOpions pattern for injecting settings into your controller.