Uploaded by Md Ashikur Rahman Sorol

auto login project in next js

advertisement
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Course No: ECSE 1259
Course Title: CSE 2100
Name of Experiment : auto login project in next js
Experiment No.
: 03
Date of Assign
: 14-11-2022
Date of Submission: 30-12 2022
Submitted By
: MD. ASHIKUR RAHMAN
ID
: 42220200119
Group No.
:A
Remark
Submitted To:
Tahia Tasnim
Lecturer
Department of Computer Science &
Engineering
Northern University Bangladesh
1. Configure JWT and Authentication:
● Set up an authentication system that issues JWT tokens upon successful login.
● Make sure the authentication system uses the same secret key for signing and
verifying JWT tokens across all subdomains.
2. Set the JWT as a Cookie:
●
In your Next.js server code, after a user logs in successfully, set the JWT token
as a cookie with the domain attribute set to the root domain.
● You can use the setCookie function from the cookies library in Next.js to achieve
this.
import { setCookie } from 'cookies';
// After successful login
setCookie({
res,
name: 'jwt',
value: token,
options: {
domain: '.example.com', // Set the root domain here
// Other cookie options like expiration, secure, etc.
},
});
3. Validate JWT Tokens:
● In your Next.js server middleware or API routes, validate the JWT token sent with
each request from the client.
● You can use a JWT library like jsonwebtoken to verify and decode the token.
import jwt from 'jsonwebtoken';
// Middleware function to validate JWT token
export function validateToken(req, res, next) {
const { jwt: token } = req.cookies;
if (!token) {
// Token is missing, redirect to login page
res.redirect('/login');
return;
}
try {
const decoded = jwt.verify(token, 'your-shared-secret-key');
// Token is valid, proceed with the request
req.user = decoded.user;
next();
} catch (error) {
// Token verification failed, redirect to login page
res.redirect('/login');
}
}
// Apply the middleware to API routes or specific pages
// Example:
// pages/api/profile.js
import { validateToken } from './middleware';
export default function profileHandler(req, res) {
// Validate token middleware
validateToken(req, res, () => {
// Token is valid, handle the request
res.status(200).json({ message: 'Profile page' });
});
}
4. Redirect to Login if JWT is Invalid:
● If the JWT token is missing, expired, or fails verification, redirect the user to the
login page of the root domain.
● You can use the res.redirect function to redirect the user to the login page.
// Example in a Next.js API route
export default function protectedHandler(req, res) {
if (!req.user) {
// User is not authenticated, redirect to login page
res.redirect('/login');
return;
}
// User is authenticated, handle the request
res.status(200).json({ message: 'Protected page' });
}
Download