How to generate a JWT with Net Core

asp.net-core entity-framework-core jwt

Question

Hello i'm confused when creating a token with Net Core, i have followed a guide and is not working when i execute in Postman the Post request.

See, i have my database with ef core migrations, and my User class have UserName and Password {get;set;}.

Then i created an AuthController that contains this:

public class AuthController : Controller
{
    private readonly IConfiguration _configuration;
    private readonly HacsysContext _context;
    public AuthController(IConfiguration configuration, HacsysContext context) {
        _configuration = configuration;
    }


    [AllowAnonymous]
    [HttpPost]
    [Route("token")]
    public IActionResult Post([FromBody]Personal personal)
    {
        if (ModelState.IsValid)
        {
            var userId = GetUserIdFromCredentials(personal);
            if (userId == -1)
            {
                return Unauthorized();
            }

            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, personal.CorreoE),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

            var token = new JwtSecurityToken
            (
                issuer: _configuration["Issuer"],
                audience: _configuration["Audience"],
                claims: claims,
                expires: DateTime.UtcNow.AddDays(10),
                notBefore: DateTime.UtcNow,
                signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["SigningKey"])),
                     SecurityAlgorithms.HmacSha256)
            );

            return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
        }

        return BadRequest();
    }

    private int GetUserIdFromCredentials(Personal personal)
    {
        var userId = -1;

        var email = personal.CorreoE;
        var password = personal.Contrasena;
        if (personal.CorreoE.Equals(email)) 
            {
                userId = 1;
            }



        return userId;


    }
}

Basically, when i compare in GetUserIdFromCredentials if the email is equals to peronal.CorreoE returns always True, even if in Postman i send a POST whith only one letter or diferent Email or different Email that is not in my database.

enter image description here

1
0
4/14/2018 5:19:26 PM

Accepted Answer

You are getting userId 1 everytime because you are first setting the email value to the value of personal.CorreoE and then comparing if the email value is equal to personal.CorreoE.. This will allways be true and therefore return 1.

But what you should do is make a query on the Personal entity in the dbContext to find a person with that email and return userId of the found entity

private int GetUserIdFromCredentials(Personal personal)
{
    var email = personal.CorreoE;
    var password = personal.Contrasena;

    //make a query on the db context
    var dbPerson = _context.Personal.FirstOrDefault(p=> p.Email == email);

    if(dbPerson == null)
        return -1;

    return dbPerson.Id;
}
0
4/14/2018 6:50:03 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow