Authentication and Authorization in MEAN Stack
Implementing authentication and authorization is critical for securing a MEAN stack application. JSON Web Tokens (JWT) are often used to manage secure login and access controls.
Setting Up JWT in Node.js
First, install the necessary packages:
npm install jsonwebtoken bcryptjs
Then, create a middleware to generate and verify tokens.
// JWT Middleware
const jwt = require('jsonwebtoken');
const secret = 'your-secret-key';
function generateToken(user) {
return jwt.sign({ id: user._id }, secret, { expiresIn: '1h' });
}
function verifyToken(req, res, next) {
const token = req.headers['authorization'];
if (!token) return res.status(403).send('No token provided.');
jwt.verify(token, secret, (err, decoded) => {
if (err) return res.status(500).send('Failed to authenticate token.');
req.userId = decoded.id;
next();
});
}
Frontend Implementation in Angular
In Angular, use services to manage user authentication status and intercept HTTP requests with JWT.
// Auth Service in Angular
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private tokenKey = 'auth-token';
constructor(private http: HttpClient) {}
login(credentials) {
return this.http.post('/api/login', credentials).subscribe((response: any) => {
localStorage.setItem(this.tokenKey, response.token);
});
}
isAuthenticated() {
return !!localStorage.getItem(this.tokenKey);
}
}
Protecting Routes
To protect routes in Angular, use route guards to check authentication status.
Leave a Reply