ajmas / vue-authenticate-2

Simple Vue.js authentication library
10 stars 4 forks source link

Bug with Discord example #6

Closed ajmas closed 2 years ago

ajmas commented 2 years ago

While trying to use the Discord config example it turns out we aren't getting the Discord user id. Need to investigate to see what is going wrong and update docs accordingly.

ajmas commented 2 years ago

Turns out it isn't a bug, but i misunderstanding on the flow.

Basically once the front end has received the code fro the OAuth provider, vue-authenticate expects the rest of the flow to be handled by a REST server.

The REST server takes the data, does a token exchange and with the resultant access token can then fetch the user profile.

On the server side three pieces of information will be received:

These then need to be passed as multipart form to https://discord.com/api/oauth2/token

For example (assuming express):


import axios from 'axios';
import qs from 'qs';

async linkAccount (req: Request, res: Response, next: NextFunction) {
  // provided by the Discord OAuth section for your app
  const clientSecret = 'xxxxx';
  try {
    const data = {
      'client_id': req.body.clientId,
      'code': req.body.accessToken,
      'grant_type': 'authorization_code',
      'client_secret': clientSecret,
      'redirect_uri': req.body.redirectUri
    };

    // fetch the access token
    let response = await axios.post('https://discord.com/api/oauth2/token',
      qs.stringify(data),
      {
          headers: {
            'content-type': 'application/x-www-form-urlencoded',
            Authorization: `Bearer ${externalProfile.accessToken}`
          }
      }
    );

    // fetch the user profile
    response = await axios.get('https://discordapp.com/api/users/@me', {
      headers: { Authorization: `Bearer ${response.data.access_token}` }
    });    

    // the user profile
    console.log(response.data);
    res.json({});
  } catch (error) {
    next(error);
  }
}

More details here: https://discord.com/developers/docs/topics/oauth2

This can probably be adapted to other OAuth providers, given the appropriate URLs