我需要使用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
组件中。由于Public
和Settings
不在Secured
内部,因此它们不需要身份验证。 Public
很好,但是,我也希望保护Settings
,即,用户应该先通过KeyCloak进行身份验证,然后才能看到页面。
我曾尝试复制Secured
并将Dashboard
替换为Settings
,但我认为这是多余的。如果我有一打要保护的页面怎么办?如何有效地做到这一点?