Auth0 Home Blog Docs

Access Denied / Unauthorized when calling oauth/token to fetch Idp Token

access-token
idp

#1

Hi all!
I’m trying to get Idp Token but always get an Access Denied and Unauthorized response.

I follow this steps:

  1. Create an Machine to Machine App

  2. Set Client_Credentials at Grant Type

  3. Set an API with scope read:users and read:user_idp_token

  4. Use passport-auth0 Strategy and configure login route

    var strategy = new Auth0Strategy({
    domain: ‘xxx’,
    clientID: ‘7saW6f0Zu16m99wrqtRZZNuGHNiri5x6’,
    clientSecret: ‘CFzy1PBwuu73lsejvSxeJudEdupBodPG3bkKnElegIQo280nxh7S0WDdyI-Lc8jh’,
    callbackURL: ‘xxx/callback’
    },
    function (accessToken, refreshToken, extraParams, profile, done) {
    var idToken = extraParams.id_token
    return done(null, {
    id: profile.id,
    access_token: accessToken,
    id_token: idToken,
    profile: profile
    })
    }
    )

  5. Set the route to /login and /callback

    module.exports = (app) => {
    app.get(’/login’,
    passport.authenticate(‘auth0’, {
    audience: ‘xxx/audience’,
    scope: ‘openid profile read:users read:user_idp_tokens offline_access’}), function (req, res) {
    res.redirect(’/’)
    })

    app.get(’/callback’,
    passport.authenticate(‘auth0’, { failureRedirect: ‘/login’ }),
    VideosController.oauthToken
    )

  6. Create a Controller to make call and handle responses
    async oauthToken (req, res, next) {
    try {
    const userId = req.user.id
    axios.post(BASE_URL_OAUTH, {
    headers: { ‘content-type’: ‘application/json’ },
    body: {
    client_id: ‘7saW6f0Zu16m99wrqtRZZNuGHNiri5x6’,
    client_secret: ‘CFzy1PBwuu73lsejvSxeJudEdupBodPG3bkKnElegIQo280nxh7S0WDdyI-Lc8jh’,
    grant_type: ‘client_credentials’,
    audience: ‘xxxx/api/v2/’},
    json: true })
    .then((error, response, body) => {
    if (error) next(error)
    axios.get(BASE_URL + userId, { headers: { Authorization: Bearer + body.access_token } })
    .then((error, response, body) => {
    if (error) next(error)
    body = JSON.parse(body)
    req.idp_access_token = body.identities[0].access_token
    console.log(‘idp access token’, req.idp_access_token)
    }).catch(err => console.error(err))
    })
    .catch(err => console.error(err))
    } catch (err) {
    res.status(500).send({
    error: ‘An error has occured trying to fetch the user’
    })
    }
    }
    }

I’m getting the following error when try get access_token via POST oauth/token:

  response: 
   { status: 401,
     statusText: 'Unauthorized',
     headers: 
      { date: 'Tue, 14 Aug 2018 13:30:15 GMT',
        'content-type': 'application/json',
        'content-length': '60',
        connection: 'close',
        'x-auth0-requestid': 'e46f8b4438bfac49f3d0',
        'x-ratelimit-limit': '30',
        'x-ratelimit-remaining': '29',
        'x-ratelimit-reset': '1534253416',
        'www-authenticate': 'Basic realm="Users"',
        'cache-control': 'private, no-store, no-cache, must-revalidate, post-check=0, pre-check=0' },
     config: 
      { adapter: [Function: httpAdapter],
        transformRequest: [Object],
        transformResponse: [Object],
        timeout: 0,
        xsrfCookieName: 'XSRF-TOKEN',
        xsrfHeaderName: 'X-XSRF-TOKEN',
        maxContentLength: -1,
        validateStatus: [Function: validateStatus],
        headers: [Object],
        method: 'post',
        url: 'https://3ecologias.auth0.com/oauth/token',
        data: '{"headers":{"content-type":"application/json"},"body":{"client_id":"7saW6f0Zu16m99wrqtRZZNuGHNiri5x6","client_secret":"CFzy1PBwuu73lsejvSxeJudEdupBodPG3bkKnElegIQo280nxh7S0WDdyI-Lc8jh","grant_type":"client_credentials","audience":"https://3ecologias.auth0.com/api/v2/"},"json":true}' },
     request: 
      ClientRequest {
        domain: null,
        _events: [Object],
        _eventsCount: 6,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: false,
        _last: true,
        upgrading: false,
        chunkedEncoding: false,
        shouldKeepAlive: false,
        useChunkedEncodingByDefault: true,
        sendDate: false,
        _removedConnection: false,
        _removedContLen: false,
        _removedTE: false,
        _contentLength: null,
        _hasBody: true,
        _trailer: '',
        finished: true,
        _headerSent: true,
        socket: [Object],
        connection: [Object],
        _header: 'POST /oauth/token HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nContent-Type: application/json;charset=utf-8\r\nUser-Agent: axios/0.18.0\r\nContent-Length: 282\r\nHost: 3ecologias.auth0.com\r\nConnection: close\r\n\r\n',
        _onPendingData: [Function: noopPendingOutput],
        agent: [Object],
        socketPath: undefined,
        timeout: undefined,
        method: 'POST',
        path: '/oauth/token',
        _ended: true,
        res: [Object],
        aborted: undefined,
        timeoutCb: null,
        upgradeOrConnect: false,
        parser: null,
        maxHeadersCount: null,
        _redirectable: [Object],
        [Symbol(outHeadersKey)]: [Object] },
     data: { error: 'access_denied', error_description: 'Unauthorized' } } }

What I’m missing?

Thanks!