https://github.com/dineshkumar-mb/mern-urlbackend
url shortner with authentication
https://github.com/dineshkumar-mb/mern-urlbackend
authentication jwt-token mern
Last synced: over 1 year ago
JSON representation
url shortner with authentication
- Host: GitHub
- URL: https://github.com/dineshkumar-mb/mern-urlbackend
- Owner: dineshkumar-mb
- Created: 2024-07-10T12:45:11.000Z (almost 2 years ago)
- Default Branch: master
- Last Pushed: 2024-07-11T11:41:21.000Z (almost 2 years ago)
- Last Synced: 2024-07-12T11:28:38.664Z (almost 2 years ago)
- Topics: authentication, jwt-token, mern
- Language: JavaScript
- Homepage: https://mern-urlbackend.onrender.com
- Size: 5.86 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
implementing JWT authentication in a Node.js + Express.js API:
Install Dependencies: First, make sure you have Node.js and npm installed. Then, create a new Node.js project and install the necessary packages:
npm install express jsonwebtoken
Create an Authentication Middleware: You’ll need a middleware function to verify JWT tokens. Here’s a simple example:
JavaScript
const jwt = require('jsonwebtoken');
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1]; // Extract the token from the Authorization header
if (token == null) {
return res.sendStatus(401); // Unauthorized
}
jwt.verify(token, 'your-secret-key', (err, user) => {
if (err) {
return res.sendStatus(403); // Forbidden
}
req.user = user; // Attach the user object to the request
next();
});
}
Generate Tokens on Login: When a user logs in, generate a JWT token and send it back to the client:
JavaScript
const token = jwt.sign({ username: 'user123' }, 'your-secret-key', { expiresIn: '1h' });
res.json({ token });
Protect Routes: Apply the authenticateToken middleware to routes that require authentication:
JavaScript
app.get('/protected-route', authenticateToken, (req, res) => {
// Access the user object from req.user
res.json({ message: 'Welcome to the protected route!' });
},
Client-Side Usage: In your client application (e.g., React, Angular, or Vue), store the token (usually in local storage) and include it in the Authorization header for authenticated requests.
Remember to replace 'your-secret-key' with a strong, unique secret key for signing and verifying tokens. Also, consider using environment variables for sensitive information.
## Deployment
- Frontend: Deployed on [Netlify](https://chipper-marigold-f7720c.netlify.app)
- Backend: Deployed on [Render](https://mern-urlbackend.onrender.com)