最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get Keycloak access_token using client credentials using axios throws 400 error in NextJS app - Stack Overflow

programmeradmin1浏览0评论

I am trying to get the access_token from keycloak using axios using client credentials. However, I am getting a 400 error when I use axios post request to get the access_token.

I havet tested my client credentials using postman and it does return the access__token however, when using in a NextJS app I get a 400 error:

currently inside my _app.tsx file I have the following method:

const getToken = () => {
  let token: string = undefined;
  const realm = process.env.NEXT_PUBLIC_KEYCLOAK_REALM;
  const keycloakClientSecret = process.env.NEXT_PUBLIC_KEYCLOAK_BEARER_CLIENT_SECRET;
  const kcTokenEndpoint = `http://localhost:8080/auth/realms/${realm}/protocol/openid-connect/token`;

  axios({
    method: 'POST',
    url: kcTokenEndpoint,
    data: {
      client_id: 'keycloak-token-bearer', // create client in keycloak with same name
      client_secret: keycloakClientSecret,
      grant_type: 'client_credentials',
    },
    headers: {
      'Content-type': 'application/x-www-form-urlencoded',
    },
    withCredentials: true,
  })
    .then(response => {
      token = (response as any)?.access_token;
    })
    .catch(error => {
      token = undefined;
    });

  return token;
};

Which I see returns a 400 (Bad Request) error When I check the response I see the following:

error   "invalid_request"
error_description   "Missing form parameter: grant_type"

I am trying to get the access_token from keycloak using axios using client credentials. However, I am getting a 400 error when I use axios post request to get the access_token.

I havet tested my client credentials using postman and it does return the access__token however, when using in a NextJS app I get a 400 error:

currently inside my _app.tsx file I have the following method:

const getToken = () => {
  let token: string = undefined;
  const realm = process.env.NEXT_PUBLIC_KEYCLOAK_REALM;
  const keycloakClientSecret = process.env.NEXT_PUBLIC_KEYCLOAK_BEARER_CLIENT_SECRET;
  const kcTokenEndpoint = `http://localhost:8080/auth/realms/${realm}/protocol/openid-connect/token`;

  axios({
    method: 'POST',
    url: kcTokenEndpoint,
    data: {
      client_id: 'keycloak-token-bearer', // create client in keycloak with same name
      client_secret: keycloakClientSecret,
      grant_type: 'client_credentials',
    },
    headers: {
      'Content-type': 'application/x-www-form-urlencoded',
    },
    withCredentials: true,
  })
    .then(response => {
      token = (response as any)?.access_token;
    })
    .catch(error => {
      token = undefined;
    });

  return token;
};

Which I see returns a 400 (Bad Request) error When I check the response I see the following:

error   "invalid_request"
error_description   "Missing form parameter: grant_type"
Share Improve this question edited Jul 9, 2021 at 17:00 Danila 18.7k2 gold badges54 silver badges79 bronze badges asked Jul 9, 2021 at 16:46 ashes999ashes999 1,3242 gold badges22 silver badges48 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

axios.post is an async operation. Currently you always return undefined from your function because you are not waiting for axios request to resolve.

If you have async function then you can only return a promise from it.

So you either need to do that:

  // Add return here
  return axios({
    method: 'POST',
    url: kcTokenEndpoint,
    data: {
      client_id: 'keycloak-token-bearer', // create client in keycloak with same name
      client_secret: keycloakClientSecret,
      grant_type: 'client_credentials',
    },
    headers: {
      'Content-type': 'application/x-www-form-urlencoded',
    },
    withCredentials: true,
  })
    .then(response => {
      // Return token here
      return (response as any)?.access_token;
    })

Or make getToken function async and await axios request:

const getToken = async () => {
  const realm = process.env.NEXT_PUBLIC_KEYCLOAK_REALM;
  const keycloakClientSecret = process.env.NEXT_PUBLIC_KEYCLOAK_BEARER_CLIENT_SECRET;
  const kcTokenEndpoint = `http://localhost:8080/auth/realms/${realm}/protocol/openid-connect/token`;

  cosnt { response } = await axios({
    method: 'POST',
    url: kcTokenEndpoint,
    data: {
      client_id: 'keycloak-token-bearer', // create client in keycloak with same name
      client_secret: keycloakClientSecret,
      grant_type: 'client_credentials',
    },
    headers: {
      'Content-type': 'application/x-www-form-urlencoded',
    },
    withCredentials: true,
  })

  return response.access_token;
};

Obviously now you need to await getToken function or use then(...) too

use URLSearchParams for encode request.


const getToken = async () => {

  const params: {
      client_id: 'keycloak-token-bearer', // create client in keycloak with same name
      client_secret: keycloakClientSecret,
      grant_type: 'client_credentials',
    },

  const dataParams = new URLSearchParams(params);

  const realm = process.env.NEXT_PUBLIC_KEYCLOAK_REALM;
  const keycloakClientSecret = process.env.NEXT_PUBLIC_KEYCLOAK_BEARER_CLIENT_SECRET;
  const kcTokenEndpoint = `http://localhost:8080/auth/realms/${realm}/protocol/openid-connect/token`;

  const { response } = await axios({
    method: 'POST',
    url: kcTokenEndpoint,
    data: dataParams,
    headers: {
      'Content-type': 'application/x-www-form-urlencoded',
    },
    withCredentials: true,
  })

  return response.access_token;
};

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论