2021年8月29日 星期日

[cat, line, token] How to generate the channel access token

How to generate the channel access token for Line Message API

井民全, Jing, mqjing@gmail.com


Back to the Line Developer FAQ

If you want to adopt the Line Message API in your service,, you will be required to the "Channel Access Token" for LINE authentication. I'll show you how to do that. Check the document contents.


Content of tables

1. Create Channel Access Token 2

1.1. Generate the key-pair 3

1.1.1. The Javascript console (Chrome) 3

1.1.2. NodeJS 5

1.2. Register the Public key 6

1.3. Generate the JWT 7

1.4. Issue Channel Access Token 8

2. Deploy 10

2.1. Deploy to local server 10

2.2. Deploy to heroku 10

3. Setup WebURL 13

3.1. Channel Dashboard 13

3.2. Verify 14

4. Trouble-shooting 14

4.1. Test End-point 15

5. References 16




1. Create Channel Access Token

In order to generate a Line Channel Access Token, we need to proceed the following steps:

Step 1: Create a public/private key-pair for assertion signing

Input: null

Output: (1) the public key and (2) the private key

Save the public/private key-pair at a security place.

Step 2: Register the public key on dashboard to get the kid

Input: (1) the public key

Output: (1) the kid

Save the kid at a security place.

Step 3: Generate the JWT

Input: (1) the private key, (2) kid, (3) channel id (get it from the dashboard)

Output: (1) the JWT

Save the JWT at a security place.  

Step 4: Get the Channel Access Token with the JWT

Input: (1) JWT

Output: (1) Channel-Access-Token string and (2) the Kid string

 Save the Channel-Access-Token and the Kid at a security place.   


Ok, let's go into the detail procedure.

1.1. Generate the key-pair

This procedure will generate a key-pair for assertion signing key. After that, we'll send the generated public key to Line for registering and retrieving the kid string.

Input: null

Output: (1) the public key and (2) the private key

Save the public/prvate key-pair at a security place.

1.1.1. The Javascropt console (Chrome)

The official document provides three methods to generate the key pairs, I choose Chrome brower because that requires no more software installation.

Step 1: Open Chrome browser

Step 2: Paste the following Javascript code to the console of Chrome: [Developper Tools]

(Original)

(async () => {

  const pair = await crypto.subtle.generateKey(

    {

      name: 'RSASSA-PKCS1-v1_5',

      modulusLength: 2048,

      publicExponent: new Uint8Array([1, 0, 1]),

      hash: 'SHA-256'

    },

    true,

    ['sign', 'verify']

  );

   

  console.log('=== private key ===');

  console.log(JSON.stringify(await crypto.subtle.exportKey('jwk', pair.privateKey), null, '  '));

   

  console.log('=== public key ===');

  console.log(JSON.stringify(await crypto.subtle.exportKey('jwk', pair.publicKey), null, '  ')); 

})();



Result

 Save the key-pair at a security place.     


1.1.1.1. Private Key (example)

Note to cut the red text.

=== private key ===

VM628:14 {

  "alg": "RS256",

  "d": "Dqn4bN1x ....",

  "dp": "DOsHtrYl....",

  "dq": "q6W_k4Pq4Xp...",

  "e": "AQAB",

  "ext": true,

  "key_ops": [

    "sign"

  ],

  "kty": "RSA",

  "n": "04ghYezfx_p74l4....",

  "p": "7nuAoWDS1....",

  "q": "4xHW0nJI....",

  "qi": "ehaNFYh..."

}


1.1.1.2. Public key (example)

Paste the public key after removing the "red" text.

VM628:16 === public key ===

VM628:17 {

  "alg": "RS256",

  "e": "AQAB",

  "ext": true,

  "key_ops": [

    "verify"

  ],

  "kty": "RSA",

  "n": "04ghYez..."

}


1.1.2. NodeJS

In order to autoatmic, I copied the javascode to a nodejs project. You can download it from here, https://github.com/jing-tw/lab-cloud/tree/main/lab/line/tools/01-gen-ask.


yarn install

yarn build

yarn start



1.2. Register the Public key

In order to get the kid, you should register the public key.

Input: (1) the public key

Output: (1) the kid

Save the kid at a security place.

Step 1: Go to LINE Developers Console,

 https://developers.line.biz/console/

Step 2: [Channel] -> [Basic settings]: Register a public key

Register your public key to get the kid string for JWT token.

Fig. Register a public key.


Output:

kid: xxxxxxx

 Save the kid  

1.3. Generate the JWT

A JWT defines a compact and self-contained way to transmit information between parties as a JSON object securely. Here, we generate a JWT that will be used to generate our channel access token.

Input: (1) the private key, (2) kid, (3) channel id (get it from the dashboard)

Output: (1) the JWT

Save the JWT at a security place. 


Step 1: Download the tool & Generate the JWT token

  1. Official doc:
    https://developers.line.biz/en/docs/messaging-api/generate-json-web-token/#jwt-use-nodejs

  2. I copied the code and create the nodejs: 

    1. https://github.com/jing-tw/lab-cloud/tree/main/lab/line/tools/02-gen-jwt


yarn install

<Fill the the privateKey, kid, channel-id>

yarn build

yarn start



Step 2: Fill the necessary field

Replace the blue-colored values from yours.

let privateKey = `

YOUR-PRIVATEKEY

`;



let header = {

    alg: "RS256",

    typ: "JWT",

    kid: "YOUR-KID-STRING"

};


let payload = {

    iss: "CHANNEL-ID",

    sub: "CHANNEL-ID",

    aud: "https://api.line.me/",

    exp: Math.floor(new Date().getTime() / 1000) + 60 * 30,

    token_exp: 60 * 60 * 24 * 30

};


    Save the JWT at a security place.  

Verify the JWT

  1. It will be automatically verify in the "Issue Channel Access Token" procedure.

  2. You can chect decripypted heart and payload  fields from the https://jwt.io/.


1.4. Issue Channel Access Token

Now, we have all necessary items for generate the channel access token.

Input: (1) JWT

Output: (1) Channel-Access-Token string and (2) the Kid string

Save the Channel-Access-Token and the Kid at a security place. 

export JWT=YOUR-JWT


curl -v -X POST https://api.line.me/oauth2/v2.1/token \

-H 'Content-Type: application/x-www-form-urlencoded' \

--data-urlencode 'grant_type=client_credentials' \

--data-urlencode 'client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer' \

--data-urlencode 'client_assertion='${JWT}


Ex:


Result

Save the Channel-Access-Token and the Kid at a security place.  


2. Deploy

With the channel access token, now, we can deploy our App and use the Line Message Line. If you have a local server with public ip, you can deploy the App to it. However, I preferred you deploy it to Heroku Server.

2.1. Deploy to local server

Step 1: Get the Line-bot Nodejs SDK

https://github.com/line/line-bot-sdk-nodejs/tree/next/examples/echo-bot-ts


Step 2: Setup the secret

cd line-bot-sdk-nodejs/examples/echo-bot-ts

export CHANNEL_ACCESS_TOKEN=<YOUR_CHANNEL_ACCESS_TOKEN> # that you just created

export CHANNEL_SECRET=<YOUR_CHANNEL_SECRET> # that you can get from the Dashboard

export PORT=<YOUR_PORT> # choose one suitable for your server


Step 3: build & run

yarn install

yarn build

yarn start


2.2. Deploy to heroku

Step 1: Get the Line-bot Nodejs SDK





Step 2: Setup heroku 

cd line-bot-sdk-nodejs/examples/echo-bot-ts

git init

heroku create my-echo-bot-ts

File: .git/config

[core]

        repositoryformatversion = 0

        filemode = true

        bare = false

        logallrefupdates = true

        ignorecase = true

        precomposeunicode = true

[remote "heroku"]

        url = https://git.heroku.com/my-echo-bot-ts.git

        fetch = +refs/heads/*:refs/remotes/heroku/*




Step 3: Setup the secret

heroku config:set CHANNEL_ACCESS_TOKEN=YOUR_CHANNEL_ACCESS_TOKEN

heroku config:set CHANNEL_SECRET=YOUR_CHANNEL_SECRET


Step 4: Push the app to the heroku server

git rm package-lock.json    # (optional) if you want to use yarn, delete npm package-lock file.

git add .

git commit -m "Initial commit for Heroku testing"

git push heroku master

Ex:


Open your app

heroku open

Check log

heroku logs --tail

3. Setup WebURL

3.1. Channel Dashboard

Your channel: [Messaging API] -> [Webhook settings]: Webhook URL

  • The URL format is: 

https://YOUR-APP-URL.heroku.com/webhook

Ex:

3.2. Verify

Click the [Verify]


4. Trouble-shooting

  1. Cannot enable Use webhook

    1. Solution





4.1. Test End-point

Ref: https://developers.line.biz/en/reference/messaging-api/#test-webhook-endpoint


curl -X POST \

-H 'Authorization: Bearer {CHANNEL_ACCESS_TOKEN}' \

-H 'Content-Type:application/json' \

-d '{"endpoint":"https://YOUR-APP-URL.herokuapp.com/webhook"}' \

https://api.line.me/v2/bot/channel/webhook/test


https://App-URL/webhook

Result




5. References

  1. Issue channel access tokens v2.1, https://developers.line.biz/en/docs/messaging-api/generate-json-web-token/

  2. Channel access tokens, https://developers.line.biz/en/docs/messaging-api/channel-access-tokens/#page-title