How to restrict API access with Static Token

kuroco's API security

You have following 4 options for Kuroco's API security:

  • None
  • Static Token
  • Dynamic Token
  • Cookie

You can set "None" if you want to create and test a temporary development API, or if you want to use completely open data. Image (fetched from Gyazo)

However, if you set the API security setting to "None", anyone can use the API, and it will be possible to accept API requests indiscriminately from the outside.

If this situation is not as expected, you can use the Static Token function to impose some restrictions. This tutorial explains how to apply access restrictions using Static Token.

Note:
The character string of StaticToken becomes information that can be viewed from the outside by referring to the network communication of the public site and the description in the JS file. Therefore, if you want to restrict secure information, please do so by restricting login authentication by Dynamic Token / Cookie restriction instead of Static Token or by restricting API by browsing group.

How to restrict API access by Static Token

This section explains how to restrict API access by Static Token.

1. Configure the security of Kuroco API
On any API list page, click [Security].
Image (fetched from Gyazo)

Change the "Security" to Static Token and click [Save] Image (fetched from Gyazo)

2.Issue Static Token
Click [Swagger UI] on the API list page.
Image (fetched from Gyazo)

Enter "Valid Until" of "Generate Static Access Token" at the top of Swagger UI page and click [Generate].
Image (fetched from Gyazo)

Token will be issued. You will need it later so save it.
Image (fetched from Gyazo)

The configuration on the Kuroco management page is now complete.

3. Install axios-middleware
Next, we will configure on the terminal.
Open the terminal(command prompt) and install axios-middlewareon the site using below command:

npm install --save axios-middleware

4. Add plugin on nuxt.config.js
Add below code in nuxt.config.js.

nuxt.config.js
plugins: ['@/plugins/axios']

5. Create "axios.js" file inplugins directory
Create "axios.js" file in plugins directory and add below code:

/plugins/axios.js
import axios from 'axios'

export default function({ $axios }) {
  $axios.onRequest((config) => {
    config.headers['x-rcms-api-access-token'] = 'TOKEN YOU HAVE SAVED'
    return config
  })
}

*We are including the Token information in the file, but in actual projects, it is recommended to write it in other files such as .envb file.

The configuration of API access restriction by Static Token is now complete.

Confirm that API is successfully called

Now, since there is a restriction by Static Token, you get the below response when you try to use API.(StatusCode: 401)

{
    "errors": [
        "[GW] Access Token is required"
    ]
}

Reference