Azure 应用服务身份验证 - 尝试获取 /.auth/me 时为 302

Azure App Service Authentication - 302 when trying to GET /.auth/me

我有一个使用应用服务身份验证托管在 Azure 应用服务上的 reactjs Web 应用。

我的应用程序进行了正确的身份验证,我正在尝试从应用程序内部获取 /.auth/me,以便我可以读取访问令牌以用于将来的某些 API 请求,但我收到了302响应。即使第一个请求(加载应用程序)已经通过身份验证,响应也会重定向到 login.microsoft.com。

const headers = {
    'Accept': 'application/json, text/plain, */*',
    'Content-Type': 'application/json',
    'credentials': 'include'
};

return (dispatch) => {
    const requestOptions = {
        method: 'GET',
        headers: headers,
    };

    return fetch("/.auth/me", requestOptions) 
        .then(parseResponseAndHandleErrors)
        .catch(error => {
            console.error(error)
        });
}

我想我一定是在 GET 中遗漏了一个 cookie 或 header,但文档没有提供太多信息:https://docs.microsoft.com/en-us/azure/app-service/app-service-authentication-how-to#retrieve-tokens-in-app-code

From your client code (such as a mobile app or in-browser JavaScript), send an HTTP GET request to /.auth/me. The returned JSON has the provider-specific tokens.

我试过设置 'credentials': 'same-origin' 但没有任何区别。

在查看了 fetch() API 的 'credentials' 选项的更多细节后,我设法解决了这个问题。

'credentials' : 'same-origin' 不应包含在 headers 中,而是作为单独的请求选项:

const headers = {
    'Accept': 'application/json, text/plain, */*',
    'Content-Type': 'application/json'
};

return (dispatch) => {
    const requestOptions = {
        method: 'GET',
        headers: headers,
        'credentials': 'same-origin'  //credentials go here!!!
    };

    return fetch("/.auth/me", requestOptions) 
        ......
}