问题描述
我在一个域中托管了用Flask编写的rest API,在Azure应用服务中将我的react应用托管在另一个域中。我可以使用用户名和密码成功登录系统。但是,当我尝试触碰端点时,我得到None
的username属性(本地一切正常,没有任何问题)。
def login_required( f ):
@wraps(f)
def wrap( *args,**kwargs ):
project_owner = session.get( 'username' )
if project_owner is None:
logging.error( ERROR_MSG.LOGIN_ERROR_MSG )
return response.cannot_process_redirect( ERROR_MSG.LOGIN_ERROR_MSG,'/' )
else:
return f( *args,**kwargs )
return wrap
我认为我已经应用了正确的CORS政策,但无法使其正常工作。应用的CORS配置如下。
app.config['CORS_HEADERS'] = 'Content-Type'
app.config['SESSION_COOKIE_HTTPONLY'] = False
CORS( app,supports_credentials = True,resources = {r"/api/*": {"origins": "http://domainA.net"}} )
端点的获取请求如下所示。
export function getUsers() {
const url = 'users/'
const requestOptions = {
method: 'GET',credentials: 'include'
};
return ( dispatch ) => {
return fetchReq( requestOptions,url ).then( ([response,json]) => {
// Do something
} )
}
}
还在Azure应用服务中,将domainA
添加到domainB
的允许的来源列表中。
如果我使用Postman,则可以使用端点而没有任何问题。我注意到的一件事是我的请求和响应会话值字符串不同。下面是请求-响应标头的屏幕截图。
解决方法
玩了很多天之后,我发现我需要在提取请求中添加credentials: 'include'
,以便浏览器将发送带有跨域请求(https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials)的cookie。因此,我在Flask应用中的最终CORS配置如下。
app.config['SESSION_COOKIE_SECURE'] = True
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'None'
CORS( app,resources = {r"/api/*": {"origins": ["http://localhost:3000","<Domains that are allowed to do cross origin requests>"],