How to Add GitHub OAuth2 Login in Node.js | GitHub OAuth2 Authentication with Passport.js (2024)

  Рет қаралды 864

ProgrammingKnowledge

ProgrammingKnowledge

Күн бұрын

*Title: How to Add GitHub OAuth2 Login in Node.js | GitHub OAuth2 Authentication with Passport.js*
github.com/har...
In this tutorial, learn how to set up GitHub OAuth2 login in your Node.js application using Passport.js. GitHub authentication is a powerful way to allow users to log in using their GitHub accounts, enhancing security and user experience. We’ll go step-by-step through setting up OAuth2 in GitHub, configuring Passport.js in Node.js, and implementing login functionality.
By the end of this video, you’ll have a fully functional GitHub OAuth2 login integrated into your Node.js app!
Prerequisites:
Basic knowledge of Node.js and Express.js
GitHub account to create OAuth app
Passport.js installed in your project
Steps to Implement GitHub OAuth2 Authentication in Node.js:
#### 1. **Set Up GitHub OAuth App**:
Go to [GitHub Developer Settings](github.com/set....
Click **New OAuth App**.
Fill in the details:
**Application name**: Give a name to your app.
**Homepage URL**: Enter the URL where your app is hosted (localhost for local development).
**Authorization callback URL**: `localhost:3000/auth/github/callback` (or change the port if your app uses a different one).
Click *Register Application* and take note of your *Client ID* and **Client Secret**.
#### 2. **Install Required Packages**:
Open your project in the terminal and install Passport and GitHub strategy:
```bash
npm install passport passport-github2 express-session dotenv
```
#### 3. **Configure Passport.js with GitHub Strategy**:
In your main server file (e.g., `app.js` or `server.js`), require and configure Passport:
```javascript
const passport = require('passport');
const GitHubStrategy = require('passport-github2').Strategy;
const session = require('express-session');
require('dotenv').config();
app.use(session({
secret: 'your_secret_key',
resave: false,
saveUninitialized: true,
}));
app.use(passport.initialize());
app.use(passport.session());
```
Set up Passport’s GitHub strategy:
```javascript
passport.use(new GitHubStrategy({
clientID: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
callbackURL: "localhost:3000/auth/github/callback"
},
(accessToken, refreshToken, profile, done) = {
// Here you would find or create a user in your database
return done(null, profile);
}
));
passport.serializeUser((user, done) = done(null, user));
passport.deserializeUser((obj, done) = done(null, obj));
```
#### 4. **Set Up Routes**:
Define routes for authentication:
```javascript
// Redirect to GitHub for authentication
app.get('/auth/github', passport.authenticate('github', { scope: ['user:email'] }));
// GitHub callback URL
app.get('/auth/github/callback',
passport.authenticate('github', { failureRedirect: '/' }),
(req, res) = {
res.redirect('/profile'); // Redirect to profile page after login
});
// Route to log out
app.get('/logout', (req, res) = {
req.logout();
res.redirect('/');
});
```
#### 5. **Create Profile and Logout Pages**:
Set up a profile route to show user information:
```javascript
app.get('/profile', (req, res) = {
if (!req.isAuthenticated()) return res.redirect('/');
res.send(`Hello, ${req.user.username}!`);
});
```
#### 6. **Set Environment Variables**:
In a `.env` file, store your GitHub Client ID and Client Secret:
```plaintext
GITHUB_CLIENT_ID=your_client_id
GITHUB_CLIENT_SECRET=your_client_secret
```
#### 7. **Test GitHub Login**:
Start your Node.js server and go to `localhost:3000/auth/github`.
You’ll be redirected to GitHub to authorize access, and then back to your app’s profile page once authentication is successful.
Summary:
After setting up these steps, you’ll have GitHub OAuth2 login functionality integrated with Passport.js in your Node.js app. You can now allow users to log in with their GitHub credentials securely!
Troubleshooting Tips:
**Invalid Callback URL**: Make sure the callback URL in GitHub OAuth App settings matches the callback URL in your code.
**Environment Variables Not Loading**: Verify your `.env` file and make sure you’re using `require('dotenv').config()` at the top of your main file.
**Helpful Resources**:
GitHub OAuth Documentation: [GitHub OAuth](docs.github.co...)
Passport.js Documentation: [Passport.js](www.passportjs....)
#GitHubOAuth #NodeJS #PassportJS #Authentication #GitHubLogin #WebDevelopment #OAuth2 #NodeJSTutorial #JavaScript

Пікірлер
Session Vs JWT: The Differences You May Not Know!
7:00
ByteByteGo
Рет қаралды 199 М.
Ryan Dahl introduces JSR at DevWorld 2024
29:13
Deno
Рет қаралды 112 М.
啊?就这么水灵灵的穿上了?
00:18
一航1
Рет қаралды 58 МЛН
My Daughter's Dumplings Are Filled With Coins #funny #cute #comedy
00:18
Funny daughter's daily life
Рет қаралды 32 МЛН
didn't manage to catch the ball #tiktok
00:19
Анастасия Тарасова
Рет қаралды 33 МЛН
Node.js Doesn’t Suck Anymore
16:59
Web Dev Simplified
Рет қаралды 121 М.
Young People Try Windows XP
14:19
Linus Tech Tips
Рет қаралды 1,4 МЛН
Will Deno 2.0 Replace Node.js?
12:35
Web Dev Simplified
Рет қаралды 82 М.
Proxy vs Reverse Proxy vs Load Balancer | Simply Explained
13:19
TechWorld with Nana
Рет қаралды 152 М.
I'm Ditching Try/Catch for Good!
10:29
Web Dev Simplified
Рет қаралды 96 М.
OAuth 2.0 explained with examples
10:03
ByteMonk
Рет қаралды 145 М.
啊?就这么水灵灵的穿上了?
00:18
一航1
Рет қаралды 58 МЛН