Problems to get an refresh token using vue, nuxt and keycloak

Good afternoon people. I’m doing a project with vue, nuxt and keycloak as server for token, axios as http client and @nuxtjs/auth-next module for keycloak access.
I’m using a public client so I don’t have a secret key which is the most recommended.
The part of getting the token and talking to the backend is working.
But as it is a public client it has no refresh token.
Searching the internet, a recommendation would be to post from time to time to the keycloak /token endpoint, passing the current token, to fetch a new token.
To perform this post, it doesn’t work to pass json, having to pass application/x-www-form-urlencoded.
But it generates an error saying that the parameter was not passed.
On the internet they recommended passing it as url string, but then it generates an error on the keycloak server, as a parameter that is too long, because of the current token that is passed.
Below is the code used to try to fetch a new token.
This code is being called on a test-only button.
If anyone can help, I appreciate it.

const token = this.$auth.strategy.token.get()

const header = {
“Content-Type”: “application/x-www-form-urlencoded”
}

const body = {
grant_type: “authorization_code”,
client_id: “projeto-ui”,
code: token
}

this.$axios ( {
url: process.env.tokenUrl,
method: ‘post’,
data: body,
headers: header
} )
.then( (res) => {
console.log(res);
})
.catch((error) => {
console.log(error);
} );

A public client can also get a refresh token.
When you say, you don‘t have a refresh token, I assume you are using implicit flow? This is strongly discouraged, as it is considered insecure. The recommended way is using the default auth code flow and enforcing usage of PKCE. This way you also get the refresh token.

2 Likes

Good afternoon people.
Below is the solution to the problem:

  • On the keycloak server:
    it was necessary to put false the part of the implicit flow.
    it was necessary to add web-origins: http://localhost:3000, to allow CORS origins.
  • In nuxt.config.js it was necessary to modify the configuration, as below:
    auth: {
    strategies: {
    keycloak: {
    scheme: ‘oauth2’,

    responseType: ‘code’,
    grantType: ‘authorization_code’,
    codeChallengeMethod: ‘S256’
    }
    }
    }