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

I am trying to get the access_token from keycloak using axios using client credentials. However, I am g

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;
};

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745337015a4623151.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信