6

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>
      );
   }
}
6
  • Its not react's concern. React is a UI library. You can set a cookie from the server side, after authenticating, when you serve the html file, for example. Commented Nov 16, 2016 at 8:10
  • Yes, I already do that. When the user is authenticated, I create a cookie but in my React component I need to check if the user is authenticated or not. I can also place user authentication information in my redux store but not sure how to read if the user is authenticated or not. Commented Nov 16, 2016 at 8:12
  • Then pass that info as a prop to your component. If you can set that information in the redux store, it should not be any different to other stuff in your redux store. Or am I not understanding you correctly? Commented Nov 16, 2016 at 8:13
  • Maybe I'm failing to express my question properly. I authenticate the user and create a cookie in my server side code i.e. ASP.NET. Now on the frontend, I want to see if the user is authenticated or not so that I can store that data in my redux store. I'm not sure how to check if there's an authentication cookie on the frontend. Commented Nov 16, 2016 at 8:17
  • developer.mozilla.org/en-US/docs/Web/API/Document/cookie Commented Nov 16, 2016 at 8:21

2 Answers 2

14

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

Sign up to request clarification or add additional context in comments.

1 Comment

are you setting the cookie in client-side which is not httpOnly? so vulnerable?
-1

the correct syntax is:

class MyComponent extends Component {

   constructor(props){
      super(props)
      this.state = {isAuthenticated: false};
   }

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

4 Comments

Thanks for the syntax correction but this didn't answer my question. If I'm reading your code correctly, you're looking for authentication info in the state. My question is "before" I put the authentication info into the state, how do I actually check if the user is authenticated?
Sorry, for authentification you can do an API (with FeathersJS for ex.), use Token authentification process, set this in cookie and in constructor you can check if a cookie with token is present. Then ask your API with this token.
I handle authentication in my server side code -- in ASP.NET. What I'm trying to understand is how to check for an authentication cookie in my frontend code.
Ok man, why dont explain your problem like that in your first post. So:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.