Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking authentication in React

How do I check if user is authenticated in my React component?

class MyComponent extends Component {

   var isAuthenticated = false; // How do I check if the user is authenticated?
   var message = "Hello stranger!";

   if(isAuthenticated) {
      message = "Hello friend!";
   }

   render() {
      return(
         <div>
             {message}
         </div>
      );
   }
}
like image 951
Sam Avatar asked Nov 16 '16 07:11

Sam


People also ask

What is JWT authentication in react?

JWT, or JSON Web Token, is a web protocol used to share security information between client and a server. In a standard web application, private API requests contain JWT that is generated as a result of the verification of the user information, thus allowing these users to reach protected data and access services.

How do you check if JWT token is expired react?

There are two ways to check if Token is expired or not. I will show you the implementations of both ways. – For 1, we check the token expiration every time the Route changes and call App component logout method. – For 2, we dispatch logout event to App component when response status tells us the token is expired.


1 Answers

you need to have a way to surface your auth to the frontend. lets say you have an api called user/validate the purpose of that api is to return an authenticated flag and whatever else you want like the server auth token or something. you need a method to request that information. I'm assuming you have a way to make requests to api methods already setup.

make a function to request this authentication.

export const checkAuth = () => {
    const url = `${api_route}/user/validate`;
    // this is just pseudo code to give you an idea of how to do it
    someRequestMethod(url, (resp) => {
        if (resp.status === 200 && resp.data.isAuthenticated === true) {
            setCookie(STORAGE_KEY, resp.data.token);
        }
    });
}

your base app component would look something like this

export default class App extends Component {
    constructor() {
        super();
        checkAuth();
    }
    ....
}

now your component could do something like this.

class MyComponent extends Component {
   constructor(){
      super()
      this.isAuthenticated = getCookie(STORAGE_KEY);
   }

   render() {
      return(
         <div>
             Hello {this.isAuthenticated ? 'friend' : 'stranger'} !
         </div>
      );
   }
}

your getCookie and setCookie methods would be something like this

export const setCookie = (name, value, days, path = '/') => {
    let expires = '';
    if (days) {
        let date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = `; expires=${date.toUTCString()};`;
    } 
    document.cookie = `${name}=${value}${expires}; path=${path}`;
};

export const getCookie = (cookieName) => {
    if (document.cookie.length > 0) {
        let cookieStart = document.cookie.indexOf(cookieName + '=');
        if (cookieStart !== -1) {
            cookieStart = cookieStart + cookieName.length + 1;
            let cookieEnd = document.cookie.indexOf(';', cookieStart);
            if (cookieEnd === -1) {
                cookieEnd = document.cookie.length;
            }
            return window.unescape(document.cookie.substring(cookieStart, cookieEnd));
        }
    }
    return '';
};

Now... I would strongly recommend you look at adding something like Redux to handle passing data around via props. This way you can have one storage method that does the getCookie and sets it up right away and everything else will have isAuthenticated as a flag in the props

like image 189
John Ruddell Avatar answered Sep 22 '22 14:09

John Ruddell