Search code examples
reactjslaravelreact-routerlaravel-passport

Can I and how to protect my react-router routes with laravel passport


I can't find docs for react and laravel authentication, but I saw in forums that people are using passport and so I used it too. Currently I have access_token, I can guard laravel routes with passport's middleware, but how do I protect react-router route?

currently I am thinking of using Cookies from 'universal-cookie' to pass token as cookie to admin dashboard component and from there to run axios request in order to check whether token is valid. If access would be granted I could display the dashboard, other way to display "access denied" element. But this isn't route protection, I would like to know how to do it properly

 var bodyFormData = new FormData;
        bodyFormData.append('name', this.state.name);
        bodyFormData.append('password', this.state.password);
        axios({
            method: 'post',
            url: '/api/login',
            data: bodyFormData,
            config: { headers: {'Content-Type': 'multipart/form-data' }}
        })
            .then(function (response) {
                var cookies = new Cookies();
                cookies.set('access_token', response.data.access_token, { path: '/' });
            })
            .catch(function (response) {
                alert(response)
            });


Solution

  • Generally, the way this is done is by wrapping the standard Route component with a a custom one, and handing your auth logic there.

    See this post for a good example: https://tylermcginnis.com/react-router-protected-routes-authentication/