未在角度客户端上设置Cookie [英] Cookie not being set on angular client

查看:75
本文介绍了未在角度客户端上设置Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在django python中有一个后端应用程序,并且正在http://localhost:8000上提供该服务.

I have a backend app in django python and it is being served on http://localhost:8000.

我在http://localhost:4200上提供了一个有角度的前端.

I have a angular frontend which is being served on http://localhost:4200.

我在Django上禁用了CORS. 在点击http://localhost:8000/auth/login/上的登录api时,我得到了有效的响应 以及Set-Cookie标头.

I have disabled CORS on django. On hitting the login api on http://localhost:8000/auth/login/, I am getting a valid response along with the Set-Cookie header.

这是我打印饼干的角度代码:

Here is my angular code to print the cookies:

  this.http.post<any>('http://localhost:8000/auth/login/', this.LoginForm, { observe: 'response' }).subscribe(response => {
   console.log("response is ", response);
   var cookies = this.cookieService.getAll();//('cookies');
   console.log("cookies is :", cookies);

它将在控制台上打印一个空对象. 我该如何工作?我想使用Cookie进行身份验证.

It prints an empty object on console. How do I make this work? I want to use cookies for authentication.

推荐答案

您正在尝试设置跨域cookie,该cookie无法立即生效.要执行此操作,需要遵循一些步骤.

You are trying to set cross domain cookies, which will not work straight away. There are a few steps to follow to be able to do that.

  1. 从angular发出身份验证请求时设置withCredentials: true

this.http.post<any>('http://localhost:8000/auth/login/', this.LoginForm, { observe: 'response', withCredentials: true })

配置服务器以返回以下CORS标头:Access-Control-Allow-Credentials: trueAccess-Control-Allow-Origin: http://localhost:4200

Configure your server to return the following CORS headers: Access-Control-Allow-Credentials: true and Access-Control-Allow-Origin: http://localhost:4200

注意

您要设置的Cookie之一是HttpOnly.因此,您无法从Javascript访问它(请参见文档).

One of the cookies that you are setting is HttpOnly. As such, you cannot access it from Javascript (see documentation).

您可能始终不需要使用JS访问cookie.如果您只想在下一个API请求中发送cookie,只需将withCredentials: true传递给HttpClient其他api调用

You may not need to access the cookies with JS anyway. If you just want to send the cookies in the next API requests, just pass withCredentials: true to HttpClient other api calls

this.http.get('http://localhost:8000/path/to/get/resource',
  { withCredentials: true }).subscribe(response => {

这篇关于未在角度客户端上设置Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆