在react-admin中通过REST API进行基于cookie的身份验证

2024-05-19

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

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

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

Cheers!


这当然是可能的。你只需要做fetch https://developer.mozilla.org/fr/docs/Web/API/Fetch_API使用cookie。

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

所以要使fetch发送cookies,你必须添加credentials: 'include'每个选项fetch调用该应用程序。

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

See react-admin有关如何自定义请求的文档dataProvider here: https://github.com/marmelab/react-admin/blob/master/docs/Authentication.md#sending-credentials-to-the-api 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在react-admin中通过REST API进行基于cookie的身份验证 的相关文章

随机推荐