我有一个使用Angular 9和Django构建的客户端-服务器应用程序,并且遇到以下情况:
登录后,我在“响应头”中收到会话ID。即使浏览器设置了该Cookie,并且我也可以在“开发工具”>“应用程序”>“ Cookie”中看到它,但后续的请求中并未使用此Cookie。更确切地说,如果我在登录后发出请求,我的Django服务器将显示没有会话,并且用户未登录。
我在Internet上搜索了此问题,发现我必须在Angular项目的请求标头中设置{withCredentials: true}
。我让拦截器在每个请求标头中设置{withCredentials: true}
,但这对我不起作用。我以这种方式将拦截器放在AppModule的Provider中:providers: [[{provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true}]]
这是我的拦截器代码:
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(public auth: AuthService) {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
withCredentials: true
});
return next.handle(request);
}
}
这是我在Angular中的登录名
login() {
// stop here if form is invalid
if (!this.loginForm.valid) {
return;
}
this.authService.login(this.loginForm.value)
.subscribe((res) => {
this.router.navigate(['/workspace']);
}, (error) => {
console.log(error);
});
}
在AuthService中,我有:
@Injectable({
providedIn: 'root'
})
export class AuthService {
private headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded'});
private serverUrl = 'http://localhost:8000/api/auth/';
constructor(private httpClient: HttpClient) {
}
login(loginInputData) {
const body = new HttpParams()
.set('username', loginInputData.username)
.set('password', loginInputData.password);
return this.httpClient.post<any>(`${this.serverUrl}login/`, body.toString(), {headers: this.headers});
}
这是我在Django中的登录功能:
@csrf_exempt
def log_in(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return HttpResponse(status=200)
else:
return HttpResponseBadRequest("Invalid credentials")
return HttpResponseForbidden("Not allowed")
在我修改的Django settings.py文件中:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders', # for CORS policy
'uploadImg.apps.UploadimgConfig',
'users.apps.UsersConfig',
'frontEnd.apps.FrontendConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware', # for CORS policy
'django.middleware.common.BrokenLinkEmailsMiddleware', # for CORS policy
]
CORS_ORIGIN_ALLOW_ALL = True # for CORS policy
CORS_ALLOW_CREDENTIALS = True # for CORS policy
CORS_ORIGIN_REGEX_WHITELIST = [
'http://localhost:4200',
] # for CORS policy