首页 > 解决方案 > Keycloak json 配置文件,React 和 Router 4

问题描述

我将 React (16.3.2) 与 TypeScript (2.8.3)、Keycloak-js (3.4.3) 和 React Router 4 (4.2.2) 一起使用。这是Keycloak初始化:

const auth = Keycloak('./../keycloak.json');
const init = () => {
  return auth.init({ onLoad: 'login-required', checkLoginIframe: false });
};

keycloak.json 文件存储在公共文件夹中我在 ReactDOM.render 方法之前进行 Keycloak 初始化:

import { init } from './auth';
init()
  .success((authenticated: boolean) => {
    if (authenticated) {
      ReactDOM.render(
        <Provider store={store}>
          <App />
        </Provider>,
        document.getElementById('root') as HTMLElement
      );
    } else {
      console.log('not authenticated');
    }
  })
  .error(() => {
    console.log('failed to initialize');
  });

然后是 App(ThemeProvider 来自 styled-components):

const App: React.SFC<Props> = ({ theme }) => {
  return (
    <BrowserRouter>
      <ThemeProvider theme={theme}>
        <Switch>
          <Redirect from="/" exact={true} to="/books" />
          <Route path="/books" component={BooksList} />
          <Route component={Error404} />
        </Switch>
      </ThemeProvider>
    </BrowserRouter>
  );
};

然后是书单:

const BooksList: React.SFC<RouteComponentProps<void>> = ({ match }) => {
  return (
    <ColumnView>
      <Switch>
        <Route path={match.url} component={List} />
      </Switch>
      <Switch>
        <Route path={match.url} exact component={EmptyView} />
        <Route path={match.url + '/details/:id'} component={BookDetails} />
        <Route component={Error404} />
      </Switch>
    </ColumnView>
  );
};

当我在 URL localhost:3000上打开我的网站时,一切正常。Keycloak 呈现一个登录页面,我可以浏览整个网站。当我想通过在浏览器中输入不同的 URL 时出现问题,例如localhost:3000/books/details/11。突然,Keycloak 开始在一个非常不同的目录中搜索 keycloak.json 文件——不是localhost:3000/keycloak.json而是localhost:3000/books/details/keycloak.json

当我将配置文件的本地化编写为:

const auth = Keycloak('./../../../keycloak.json');

'../' 的数量取决于我的路由器的嵌套程度。这解决了一切。

标签: reactjstypescriptreact-routerkeycloak

解决方案


所以解决方案很简单——我必须删除初始化 URL 前面的单点,以使路径直接不是相对的:

const auth = Keycloak('/../keycloak.json');

推荐阅读