3
Hello, I am building an API for studies and I am implementing JWT in the authentication of it. All the contents I found refer to Asp.Net Core, as I do for validate tokens in the. Net Framework?
I was following the lessons with Macoratti but the classes are also related to Core.
PS.: Token generation is already implemented.
This is the token generation action implementation.
public IHttpActionResult Post([FromBody] Usuario usuario)
{
Usuario autenticado;
try
{
//REALIZA O LOGIN DO USUÁRIO COM OS DADOS DE LOGIN PASSADOS PELO CORPO DA REQUISIÇÃO
autenticado = N_Usuario.Logar(usuario.Login, usuario.Senha);
}
catch (Exception ex)
{
return BadRequest("LOGIN ERROR " + ex.Message);
}
try
{
if (autenticado != null)
{
//CRIA AS CLAIMS DO USUÁRIO
var Claims = new[]
{
new Claim(ClaimTypes.Name, autenticado.Id.ToString())
};
// GERA A CHAVE DE SEGURANÇA COM BASE NA CHAVE CRIADA
SymmetricSecurityKey SecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Key));
// DEFINE O ALGORÍTIMO DE CRIPTOGRAFIA E GERA AS CREDENCIAIS PARA A ASSINATURA
var Credencials = new SigningCredentials(SecurityKey, SecurityAlgorithms.HmacSha256);
// CRIA O TOKEN DO USUÁRIO
var Token = new JwtSecurityToken(issuer: "EMPRESTEI", audience: "EMPRESTEI", claims: Claims, expires: DateTime.Now.AddMinutes(5), signingCredentials: Credencials);
//RETORNA O TOKEN CRIADO
return Ok(new { Token = new JwtSecurityTokenHandler().WriteToken(Token) });
}
else
return BadRequest("LOGIN ERROR Incorrect credentials."); // CASO NÃO SEJA AUTENTICADO O USUÁRIO
}
catch (Exception ex)
{
return BadRequest("GENERATE TOKEN ERROR " + ex.Message);
}
}
My Startup class was also not created.
could you let me know what is the jsonwebtoken library and the jsonwebtoken link you are using? Because there are different strands of it.
– user148754
using Microsoft.IdentityModel.Tokens; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims;
– Augusto Henrique