You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
13 Hrs
11 Min
31 Seg

Firmando un JSON Web Token

9/25
Resources

How to sign a JSON Web Token?

Signing a JSON Web Token (JWT) is an essential process to guarantee the authenticity and integrity of data transferred in web applications. Using the jsonwebtoken library, we can implement a signing system in three fundamental steps: define the payload, choose the appropriate algorithm and sign the token with a secret or private key. This implementation is crucial to protect your endpoints and ensure secure data communication.

What do we need to sign a JWT?

  • Payload: It is the JSON object that contains the Claim Names, such as sub, name and exp. Using the verified user information is vital for its correct creation.
  • Secret or Private Key: Depending on the signing algorithm:
    • Symmetric (HS256): Uses a secret.
    • Asymmetric (RS256): Uses a private key.
  • Options or callback function: It can include additional configurations for the JWT.

Practical implementation in Node.js

Construction of the payload

Before proceeding to signing, it is vital to structure the payload correctly. Here is an example of how this could be done:

const user = /* We assume the user is previously defined and verified */;const payload = { sub: user.id, // Subject is usually the user ID name: user.full_name, // We use the full name since we don't have a 'name' field exp: Math.floor(Date.now() / 1000) + (60 * 1) // Expiration in 1 minute};

Signing the token

To sign the token, we first import the jsonwebtoken library and then use the sign method:

const jwt = require('jsonwebtoken');const secret = process.env.SECRET_KEY; // A good practice is to use environment variables
const token = jwt.sign(payload, secret);

Recommendations for handling the secret

  • Make sure that the secret is a long random string.
  • Use environment variables to store the secret and other sensitive data.
  • Never expose your secret or private key in the repository.

Testing and verification in Postman

To verify that the server and endpoints are working properly, first verify access to the public endpoint:

  1. Make a request to public to confirm that the server is running.
  2. Request the endpoint token to obtain the signed JWT.
  3. Evaluate the received token by accessing the private endpoint.

Challenge for the reader: Implement in another language.

A great exercise would be to perform this same implementation of signing a JWT in another programming language other than Node.js. This will not only help you broaden your skills, but also help you understand the differences between implementations in different environments.

Go ahead and put your knowledge into practice, explore new languages and keep improving your skills in web application programming and security!

Contributions 4

Questions 2

Sort by:

Want to see more contributions, questions and answers from the community?

Adjunto los codigos que uso en python para la creaci贸n de los tokens en FastAPI.


# Esta funci贸n firma los tokens


def signJWT(email: str, perfil: int):
    payload = {
        "userID": email,
        "perfilID": perfil,
        "expiry": time.time() + 600
    }
    token = jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM)

    return token_response(token)


//Using C# Net7
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace PlayOauth
{
    public class JwtHandler
    {
        private readonly string secretKey;

        public JwtHandler(string secretKey)
        {
            this.secretKey = secretKey;
        }

        public string GenerateToken(string username, int expirationMinutes = 60)
        {
            var key = Encoding.ASCII.GetBytes(secretKey);
            var tokenHandler = new JwtSecurityTokenHandler();
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.Name, username),
                }),
                Expires = DateTime.UtcNow.AddMinutes(expirationMinutes),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token);
        }
    }
}

private async Task<Tuple<string, string>> GenerateToken(IdentityUser user)
        {
            var jwtTokenHandler = new JwtSecurityTokenHandler();

            var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_jwtSettings.Key));

            var userClaims = await _userManager.GetClaimsAsync(user);

            var roles = await _userManager.GetRolesAsync(user);

            var roleClaims = new List<Claim>();

            foreach (var item in roles)
            {
                roleClaims.Add(new Claim(ClaimTypes.Role, item));
            }

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                    {
                        new Claim("Id",user.Id),
                        new Claim(JwtRegisteredClaimNames.Email,user.Email),
                        new Claim(JwtRegisteredClaimNames.Sub,user.UserName),
                        new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString()),
                    }.Union(userClaims)
                     .Union(roleClaims)
                    ),
                Expires = DateTime.UtcNow.Add(_jwtSettings.ExpireTime),
                SigningCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256Signature)
            };
            var token = jwtTokenHandler.CreateToken(tokenDescriptor);
            var jwtToken = jwtTokenHandler.WriteToken(token);

            var refreshToken = new RefreshToken
            {
                JwtId = token.Id,
                IsUsed = false,
                IsRevoked = false,
                UserId = user.Id,
                CreatedDate = DateTime.UtcNow,
                ExpireDate = DateTime.UtcNow.AddMonths(6),
                Token = $"{GenerateRandomTokenCharacters(35)}{Guid.NewGuid()}"
            };

            await _cleanArchitectureIdentityDbContext.RefreshTokens!.AddAsync(refreshToken);
            await _cleanArchitectureIdentityDbContext.SaveChangesAsync();

            return new Tuple<string, string>(jwtToken, refreshToken.Token);


        }
Qu茅 clase tan increible