tymondesigns / jwt-auth

🔐 JSON Web Token Authentication for Laravel & Lumen
https://jwt-auth.com
MIT License
11.32k stars 1.54k forks source link

refresh token stored in localstorage #1351

Open packytagliaferro opened 7 years ago

packytagliaferro commented 7 years ago

So I started using Tymon JWT package for Laravel for my SPA. Its all going good ( adding user, signing in, getting Auth user) but when I make an API request it only works for an hour. I understand that the token I stored on login expires so when I make a request to the API after 60 minutes it doesn't work. My question is how do I refresh the token and restore it in my local storage? On a new request? Every 59 minutes? I am just confused on the process. Right now my app just checks if there is a token in local storage to bypass login as well, should this check against the refresh token as well??? I have yet to find a clear example of how to do this with Laravel and Vue (seems like with this being a laravel package there would be somewhere)

AuthController.php

    public function authenticate(Request $request)
    {
        // grab credentials from the request
        $credentials = $request->only('email', 'password');

        try {
            // attempt to verify the credentials and create a token for the user
            if (! $token = JWTAuth::attempt($credentials)) {
                return response()->json(['error' => 'Sorry, we cant find you.']);
            }
        } catch (JWTException $e) {
            // something went wrong whilst attempting to encode the token
            return response()->json(['error' => 'could_not_create_token'], 500);
        }

        // all good so return the token
        $user = JWTAuth::toUser($token);

        //Fire off the login event
        event( new LoginSuccessful($user) );

        return response()->json( compact('token', 'user') );
    }

Login.vue


            axios.post('/api/authenticate',{
                email: this.email,
                password: this.password
            })
            .then(response => {

                if(response.data.error){

                    //Show the error
                    this.error = response.data.error
                    this.loading = false;

                } else {

                    this.loading = false;

                    //Store the items in storage
                    localStorage.setItem('jwt_token', response.data.token);
                    localStorage.setItem('user', JSON.stringify(response.data.user));

                    //Mutate the state
                    this.$store.commit('login');

                    //Now go to the dashboard
                    this.$router.push('dashboard');
                }

            })
            .catch(error => {

            });

in my head tag

<script>

    window.hopbak = {
        'jwt_token': localStorage.getItem('jwt_token'),
        'csrfToken': {!! json_encode( csrf_token() ) !!},
    };

</script>

in my bootstrap.js

let token = window.hopbak.jwt_token;

if (token) {

    window.axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;

} else {
    console.log('no token');
}

in my store.js

state:{
        isLoggedIn: !!localStorage.getItem("jwt_token"),
        user: localStorage.getItem("user") ? JSON.parse( localStorage.getItem("user") ) : {},
        role: localStorage.getItem("user") ? JSON.parse( localStorage.getItem("user") ).roles[0].name : '',
        showDrawer: false
    },
philliperosario commented 7 years ago

@packytagliaferro #1355