IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

React Discussion :

Authentification et locale storage


Sujet :

React

  1. #1
    Membre éprouvé
    Profil pro
    Inscrit en
    Juin 2013
    Messages
    1 225
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2013
    Messages : 1 225
    Par défaut 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 : Sélectionner tout - Visualiser dans une fenêtre à part
    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 : Sélectionner tout - Visualiser dans une fenêtre à part
    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 : Sélectionner tout - Visualiser dans une fenêtre à part
    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 :
    auth : null
    RENDER - isAuthenticated : false
    1 fois que je clique sur le bouton se connecter :
    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}

  2. #2
    Membre éprouvé
    Profil pro
    Inscrit en
    Juin 2013
    Messages
    1 225
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2013
    Messages : 1 225
    Par défaut
    J'ai résolu mon problème comme ceci :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    34
     
      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);
            console.log("IS_AUTHENTICATED : " +localStorage.getItem(IS_AUTHENTICATED));
            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});
      }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
      render() {    
        let isAuthenticated = JSON.parse(localStorage.getItem(IS_AUTHENTICATED));
        console.log("RENDER - isAuthenticated : "+isAuthenticated)
     
        if(isAuthenticated === null)
        isAuthenticated = this.state.isAuthenticated;
     
        console.log("RENDER - isAuthenticated : "+isAuthenticated)
        if(isAuthenticated === true){
          console.log("redirect dashboard");
          return <Redirect to={"/dashboard"}/>;
        }else{
          console.log("redirect login");
     
          return LoginTemplate.call(this);
        }
      }
    }
    Et dans mon dashboard, j'ai transformé ma constante qui charge les route en fonction.

    Par contre il y a quelque chose que je comprend pas : quand je lance mon application, j'ai l'impression que ma page de login est appelé 3 fois au début :
    RENDER - isAuthenticated : null
    RENDER - isAuthenticated : false
    redirect login
    RENDER - isAuthenticated : null
    RENDER - isAuthenticated : false
    redirect login
    RENDER - isAuthenticated : null
    RENDER - isAuthenticated : false
    redirect login
    Ensuite, quand je clique sur le bouton se connecter, j'ai l'impression qu'il y a 2 appels :
    RENDER - isAuthenticated : null
    RENDER - isAuthenticated : false
    redirect login

    ACCESS_TOKEN : Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJkeWxhbi5uYXRpZXJAYmx1ZXNvZnQtZ3JvdXAuY29tIiwiZXhwIjoxNTQzMzE3ODE4fQ.wE6tBz30csnBwgPJQk6tx1Ku58YegIuV6-eqYS20XraX6DwgXez5vm3nbzf2EJYBo7mZauEadce1vVQPAA5g
    IS_AUTHENTICATED : true
    RENDER - isAuthenticated : true
    RENDER - isAuthenticated : true
    redirect dashboard

Discussions similaires

  1. [API HTML5] Stocker une image base64 en local storage
    Par Oriane85 dans le forum Général JavaScript
    Réponses: 2
    Dernier message: 02/11/2015, 17h52
  2. [Débutant] VS2013 - Authentification en local ou Windows
    Par Ti-Pou dans le forum Développement Web avec .NET
    Réponses: 0
    Dernier message: 14/09/2015, 20h36
  3. Local storage data image
    Par var83 dans le forum Général JavaScript
    Réponses: 16
    Dernier message: 25/05/2015, 13h51
  4. authentification compte local client sur windows serveur 2012
    Par p7500 dans le forum Windows Serveur
    Réponses: 2
    Dernier message: 10/06/2014, 12h24
  5. challenge Azure Epreuve 2 Local storage
    Par lerab51 dans le forum Microsoft Azure
    Réponses: 2
    Dernier message: 06/12/2010, 20h32

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo