You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

实现Django REST Framework JWT认证(Django REST + Angular 5)

Troubleshooting Angular 5 + DRF JWT Authorization Issue

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
  • 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 HttpClientModule in your Angular app module (Angular 5 uses HttpClient instead of the legacy Http service).

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.py has 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-headers and add it to your installed apps in settings.py
  • Set CORS_ALLOWED_ORIGINS to include your Angular app’s URL (e.g., http://localhost:4200) or use CORS_ALLOW_ALL_ORIGINS = True for 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 the Authorization header 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

火山引擎 最新活动