Generate Jwt Token With Key

Heads up… this post is old!

  1. Generate Jwt Token With Private Key Online
  2. Generate Jwt Token With Private Key C#
  3. Generate Jwt Token With Public Key

For an updated version of this article, see Create and Verify JWTs with Node.

Create a public / private key pair for signing JWTs. Open a terminal window and use openssl to generate public and private key. Store the private key someplace safe and don't share it. The public key is used in the configuration section. Enable Authorization and then provide the JWT token that you generated from the previous section. JWT Token: Generated from Eclipse above. Enable zapiAccessKey and then provide the access key that you generated from the previous section. Access Key: Retrieved from the pre-requisites above. Enter the contents for the body of the Postman. Create and sign the JWT with your private key for use as a JWT assertion in the request for a scoped access token. You can create this clientcredentials JWT in several ways. For testing purposes, use this tool (opens new window) to generate and sign a JWT. This tool supports both JWT and PEM formats.

JWT, access token, token, OAuth token.. what does it all mean??

Properly known as “JSON Web Tokens”, JWTs are a fairly new player in the authentication space. Being the cool new thing, everyone is hip to start using them. But are you doing it securely? In this article we’ll discuss user authentication best practices in Node.js using JWTs, while showing you how to use the nJwt library for creating and verifying JWTs in your Node.js application.

What is a JSON Web Token (JWT)?

In a nutshell, a JWT is an object that can tell you things about a user and what they’re allowed to do. JWTs are meant to be issued by a trusted authority and given to a user. Typically this means your server is creating the JWT and sending it to your user’s web browser or mobile device for safe keeping.

JWTs can be digitally signed with a secret key. Doing so allows you to assert that a token was issued by your server and was not maliciously modified.

When the token is signed, it is “stateless”: this means you don’t need any extra information, other than the secret key, to verify that the information in the token is “true”. This great feature allows you to remove that pesky session table in your database.

When Should I Use Them?

JWTs are typically used to replace session identifiers. For example: if you’re using a session system which stores an opaque ID on the client in a cookie while also maintaining session in a database for hat ID. With JWTs you can replace both the session data and the opaque ID.

You’ll still use a cookie to store the access token, but you need to make sure you secure your JWT cookies. For more information on that topic I’ll refer you to my other post, Build Secure User Interfaces Using JSON Web Tokens (JWTs).

With the token stored in a secure cookie, the user’s client will supply the token on every subsequent request to your server. This allows the server to authenticate the request, without having to ask for credentials a second time (until the token expires, that is).

How to Create a JWT

There are a few things you’ll need in order to create a JWT for a user, we’ll walk through each of these steps in detail:

  1. Generate the secret signing key
  2. Authenticate the user
  3. Prepare the claims
  4. Generate the token
  5. Send the token to the client

1. Generate the Secret Signing Key

To be secure, we want to sign our tokens with a secret signing key. This key should be kept confidential and only accessible to your server. It should be highly random and not guessable. In our example, we’ll use the node-uuid library to create a random key for us:

Generate Jwt Token With Private Key Online

var secretKey = uuid.v4();

2. Authenticate the User

Before we can make claims about the user, we need to know who the user is. So the user needs to make an initial authentication request, typically by logging into your system by presenting a username and password in a form. It could also mean that they’ve presented an API key and secret to your API service, using something like the Authorization: Basic scheme.

In either situation, your server should verity the user’s credentials. After you’ve done this and obtained the user data from your system, you want to create a JWT which will “remember” the information about the user. We’ll put this information into the claims of the token.

3. Prepare The Claims

Now that we have the user data, we want to build the “claims” of the JWT. That will look like this:

var claims = {
sub: ‘user9876’,
iss: ‘https://mytrustyapp.com’,
permissions: ‘upload-photos’
}

Let’s discuss each of these fields. Technically speaking, you can create a JWT without any claims. But these three fields are the most common:

  • sub – This is the “subject” of the token, the person whom it identifies. For this field you should use the opaque user ID from your user management system. Don’t use personally identifiable information, like an email address.
  • iss – This is the “issuer” field, and it lets other parties know who created this token. This could be the URL of your website, or something more specific if your website has multiple applications with different user databases.

  • permissions – Sometimes you’ll see this as scope if the JWT is being used as an OAuth Bearer Token. This is simply a comma-seperated list of things that the user has access to do.

4. Generate the Token

Now that we have the claims and the signing key, we can create our JWT object:

var jwt = nJwt.create(claims,secretKey);

This will be our internal representation of the token, before we send it to the user. Let’s take a look at what’s inside of it:

console.log(jwt)

You will see an object structure which describes the header and the claims body of the token:

{
header: {
typ: ‘JWT’,
alg: ‘HS256’
},
body: {
jti: ‘3ee9364e-8aca-4e39-8ba2-74e654c7e083’,
iat: 1434695471,
exp: 1434699071,
sub: ‘user9876’,
iss: ‘https://mytrustyapp.com’,
permissions: ‘upload-photos’
}
}

You’ll see the claims that you specified earlier, and many other properties. These are the secure defaults that our library is setting for you, let’s visit each one in detail:

  • alg – This declares how we’ve signed our token, in this case using the Hmac algorithm with a strength of 256 bits. If you want more security, you can bump this up to HS512
  • exp – This is the time that the token will expire, as a unix timestamp offset in seconds. By default our library sets this to 1 hour in the future. If you need to change this value, call jwt.setExpiration() and pass a Date object that represents the desired expiration time.

  • iat – This is the time that the token was created, as a unix timestamp offset in seconds.

  • jti – This is simply a random value, that is created for every JWT. We provide this in case you want to create a database of tokens that were issued. You may do this if you want to implement a token blacklist for tokens that you know have been compromised (i.e. a user tells you their account has been hacked into).

5. Send the Token to the Client

Now that we have the JWT object, we can “compact” it to get the actual token, which will be a Base64 URL-Safe string that can be passed down to the client.

Simply call compact, and then take a look at the result:

var token = jwt.compact();
console.log(token);

What you see will look like this:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIyYWIzOWRhYS03ZGJhLTQxYTAtODhiYS00NGE2YmIyYjk3YWMiLCJpYXQiOjE0MzQ2OTY4MDEsImV4cCI6MTQzNDcwMDQwMX0.qRe18XcmNXB2Ily-U9dwF_8j9DuZOi35HJGppK4lpBw

This is the compact JWT, it’s a three-part string (separated by periods). It contains the encoded header, body, and signature.

How you send the token to the client will depend on the type of application you are working with. The most common use case is a login form on a traditional website. In that situation you will store the cookie in an HttpOnly cookie, so you can simply set the cookie on the POST response.

For example, if you’re using the cookies library for Express:

new Cookies(req,res).set(‘access_token’,token,{
httpOnly: true,
secure: true // for your production environment
});

Once the client has the token, it can use it for authentication. For example, if you’re building a single-page-app, the app will be making XHR requests of your server. When it does so, it will supply the cookie for authentication.

How to Verify JWTs

When a client has a token it will use it to authenticate the user. The token can be sent to your server in a cookie or an HTTP header, such as the Authorization: Bearer header.

For example, if it comes in as a cookie and you’re using the cookies library with your Express app, you could pull the token from the cookie like this:

var token = new Cookies(req,res).get(‘access_token’);

Regardless of how the token comes in, it will be that same compacted string that you sent to the client. To verify the string, you simply need to pass it to the verify method in the library, along with the secret key that was used to sign the token:

var verifiedJwt = nJwt.verify(token,secretKey);

If the token is valid, you can log it to the console and see the same information that you put into it!

{
header: {
typ: ‘JWT’,
alg: ‘HS256’
},
body: {
jti: ‘3ee9364e-8aca-4e39-8ba2-74e654c7e083’,
iat: 1434695471,
exp: 1434699071,
sub: ‘user9876’,
iss: ‘https://mytrustyapp.com’,
permissions: ‘upload-photos’
}
}

If the token is invalid, the verify method will throw an error which describes the problem:

JwtParseError: Jwt is expired

If you don’t want to throw errors you can use the verify function asynchronously:

nJwt.verify(token,secretKey,function(err,token){
if(err){
// respond to request with error
}else{
// continue with the request
}
});

JWTs Made Easy!

That’s it! Creating and verifying JWTs is incredibly simple, especially with the API that nJwt gives you. No go forth and JWT all the services!

But remember: do it securely. While our nJwt library does all the security for the JWT, you also need to ensure that you application is using cookies securely. Please see my other article for an in-depth walkthrough of the security concerns:

Happy verifying!

This guide describes the Assertion Signing Key specification, how to generate a JSON Web Token (JWT) from the signing key, and how to issue a channel access token v2.1 using the generated JWT.

# Diagram for issuing a channel access token v2.1

This diagram shows these three steps:

  • Create an Assertion Signing Key (Step 1 in the diagram)
  • Generate a JWT (Step 6 in the diagram)
  • Issue channel access tokens v2.1 (Step 7 in the diagram)

The authentication method for issuing a channel access token v2.1 is in accordance with Using JWTs as Authorization Grants(RFC 7523)(opens new window). This is the Assertion Framework of OAuth Assertion Framework(RFC 7521)(opens new window) using JSON Web Token(RFC 7519)(opens new window).

# Create an Assertion Signing Key

Issuing an Assertion Signing Key is done in the these two steps:

# 1. Generate a key pair for the Assertion Signing Key

In order to generate a JWT, you must first generate a key pair (private key, public key) for the Assertion Signing Key.

# Assertion Signing Key specification

You can use a JSON Web Key(RFC7517)(opens new window) that meets these criteria as an Assertion Signing Key for JWT.

  1. Must be an RSA public key (RSA is configured in the ktyproperty).
  2. RSA key length is 2048bit.
  3. RS256 (RSASSA-PKCS1-v1_5 with SHA256) is used in the signing algorithm (RS256 is configured in the alg property).
  4. Must state that the public key will be used for signing (appropriate value configured in either use or key_ops).

Therefore, the public key of the Assertion Signing Key must contain these fields:

PropertyDescription
ktyCryptographic algorithm family used in key. Specify RSA.
algAlgorithm used in key. Specify RS256.
useUse of key. Specify sig.*1
key_opsOperation where key is expected to be used. Specify ['verify']. Exclude elements other than verify. *1
eAbsolute value for restoring public key.
nCryptographic index for restoring public key.

*1 Valid if one of either use or key_ops is specified.

An error will occur if the public key of the Assertion Signing Key to be registered contains a kid

kid is issued when a public key is registered in the LINE Developers Console. If the public key contains kid, an error will occur. Make sure the public key you are about to register doesn't contain kid.

The key pair for the Assertion Signing Key can be generated by the developer's own program based on the published specification, but it can be generated more easily by using a library that meets the specification.

Here are two examples of the steps to generate an Assertion Signing Key:

# Generate using Go language command line tools

You can generate a key pair using jwx command line tool(opens new window), which is a part of jwx(opens new window), an open source Go language library used for implementing JWT. Use these steps to issue an Assertion Signing Key.

# 1. Install jwx command line tool

To install the jwx command line tool, a Go language development environment is required beforehand. You can download the development environment from the Go language official site(opens new window).

Execute this command from the path where you installed Go to install the jwx command line tool.

# 2. Generate private key and public key

Use the same path to execute this command and generate a private key.

Generate Jwt Token With Private Key C#

Use this command to generate a public key based on the private key.

If you succeed, a private key (private.key) and public key (public.key) will be generated as below.

private.key example:

public.key example:

# Generate using browser

If your browser supports Web Crypto API(opens new window), you can use the SubtleCrypto.generateKey()(opens new window) method to generate a private key and public key.

Enter this code on your web browser's developer console and execute.

If you succeed, the following private key (private.key) and public key (public.key) are generated.

private.key example:

public.key example:

# 2. Register public key and get kid

Select your channel from the channel settings on the LINE Developers Console and access the Basic settings tab. Next, click the Register public key button next to Assertion Signing Key and enter the public key generated in step 1. Click the Register button.

kid will be displayed if you succeed in registering your public key.

# Generate a JWT

You can use any JWT library(opens new window) or write your own code from scratch to generate a JWT from your Assertion Signing Key.

This is an example created using a JavaScript library introduced in JWT(opens new window). To use this code, you'll need to install these items:

The JWT is a string made up of a header, payload, and signature; all are required fields.

Header

PropertyDescription
algFixed property: 'RS256'
typFixed property: 'JWT'
kidUse the kid property obtained in Create an Assertion Signing Key.

This is an example of a decoded header value.

Payload

PropertyTypeDescription
issStringChannel ID. Found on the LINE Developers Console. Must be equal to sub.
subStringChannel ID. Found on the LINE Developers Console. Must be equal to iss.
audStringhttps://api.line.me/
expNumberThe expiration time of the JWT. Set this value in UNIX timestamp. The max lifetime of a JWT Assertion is 30 minutes.
token_expNumberRequired when requesting a channel access token. This represents a valid expiration time for the channel access token in seconds. The max lifetime of a channel access token is 30 days.

Generate Jwt Token With Public Key

This is an example of a decoded payload value.

Signature

You can generate a JWT by signing the header and payload as shown above with your private key of your Assertion Signing Key.

This is an example of the code used to generate a JWT signed with a private key using node-jose. To create your own JWT with this code, change the privateKey to the value of the private key of your Assertion Signing Key and change the values of header and payload, respectively, and run it. See node-jose(opens new window) for more information on how to use node-jose. Be sure to sign with your private key to prove that the content has not been tampered with.

Example code using node-jose

Sign the base64url-encoded header, base64url-encoded claim set, and a secret key (such as an rsa_private.pem file) using the algorithm you defined in the header. The signature is then base64url-encoded, and the result is the JWT.

Example encoded JWT

# Issue channel access tokens v2.1

You can issue a channel access token v2.1 with the JWT assertion, generated by the procedure in Generate a JWT, specified.

To manage channel access tokens v2.1 using key IDs
  • The response when issuing a channel access token v2.1 includes a channel access token and a unique key ID (key_id) pair. To manage channel access tokens correctly, be sure to store the channel access token and key ID pair at the time of issuing.
  • The key ID is an identifier added to the Messaging API on June 22, 2020. If your app is using a channel access token v2.1 that doesn't have a key ID, we encourage you to re-issue a channel access token v2.1 and store the token and key ID pair. Change your app to always use the new token if the channel access token is re-issued.
  1. To issue a channel access token, specify the generated JWT and execute the Issue channel access token v2.1 endpoint.
  2. Channel access token and key ID are returned from the LINE Platform.
  3. Store the channel access token and key ID pair in a database or other location.

# Revoke channel access token v2.1

You can revoke a channel access token v2.1 with a valid channel access token specified.

Even if specifying an invalid channel access token and executing the Revoke channel access token v2.1 endpoint, no error occurs. To get key IDs paired to the current valid channel access tokens, execute the Get all valid channel access token key IDs v2.1 endpoint.To identify the valid access token, match the obtained key ID to its respective channel access token.

Generate jwt token with private key python
  1. Re-generate a JWT from the stored assertion signing key.
  2. Execute the Get all valid channel access token key IDs v2.1 endpoint with the JWT specified.
  3. The valid channel access token and key ID are returned from the LINE Platform.
  4. Explore the database that stores the channel access token and key ID pair.
  5. Search for the channel access token and key ID pair that match the obtained key ID.
  6. Get the valid channel access token.
  7. Specify the valid channel access token and execute the Revoke channel access token v2.1 endpoint.
  8. The channel access token is revoked from the LINE Platform.