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

问题描述 投票:1回答:1

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

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

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

干杯!

reactjs react-admin
1个回答
3
投票

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

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

因此,要使fetch发送cookie,您必须为应用程序所做的每个credentials: 'include'调用添加fetch选项。

(如果您的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
© www.soinside.com 2019 - 2024. All rights reserved.