如何使用获取客户端进行数据查询登出401?

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

在Web应用程序中,我在另一个React应用程序中重复使用dataProvider网站上指定的react-adminhttps://marmelab.com/react-admin/DataProviders.html#data-providers

如果有任何请求返回401响应,他们可以断开连接并重定向到登录。

在我的另一个不是React admin的其他React应用中,当我的请求失败(会话超时)时,我没有此重定向。

这是我的dataProvider的外观:

const dataProvider = {
    getList:    (resource, params) => Promise,
    getOne:     (resource, params) => Promise,
    getMany:    (resource, params) => Promise,
    getManyReference: (resource, params) => Promise,
    create:     (resource, params) => Promise,
    update:     (resource, params) => Promise,
    updateMany: (resource, params) => Promise,
    delete:     (resource, params) => Promise,
    deleteMany: (resource, params) => Promise,
}

我已经检查了代码,并期望看到每种方法的包装,这将添加catch并在必要时触发重定向以登录。

相反,我不是这样,我想知道为什么以及如何在我的应用程序中正确解决此问题。

javascript security xmlhttprequest fetch
1个回答
0
投票

没有其他任何代码都不能说很多。需要更多东西,以便我们复制。 Promise是否直接引用您正在使用的Promise库?具体答案完全取决于体系结构和您拥有的其他支持库。

这些是我们使用reduxreact-router-dom采取的步骤>

  1. 身份验证/数据请求失败
  2. 销毁本地存储凭据。
  3. 触发副作用/应用程序状态更改
  4. 使用应用程序状态更新redux存储。
  5. 高阶组件PrivateRoute包装所有需要私有的路由。它检查isLoggedIn状态并返回页面组件或将用户重定向到/login
  6. 例如

// handle promise error
    private handleError = (errorMessage: Error) => {
        const message = JSON.parse(errorMessage.message);
        if (message.status === 401) {

            this.authentication.logout(); // triggers logout actions and destroy credentials
        }
        throw errorMessage;
    }

    private destroyUserCredentials() {
        this.tokenResponse = null;
        this.tokenClaims = null;
        this.tokenHasExpired = true;
        this.accessToken = null;
        this.localStorage.removeItem(this.storageKey);
    }

 // dispatch action to change redux store state
 appStore.dispatch(LogOutAction(token));
// Private route HOC
export const PrivateRouteComponent = ({ component: Component, state: state, ...rest }) => {
    const renderComponent = (props) => {
        if (state.login.isLoggedIn) {
            return <Component {...props} />;
        } else {
            return <Redirect to='/login' />;
        }
    };

    return (
      <Route
        {...rest}
        render={renderComponent}
      />
    );
  };

// REF: pluralsight connect container
function mapStateToProps(state, ownProps) {
    return {
        state: {
            login: state.authenticate
        }
    };
}

export const PrivateRoute = connect(mapStateToProps)(PrivateRouteComponent);

// Route setup
 <Provider store={appStore}>
            <BrowserRouter>
                <Switch>
                    <Route path='/login' component={LoginPage} />
                    <PrivateRoute path='/analytics' component={HomePage} />
                    <PrivateRoute path='/account' component={AccountPage} />
                </Switch>
            </BrowserRouter>
        </Provider>

© www.soinside.com 2019 - 2024. All rights reserved.