如何使用第三方CAS身份验证从独立的前端与django后端(相同的域,不同的端口)对用户进行身份验证? [英] How to authenticate user from standalone react frontend with django backend (same domain, different ports), using a third-party CAS authentication?

查看:219
本文介绍了如何使用第三方CAS身份验证从独立的前端与django后端(相同的域,不同的端口)对用户进行身份验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Django REST框架设置django后端,以提供API,并通过第三方CAS服务器实现身份验证。目前,我的后端身份验证已成功实现(使用 django-cas-ng 包),这意味着我可以为不同的用户组实现不同的权限。 django后端默认通过 localhost:8000 服务。

I'm setting up a django backend with Django REST framework for providing APIs, with authentication implemented through a third-party CAS server. Currently my backend authentication has been successfully implemented (using django-cas-ng package), which means I can implement different permissions for different groups of user. The django backend serves through localhost:8000 by default.

添加独立的反应前端( localhost:3000 默认情况下)似乎会使身份验证系统复杂化。从3000端口发送到8000端口的请求(由axios实现)无法通过身份验证。

Adding a standalone react frontend (localhost:3000 by default) seems complicating the authentication system. Requests (implemented by axios) sending from 3000 port to 8000 port are unable to authenticate.

我尝试了 npm run build 生成静态文件并将其与django集成。在同一个8000端口中,所有身份验证和权限都可以正常工作。

I've tried npm run build to build the static files and integrate them with django. Within the same 8000 port all the authentication and permissions work fine.

有人可以建议如何通过不同的端口实现身份验证吗?

Could anyone suggest how to implement authentication through different ports?

推荐答案

原来是因为请求从 localhost:3000 发送到 localhost:8000 不包含cookie中的 sessionid ,因此用户将无法通过身份验证。

Turns out it's because request sent from localhost:3000 to localhost:8000 doesn't contain the sessionid from cookies, so the user would not able to be authenticated.

对于axios,设置 withCredential 选项将包括HTTPOnly sessionid

For axios, setting the withCredential option will include HTTPOnly sessionid:

axios("example.com", {
  method: "post",
  data: someJsonData,
  withCredentials: true
})

对于Django,响应将需要包括:

For django side, the response will need to include:

Access-Control-Allow-Credentials: true, 
Access-Control-Allow-Methods GET, POST, PUT, PATCH, DELETE, OPTIONS,
Access-Control-Allow-Headers Content-Type
Access-Control-Allow-Origin: http://localhost:3000 
// CORS_ALLOW_ORIGIN = ['*'] or CORS_ORIGIN_ALLOW_ALL = True will not work

再次感谢@ xyres提供了CORS信息,在解决此问题期间确实有很大帮助!

Thanks again to @xyres for providing CORS info and it really help a lot during solving this issue!

这篇关于如何使用第三方CAS身份验证从独立的前端与django后端(相同的域,不同的端口)对用户进行身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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