Authentification et locale storage
Bonjour,
J'ai mi en place l'authentification dans mon application sauf que quand je me connecte, je n'arrive pas à me rediriger vers la page Dashboard. J'ai mi mon token en session et aussi l'attribut isAuthenticated.
Voici ma méthode de login :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
handleSubmit(event) {
event.preventDefault();
const authentification= this.state.authentification;
const errors = this.validate(authentification);
if(Object.keys(errors).length === 0){
const params=new URLSearchParams();
params.append('username',authentification.email);
params.append('password',authentification.password);
axios.post('/login',params)
.then(response=> {
console.log(response);
localStorage.setItem(ACCESS_TOKEN, response.headers.authorization);
console.log("ACCESS_TOKEN : " +localStorage.getItem(ACCESS_TOKEN));
localStorage.setItem(IS_AUTHENTICATED, true);
this.setState({isAuthenticated:true});
})
.catch(error =>{
const statusCode = error.response.status;
if(statusCode === 404)
errors.authentification = true;
else
errors.general = true;
this.setState({errors});
});
}else
this.setState({errors});
} |
Mon test pour savoir quelle page afficher :
Code:
1 2 3 4 5 6 7 8
| render() {
console.log("RENDER - isAuthenticated : "+this.state.isAuthenticated)
if(this.state.isAuthenticated){
return <Redirect to={"/dashboard"}/>;
}else{
return LoginTemplate.call(this);
}
} |
La génération des route dans mon dashboard :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
const switchRoutes = (
<Switch>
{dashboardRoutes.map((prop, key) => {
if (prop.redirect){
return <Redirect from={prop.path} to={prop.to} key={key} />;
}else if(prop.private){
console.log("auth : " + localStorage.getItem(IS_AUTHENTICATED));
return <PrivateRoute authenticated={localStorage.getItem(IS_AUTHENTICATED)} path={prop.path} component={prop.component} key={key} />;
}else{
return <Route path={prop.path} component={prop.component} key={key} />;
}
})}
</Switch>
); |
Voici les logs au premier lancement de mon application :
Citation:
auth : null
RENDER - isAuthenticated : false
1 fois que je clique sur le bouton se connecter :
Citation:
RENDER - isAuthenticated : false
ACCESS_TOKEN : Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJkeWxhbi5uYXRpZXJAYmx1ZXNvZnQtZ3JvdXAuY29tIiwiZXhwIjoxNTQzMzEzMDc0fQ.xBCPmlj2iafznZmukU2mx9V8HYKdHToN1zOpGz-p5GFSal9l377z7G4z6XKiaSWwyd3ThpGN1pDrx_VuPM8hiQ
RENDER - isAuthenticated : true
RENDER - isAuthenticated : false
login:1 Uncaught (in promise) {isCanceled: true}
login:1 Uncaught (in promise) {isCanceled: true}