Angular登录成功后访问Django后端出现401 Unauthorized错误求助
Hey there, let's figure out why you're hitting that 401 error right after logging in successfully. The core issue here is that even though your login request works, the subsequent request to http://127.0.0.1:8000/scrumboard/Recruteurs/ isn't carrying the necessary authentication credentials that Django needs to recognize your logged-in user.
Let's break down the fixes step by step:
1. First, Make Sure You're Storing Authentication Credentials After Login
Your myService.login() method is incomplete, so I bet you're not saving the auth token or session data after a successful login. Here's how to fix that depending on your Django auth setup:
If Using JWT Token Authentication
Update your service to save the token when login succeeds:
import { HttpClient, tap } from '@angular/common/http'; public login(user: any){ return this.http.post('http://your-django-login-url/', user).pipe( tap((response: any) => { // Store the token in localStorage or a service variable localStorage.setItem('authToken', response.access_token); }) ); }
If Using Django's Default Session Authentication
Django uses session cookies for auth, so you need to ensure your Angular HttpClient sends cookies with requests. Add withCredentials: true to your login request:
public login(user: any){ return this.http.post('http://your-django-login-url/', user, { withCredentials: true }); }
2. Ensure All Subsequent Requests Carry Auth Credentials
Once you have the credentials stored, you need to attach them to every request your Angular app makes to Django.
For JWT: Use an HTTP Interceptor
Create an interceptor to automatically add the Authorization header to all requests:
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable() export class AuthInterceptor implements HttpInterceptor { intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const authToken = localStorage.getItem('authToken'); if (authToken) { // Clone the request and add the auth header const modifiedRequest = request.clone({ setHeaders: { Authorization: `Bearer ${authToken}` } }); return next.handle(modifiedRequest); } return next.handle(request); } }
Then register this interceptor in your app.module.ts:
import { HTTP_INTERCEPTORS } from '@angular/common/http'; import { AuthInterceptor } from './auth.interceptor'; @NgModule({ // ... other imports and declarations providers: [ { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true } ] }) export class AppModule { }
For Session Auth: Enable withCredentials Globally
If you're using Django's session cookies, configure your HttpClient to send cookies with every request by default. Add this to your app's providers:
import { HttpClient } from '@angular/common/http'; @Injectable() export class HttpClientSetup { constructor(private http: HttpClient) { this.http.defaults.withCredentials = true; } } // In app.module.ts providers: [HttpClientSetup]
3. Check Django Backend Configurations
- CSRF Protection: If your Angular app is on a different port/domain than Django, make sure you've configured Django to allow cross-origin requests (use
django-cors-headerspackage) and that Angular is sending the CSRF token with requests. - Login Required Decorator: Verify that the
/scrumboard/Recruteurs/view uses@login_required(or the appropriate auth decorator) and that Django's session middleware is enabled.
4. Debugging Tips
- Open your browser's DevTools > Network tab:
- Check the login request's response: Look for a
Set-Cookieheader (session) or a token in the response body. - Check the
/scrumboard/Recruteurs/request's headers: Confirm that either theAuthorizationheader (JWT) orCookieheader (session) is present.
- Check the login request's response: Look for a
内容的提问来源于stack exchange,提问作者M1rwen

