A 401 Unauthorized status code means the request lacks valid authentication credentials. Here’s how to fix it:
1. Check API Credentials
Ensure the correct API key, token, or credentials are being used.
Example (Bearer Token in Angular):
const headers = { Authorization: `Bearer YOUR_ACCESS_TOKEN` };
this.http.get('https://api.example.com/data', { headers }).subscribe();
2. Use an HTTP Interceptor for Authentication
Automatically attach tokens to requests:
intercept(req: HttpRequest<any>, next: HttpHandler) {
const authReq = req.clone({
setHeaders: { Authorization: `Bearer YOUR_ACCESS_TOKEN` }
});
return next.handle(authReq);
}
3. Handle Token Expiry
If using JWT, refresh the token when expired.
Store and retrieve tokens securely (e.g., from localStorage or cookies).
4. Verify API Endpoint & CORS
Check if the correct API URL is used.
Ensure CORS allows authentication headers.
5. Check User Permissions
Ensure the user has the necessary roles/permissions.