0
새로운 React 단일 페이지 응용 프로그램을 만들고 Auth0과 통합하려고합니다. 나는 React 예제를 가지고 일해 왔지만 제대로 작동하지 못하는 것 같아서 앱이로드 된 후에 즉시 로그인해야한다. 지금 내가 가진 문제는 인증이 처음 완료되기 전에 앱이 렌더링되기 때문에 로그인 페이지로 두 번 리디렉션된다는 것입니다.React/Redux/Router -로드시 Auth0 로그인
하는 index.js :
function initAuth(callback) {
const auth = store.getState().app.auth;
if(!auth.isAuthenticated()) {
auth.login();
}
callback();
}
//Authorize the app and then render it
initAuth(function() {
render(
<Provider store={store}>
<ConnectedRouter history={history}>
<div>
<App />
</div>
</ConnectedRouter>
</Provider>,
target
);
});
app.js :
const App = props => (
<div>
//... Other stuff
<Routes/>
//... More stuff
</div>
);
routes.js :
const Routes = props => (
<main>
<Switch>
//...Other Routes Are Here
<Route path="/callback" render={(props) => {
return <Callback data={props} {...props} />;
}}/>
<Redirect from='*' to='/'/> {/*Any unknown URL will go here*/}
</Switch>
</main>
);
callback.js :
다음은 코드의 중요한 덩어리입니다const auth = store.getState().app.auth;
const handleAuthentication = (nextState) => {
console.log('Evaluation: ', /access_token|id_token|error/.test(nextState.location.hash))
if (/access_token|id_token|error/.test(nextState.location.hash)) {
auth.handleAuthentication();
}
};
class Callback extends Component {
componentDidMount() {
handleAuthentication(this.props.data);
}
//... Render method etc
}
auth.js : login() {
this.auth0.authorize();
}
handleAuthentication() {
this.auth0.parseHash((err, authResult) => {
if (authResult && authResult.accessToken && authResult.idToken) {
this.setSession(authResult);
history.replace('/home');
} else if (err) {
history.replace('/home');
alert(`Error: ${err.error}. Check the console for further details.`);
}
});
}
isAuthenticated() {
// Check whether the current time is past the
// access token's expiry time
let expiresAt = JSON.parse(localStorage.getItem('expires_at'));
return new Date().getTime() < expiresAt;
}
는 지금 내 응용 프로그램은 기본적으로 작동합니다. 유일한 문제는 로그인 응답과 앱로드/체크 사이에 경쟁 조건이 있기 때문에 두 번 로그인해야한다는 것입니다. 왜 그런 일이 일어나고 있는지 완벽하게 이해할 수 있지만 어떻게 고칠 지 잘 모릅니다.
login() {
this.auth0.authorize();
}
handleAuthentication() {
this.auth0.parseHash((err, authResult) => {
if (authResult && authResult.accessToken && authResult.idToken) {
this.setSession(authResult);
history.replace('/home');
} else if (err) {
history.replace('/home');
alert(`Error: ${err.error}. Check the console for further details.`);
}
});
}
isAuthenticated() {
// Check whether the current time is past the
// access token's expiry time
let expiresAt = JSON.parse(localStorage.getItem('expires_at'));
return new Date().getTime() < expiresAt;
}