0

I'm using Laravel on the backend and react.js on the frontend , when I try to login it will redirect to the home ("/") but when I refresh the page I am redirected to login page again. I am using rote protection file which takes component as a parameter and all the components passed in protected route are only accessible by logged in users.. after logging in when I try to access protected pages I am redirected to login page.. can any body help?

app.js

function App() {
  return (
    <div className="App">
      {/* <AuthContextProvider> */}
      <BrowserRouter>
      <Switch>
      <Route path = "/login"><Login/></Route>
      <Route path= "/register"><Register/></Route>
      <Route path = "/add"><AuthProtection component = {AddProduct}/> </Route>
      <Route path = "/update"><AuthProtection component = {UpdateProduct}/> </Route>
      <Route path = "/search"><AuthProtection component = {Search}/> </Route>
      <Route path = "/"><AuthProtection component = {Home}/> </Route>
      </Switch>
      </BrowserRouter>
      {/* </AuthContextProvider> */}
    </div>
  );
}

export default App;

login.js

export const Login = () => {
    const history = useHistory()
    
    const [email, setemail] = React.useState("")
    const [password, setpass] = React.useState("")
    
   
   
    const loginuser = e =>{
        e.preventDefault();
        axios.defaults.withCredentials = true;
        let data = {email,password}
        axios.get('http://localhost:8000/sanctum/csrf-cookie').then(response => {
            console.log(response)
           axios.post('http://localhost:8000/login',data ,{
            headers: {
                'Content-Type': 'application/json',
                "Accept": "application/json",
                'X-XSRF-TOKEN': (() => {
                    const name = 'XSRF-TOKEN'
                    const cookies = '; ' + document.cookie
                    const parts = cookies.split('; ' + name + '=')
                    const value = parts.length == 2 ? parts.pop().split(';').shift() : null
    
                    console.log('>>> XSRF-TOKEN', value)
    
                    return value
                })(),
            },
          }).then(response => {
              
              localStorage.setItem("user-info" , JSON.stringify(response.config.headers["X-XSRF-TOKEN"]))
              Auth.authenticate();
           
               history.push("/");
           
          
         });
        });

    }
    return (
        <>
        <Header/>
        <div>
            
            <div className="wrapper fadeInDown">
                <div id="formContent">
                    {/* Tabs Titles */}
                    {/* Icon */}
                    <div className="fadeIn first">
                    
                    </div>
                    {/* Login Form */}
                    <form onSubmit = {loginuser}>
                        <input type="text" value={email} onChange={(e)=>setemail(e.target.value)} className="fadeIn second"  placeholder="login" />
                        <input type="password" value={password} onChange={(e)=>setpass(e.target.value)} className="fadeIn third"  placeholder="password" />
                        <button type="submit" className="fadeIn fourth btn btn-primary" >LOGIN</button>
                    </form>
                    {/* Remind Passowrd */}
                    <div id="formFooter">
                        <a className="underlineHover" href="#">Forgot Password?</a>
                    </div>
                </div>
            </div>

        </div>
        </>
    )
}

Auth.js

const Auth = {
    isAuthenticated: false,
    authenticate() {
      this.isAuthenticated = true;
    },
    signout() {
      this.isAuthenticated = false;
    },
    getAuth() {
        return this.isAuthenticated;
      }
  };

  export default Auth;

protectedRoutes.js

import React from 'react'
import { useHistory } from 'react-router'
import Auth from './Auth'
import { AuthContext } from './AuthContext';



export const AuthProtection = (props) => {
    console.log(props)
    const history = useHistory()
    let ProtectedTemplate = props.component
    console.log(Auth.getAuth())
    React.useEffect(()=>{
    if( !Auth.getAuth() ){
        history.push("/login")
    }
    
})

   
    return (
        <div>
            <ProtectedTemplate/>
        </div>
    )
}

Syeda
  • 23
  • 4
  • Welcome to the stack overflow, Sabrina. You have to add a mechanism to check the authenticated user to the app.js as well. That will update the isAutheticated flag in the Auth context as on refresh we will end up setting the `isAuthenticated` variable to false again. – Mehul Thakkar Sep 25 '21 at 15:41
  • @MehulThakkar how can I do that , I don't want to use local storage because it not secure what code should i add then? – Syeda Sep 25 '21 at 16:05
  • It depends on your authentication mechanism. If you're using local storage to store the token then you can get it from there. If you're using cookies then get it from there. What do you use for authentication? – Mehul Thakkar Sep 25 '21 at 16:12
  • I don't find any issue with using local/session storage to store the token. That is standard practice. Do you plan to manage the token and pass it in every subsequent request? or Do you have the cookie set from the server? – Mehul Thakkar Sep 25 '21 at 16:13
  • i have used laravel sanctum package for authentication it return xsrf token , if i save it in local storage and protect routes by local storage then attackers even if they are not logged in can add / edit any token in local storage and there will be no security – Syeda Sep 25 '21 at 16:24
  • To manage the session there are two ways you can store it on the client side. local/session storage or cookies. Read this for more information => https://stackoverflow.com/questions/44133536/is-it-safe-to-store-a-jwt-in-localstorage-with-reactjs Almost every site use one of these 2 mechanisms. The local storage is only vulnurable incase if anyone is able to inject JS on your site otherwise it is safe or use cookies. Your entire headache to maintain the token and send it in each request will be on backend rather than front-end and more secure. – Mehul Thakkar Sep 25 '21 at 16:29

0 Answers0