Do not input private or sensitive data. View Qlik Privacy & Cookie Policy.
Skip to main content

Announcements
Join us in Bucharest on Sept 18th for Qlik's AI Reality Tour! Register Now
cancel
Showing results for 
Search instead for 
Did you mean: 
jcampbel1
Contributor II
Contributor II

Getting 401 (Unauthorized) error when calling Qlik api endpoint from javascript

I am trying to call the endpoint 'api/v1/users/me' in my Javascript application however I get a 401 error.
Prior to this, I get an access token via oAuth and this is stored in session storage. I then call this endpoint and pass in the access token, however I get the 401 error. I have also tried to use the API Key in my code and it does not work. I copied the access token that that gets given to me and I try to use it to call the same endpoint in postman and I still get the 401 error.

  const getUserData = async (token: string) => {
    const accessToken = sessionStorage.getItem('qlikAccessToken');
    try {
      const userInfoUrl = 'https://my-tenant.us.qlikcloud.com/api/v1/users/me';
      const response = await fetch(userInfoUrl, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${accessToken}`,
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
      });
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
      }

      const userData = await response.json();
      console.log('User Data:', userData);
    } catch (error) {
      console.error('Error fetching user data:', error);
    }
  };
Labels (2)
1 Solution

Accepted Solutions
DaveChannon
Employee
Employee

As a sense check, do you have the right scopes applied on that token - it looks like you might be requesting a non-Qlik scope in that example?

Ref: https://qlik.dev/authenticate/oauth/scopes/

View solution in original post

6 Replies
rwunderlich
Partner Ambassador/MVP
Partner Ambassador/MVP

can you show the call and body you used to generate the token?

-Rob

jcampbel1
Contributor II
Contributor II
Author

hello, here is how i generate the token.

  const redirectToQlikAuth = async () => {
    const clientId = 'my-client-id'; // Consider moving to environment variables
    const redirectUri = encodeURIComponent(process.env.REACT_APP_REDIRECT_URI || 'http://localhost:3000/CDO-DA/build/redirect');
    const state = crypto.randomUUID();
    const codeVerifier = generateCodeVerifier();
    const codeChallenge = await generateCodeChallenge(codeVerifier);

    sessionStorage.setItem('qlikAuthState', state);
    sessionStorage.setItem('codeVerifier', codeVerifier);

    const qlikAuthUrl = `https://my-tenant.us.qlikcloud.com/oauth/authorize?` +
      `response_type=code&` +
      `client_id=${clientId}&` +
      `redirect_uri=${redirectUri}&` +
      `state=${state}&` +
      `code_challenge=${codeChallenge}&` +
      `code_challenge_method=S256&` +
      `scope=user.profile`;

    window.location.href = qlikAuthUrl;
  };

  const generateCodeVerifier = () => {
    const array = new Uint32Array(56 / 2);
    window.crypto.getRandomValues(array);
    return Array.from(array, dec => ('0' + dec.toString(16)).substr(-2)).join('');
  };

  const generateCodeChallenge = async (codeVerifier: string) => {
    const encoder = new TextEncoder();
    const data = encoder.encode(codeVerifier);
    const digest = await window.crypto.subtle.digest('SHA-256', data);
    return btoa(String.fromCharCode(...Array.from(new Uint8Array(digest))))
      .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
  };
rwunderlich
Partner Ambassador/MVP
Partner Ambassador/MVP

I believe you need to then exchange the authorization code for a token using POST/oauth/token. with an oauth-authorization-code-request. See https://www.qalyptus.com/blog/setting-up-qlik-oauth-for-authentication for a good overview and example.

-Rob
http://www.easyqlik.com
http://masterssummit.com
http://qlikviewcookbook.com

jcampbel1
Contributor II
Contributor II
Author

@rwunderlich , my code does this in the callback method. I get the token from the post endpoint. I then try to call the 'api/v1/users/me' endpoint passing in the Bearer token into the authorization and I am given the following error:

"errors":[{"code":"USERS-7","status":404,"title":"Not found"}]}

 

DaveChannon
Employee
Employee

As a sense check, do you have the right scopes applied on that token - it looks like you might be requesting a non-Qlik scope in that example?

Ref: https://qlik.dev/authenticate/oauth/scopes/

jcampbel1
Contributor II
Contributor II
Author

that was the issue, it works now! thanks