How to use passport-discord

Viewed 1219

I want to add discord login to my website, and I found this passport-discord package that seems to be the most popular way of doing so. However, I do not understand how I am supposed to use it, as I have little-to-no experience in NodeJS.

My goal is to have a Login button that uses Discord authentication.

My understanding is that I need to instantiate these variables

var passport = require('passport')

var DiscordStrategy = require('passport-discord').Strategy;
 
var scopes = ['identify', 'email', 'guilds', 'guilds.join'];
 
passport.use(new DiscordStrategy({
    clientID: 'id',
    clientSecret: 'secret',
    callbackURL: 'callbackURL',
    scope: scopes
},
function(accessToken, refreshToken, profile, cb) {
    User.findOrCreate({ discordId: profile.id }, function(err, user) {
        return cb(err, user);
    });
}));

And then somehow perform the get request (?) and I should receive a token to then use in the Discord API.

app.get('/auth/discord', passport.authenticate('discord'));

Am I right? How can I embed this into a login button?

2 Answers

You need to generate an oAuth2 URL under this link:

https://discord.com/developers/applications/YOUR_CLIENT_ID/oauth2/url-generator

You need to add a redirect URL to your endpoint (example: http://localhost:3000/auth/discord) on both sides (code and discord application settings)

Then simply add a button on your frontend with the generated link.

Your Link should look like this:

https://discord.com/api/oauth2/authorize?client_id=000000000000000000&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Fdiscord&response_type=code&scope=identify

Firstly you need some configuration of your Discord App in order to use DiscordStrategy

1- Create Discord Application 2- Generate its clientID, clientSecret 3- Finally when you have Application data then you can use it with DiscordStrategy the code you have mentioned used to get the User's details from Discord

Related