我有 2 个 AppService,一个用于我的 django 后端,另一个用于我的 Angular 前端。每个appService都有它的域。在登录端点上,后端必须在前端上下文和域中生成并设置带有 jwt 的 cookie 以启用导航。 据我了解,由于有 2 个应用程序服务具有 2 个不同的域,因此在后端创建 cookie 对应于与前端不同的域,因此这会被浏览器拒绝,从而拒绝 cookie。 (甚至在后端配置httpOnly、Secure、Domain和path属性)。 是否可以配置两个appServices共享相同的域,以便cookie保留在前端的上下文中?
我尝试将后端setCookie中的domain属性设置为前端域名,但浏览器仍然拒绝它。
是否可以配置两个appServices共享同一个域
是的,我们可以通过添加自定义域来配置它(例如,
backend.example.com
或frontend.example.com
)。
我们需要通过将 Azure 提供的 DNS 记录添加到域名注册商的 DNS 设置来验证域的所有权。
对其他应用程序服务 Angular 前端重复相同的过程,添加相同的自定义域。
姜戈:
from django.http import JsonResponse
def login(request):
# Perform login logic
# Assuming jwt_token is the JWT token you want to set
response = JsonResponse({'message': 'Login Successful'})
response.set_cookie('jwt_token', 'your_jwt_token', domain='frontend.example.com')
return response
角度:
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private apiUrl = 'https://backend.example.com';
constructor(private http: HttpClient) { }
login(credentials: any): Observable<any> {
return this.http.post(`${this.apiUrl}/login/`, credentials, { withCredentials: true });
}
}
在您的 HTTP 请求中包含
withCredentials: true
选项。
为 Django 后端配置 CORS,在设置 Django 后端应用服务中,您可以找到 CORS 设置部分。将域
https://frontend.example.com
添加到允许的来源列表
根据上述配置
Headers-set_cookies
两个应用程序,cookie 仅保留在一个域的上下文中。