如何使用KeyCloak保护我的其他React页面/路由?

问题描述

我需要使用KeyCloak保护我的React页面。大多数初学者教程只包含一页样本(我知道React非常适合单页应用程序,但前端需要它),以使用KeyCloak进行身份验证。以下是我的代码:

(App.js)

// imports

export default function App () {
    return (
      <Router>
          <Switch>
            <Route exact path='/' component={Public}></Route>
            <Route exact path='/dashboard' component={Secured}></Route>
            <Route exact path='/settings' component={Settings}></Route>
          </Switch>
      </Router>
    );
}

(Public.js)

// imports

class Public extends Component {

  render() {
    return (
        <div className="container">
          <ul>
            <li><Link to="/">Public component</Link></li>
            <li><Link to="/dashboard">Login</Link></li>
          </ul>
        </div>
    );
  }
}

export default Public;

(Secured.js)

// imports

const styles = theme => ({
    appBarSpacer: theme.mixins.toolbar,content: {
        flexGrow: 1,height: '100vh',overflow: 'auto',}
});

class Secured extends Component {

    constructor(props) {
        super(props);
        this.state = { keycloak: null,authenticated: false };
        this.state = { page: 'home' }
    }

    componentDidMount() {
        const keycloak = Keycloak('/keycloak.json');
        keycloak.init({ onLoad: 'login-required' }).then(authenticated => {
            this.setState({ keycloak: keycloak,authenticated: authenticated });
        });
    }

    render() {
        const { classes } = this.props;
        if (this.state.keycloak) {
            if (this.state.authenticated) {
                return (
                    <div>
                        <Dashboard keycloak={this.state.keycloak} />
                    </div>
                );
            } else return (<div>Unable to authenticate!</div>)
        }
        return (
            <Grid container spacing={0} direction="column"
                alignItems="center" justify="center" style={{ minHeight: '75vh' }}>
                <CircularProgress />
            </Grid>
        );
    }
}

Secured.propTypes = {
    classes: PropTypes.object.isRequired,};

export default withStyles(styles)(Secured);

如您所见,为了使用KeyCloak保护Dashboard,我将其放在Secured组件中。由于PublicSettings不在Secured内部,因此它们不需要身份验证。 Public很好,但是,我也希望保护Settings,即,用户应该先通过KeyCloak进行身份验证,然后才能看到页面。

我曾尝试复制Secured并将Dashboard替换为Settings,但我认为这是多余的。如果我有一打要保护的页面怎么办?如何有效地做到这一点?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...