实现Django REST Framework JWT认证(Django REST + Angular 5)
Hey there! Since you’ve confirmed your DRF JWT setup is correctly configured per the official docs, let’s focus on debugging the Angular 5 side of things to get that authorizeToken call working. Here are actionable steps to diagnose and fix the problem:
1. Verify Your JWT Token’s Validity
First, double-check the token itself:
- Use jwt.io to decode your hardcoded token:
- Confirm the
exp(expiration time) claim is still in the future (no expired token) - Ensure the
iss(issuer) and other custom claims match what your DRF backend expects
- Confirm the
- Make sure your hardcoded token has no extra spaces, line breaks, or typos—even a single missing character will break authentication.
2. Check the Authorization Header Format
DRF JWT strictly expects the token to be sent in the Authorization header with the Bearer schema (don’t forget the space after "Bearer"). This is the most common mistake!
Ensure your AuthService constructs the header correctly. Here’s a working example:
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable() export class AuthService { constructor(private http: HttpClient) {} authorizeToken(token: string): Observable<any> { // Build headers with the required Bearer format const authHeaders = new HttpHeaders({ 'Authorization': `Bearer ${token}` }); // Replace with your actual protected endpoint URL return this.http.get('/api/protected-view/', { headers: authHeaders }); } }
- Confirm you’ve imported
HttpClientModulein your Angular app module (Angular 5 usesHttpClientinstead of the legacyHttpservice).
3. Quick Sanity Check on Backend Setup
Even though you said your config is solid, a quick verification won’t hurt:
- Ensure your protected view uses the JWT authentication class:
from rest_framework import views, response, permissions from rest_framework_jwt.authentication import JSONWebTokenAuthentication class AuthorizedView(views.APIView): authentication_classes = [JSONWebTokenAuthentication] permission_classes = [permissions.IsAuthenticated] def get(self, request): return response.Response({'status': 'authorized', 'user': request.user.username})
- Verify your
settings.pyhas JWT set as the default auth class:
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ), }
4. Rule Out CORS Issues
If your Angular frontend and DRF backend run on different ports/domains, you’ll need to configure CORS on the backend:
- Install
django-cors-headersand add it to your installed apps insettings.py - Set
CORS_ALLOWED_ORIGINSto include your Angular app’s URL (e.g.,http://localhost:4200) or useCORS_ALLOW_ALL_ORIGINS = Truefor development (never use this in production!)
5. Debug with Browser Dev Tools
Open your browser’s Developer Tools (F12) and check these tabs:
- Network: Look at the request sent by
authorizeToken—confirm theAuthorizationheader is present and formatted correctly. Note the response status code (401 = invalid token, 403 = permission issue, 404 = wrong endpoint, 500 = server error). - Console: Look for JavaScript errors (e.g., missing imports, HTTP client issues) that might block the request from sending properly.
Final Tip
If you’re still stuck, test the endpoint directly with tools like Postman or curl first:
curl -H "Authorization: Bearer YOUR_TOKEN_HERE" http://localhost:8000/api/protected-view/
If this works, the problem is definitely in your Angular code. If it fails, revisit your DRF JWT configuration (even though you thought it was correct!).
内容的提问来源于stack exchange,提问作者user9487981




