API with JWT authentication

Asked

Viewed 176 times

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.

  • 1

    could you let me know what is the jsonwebtoken library and the jsonwebtoken link you are using? Because there are different strands of it.

  • using Microsoft.IdentityModel.Tokens; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims;

1 answer

1

Good morning.

You should first add 4 references to the project:

  1. Microsoft.AspNet.Webapi.Owin
  2. Microsoft.Owin.Host.System.Web
  3. Microsoft.Owin.Security.Oauth
  4. Microsoft.Owin.Cors

Once this is done you should create a Owin startup file (Startup.Cs)

In it you must configure which url to call will be returned the authentication token.

After this you must be creating a Precedent that will be responsible for validating the user authentication, which would be where you would check, for example the user and password, to authenticate the user.

Can a project, which use introduction for a course, which has the connection to a bank and performing authentication using the Bearer Token. In this project I use Sql Server + Entity Framework. https://github.com/felippetadeu/cursoextensao_webapi_netframework_aula1/blob/master/Aula1/DocumentAula/documento%20aula.txt

  • 1

    Good morning, first thank you @Felippe. I made a mix of content and I arrived at a solution I don’t know if it’s as right as yours, but I implemented it in a little different way. I didn’t use all the references you cited. I created an internal class that inherits from Delegatinghandler and implemented the authentication in it, the step of generating the generated tokens normal. I don’t even remember where I found the contents, but it’s working, apparently. My project is on Github https://github.com/AugustHTPereira/GiveMe

Browser other questions tagged

You are not signed in. Login or sign up in order to post.