【问题标题】:Cookie-based authentication via REST API in react-admin在 react-admin 中通过 REST API 进行基于 Cookie 的身份验证
【发布时间】:2019-07-10 02:53:43
【问题描述】:

我是 react-admin 的新手。我已经阅读了 stackoverflow 中的所有问题,也用谷歌搜索了我的问题,但没有找到任何有用的解决方案。

我正在设置 React-admin 来替换我的一个项目的现有管理页面。我通过 REST API 使用基于 cookie 的身份验证。

是否有可能(如果是的话如何?)在 react-admin 中使用它?有人可以引导我走向正确的方向吗?

干杯!

【问题讨论】:

    标签: reactjs react-admin


    【解决方案1】:

    当然可以。你只需要让fetch 使用cookies。

    react-admin 使用 fetch 将 http 请求发送到您的后端。并且 fetch 默认不发送 cookie。

    所以要让fetch 发送cookie,您必须为应用发出的每个fetch 调用添加credentials: 'include' 选项。

    (如果您的 admin 和 api 不在同一个域中,则必须在后端启用 CORS。)

    请参阅react-admin 的文档,了解如何在dataProvider 上自定义请求:https://github.com/marmelab/react-admin/blob/master/docs/Authentication.md#sending-credentials-to-the-api

    import { fetchUtils, Admin, Resource } from 'react-admin';
    import simpleRestProvider from 'ra-data-simple-rest';
    
    const httpClient = (url, options = {}) => {
        if (!options.headers) {
            options.headers = new Headers({ Accept: 'application/json' });
        }
        const token = localStorage.getItem('token');
        options.headers.set('Authorization', `Bearer ${token}`);
        return fetchUtils.fetchJson(url, options);
    }
    const dataProvider = simpleRestProvider('http://localhost:3000', httpClient);
    
    const App = () => (
        <Admin dataProvider={dataProvider} authProvider={authProvider}>
            ...
        </Admin>
    );
    

    您必须自定义它以添加 options.credentials = 'include',如下所示:

    const httpClient = (url, options = {}) => {
        if (!options.headers) {
            options.headers = new Headers({
              Accept: 'application/json'
            });
        }
        options.credentials = 'include';
        return fetchUtils.fetchJson(url, options);
    }
    

    您必须为 authProvider 做同样的事情。

    类似

    // in src/authProvider.js
    export default (type, params) => {
        // called when the user attempts to log in
        if (type === AUTH_LOGIN) {
            const { username, password } = params;
            const request = new Request(`${loginUri}`, {
                method: 'POST',
                body: JSON.stringify({ username: username, password }),
                credentials: 'include',
                headers: new Headers({ 'Content-Type': 'application/json' }),
            });
            return fetch(request)
            .then(response => {
                if (response.status < 200 || response.status >= 300) throw new Error(response.statusText);
    
                localStorage.setItem('authenticated', true);
            });
        }
        // called when the user clicks on the logout button
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-16
      • 1970-01-01
      • 2015-04-01
      • 2016-09-29
      • 1970-01-01
      • 2017-02-04
      相关资源
      最近更新 更多