【问题标题】:Laravel API - Authentication works just after reloading the pageLaravel API - 重新加载页面后身份验证工作
【发布时间】:2018-02-17 03:38:39
【问题描述】:

我正在尝试使用 VueJS 作为前端和 Laravel 作为后端来构建单页应用程序 (SPA)。
我正在使用laravel's passport 来管理身份验证令牌等。


问题:登录后我必须重新加载页面才能成功验证。


登录方式
data() {
   return {
       email: '',
       password: '',
   }
},
methods: {
   login() {
       var data = {
           client_id: 2,
           client_secret: '****************************',
           grant_type: 'password',
           username: this.email,
           password: this.password
       }
       // send data
       this.$http.post('oauth/token', data)
          .then(response => {
               // authenticate the user
               this.$store.dispatch({
                   type: 'authenticate',
                   token: response.body.access_token,
                   expiration: response.body.expires_in + Date.now()
               })
               // redirect after successful login
               if (this.$route.query.from)
                    this.$router.push(this.$route.query.from)
               else
                    this.$router.push('/feed')
               })
        }
    }

从后台获取用户信息(刷新页面后才生效)

setUser () {
     // this route throws 'unauthenticated' error 
     // and works only after refreshing the page
     this.$http.get('api/users/') 
          .then(response => {
              this.$store.dispatch({
                   type: 'setUser',
                   id: response.body.id,
                   email: response.body.email,
                   name: response.body.name
               })
          })
     }
}

Vuex 商店

export default new Vuex.Store({
    state: {
        isAuth: !!localStorage.getItem('token'),
        user: {
            id: localStorage.getItem('id'),
            email: localStorage.getItem('email'),
            name: localStorage.getItem('name')
        }
    },
    getters: {
        isLoggedIn(state) {
            return state.isAuth
        },
        getUser(state) {
            return state.user
        }
    },
    mutations: {
        authenticate(state, { token, expiration }) {
            localStorage.setItem('token', token)
            localStorage.setItem('expiration', expiration)
            state.isAuth = true
        },
        setUser(state, { id, email, name }) {
            localStorage.setItem('id', id)
            localStorage.setItem('email', email)
            localStorage.setItem('name', name)
            state.user.id = id
            state.user.email = email
            state.user.name = name
        }
    },
    actions: {
        authenticate: ({ commit }, { token, expiration }) => commit('authenticate', { token, expiration }),
        setUser: ({ commit }, { id, email, name }) => commit('setUser', { id, email, name })
    }
})


Laravel 路线
Route::group(['middleware' => 'auth:api'], function() {
    Route::get('/users', 'UsersController@users');
});

Laravel 函数

public function users(Request $request)
{
   return $request->user();
}


错误信息


当我重新加载页面时,错误消息消失并且我已成功通过身份验证。


我会很高兴得到任何帮助!

【问题讨论】:

  • 比响应更重要的是失败调用的请求标头。您可以验证令牌是否实际发送?从我看到的情况来看,您只是缺少在登录后设置默认请求标头。可能在应用程序启动时发生一次,因此在重新加载后工作
  • 非常感谢!这正是问题所在!我没有在每个请求中都发送标头!

标签: laravel vue.js vuejs2 vuex laravel-passport


【解决方案1】:

感谢 Frank Provost,我找到了答案。万一其他人遇到同样的问题:

我没有在每个请求中都传递令牌。

我不得不改变这个

Vue.http.headers.common['Authorization'] = 'Bearer ' + Vue.auth.getToken()

到这里

Vue.http.interceptors.push((request, next) => {
    request.headers.set('Authorization', 'Bearer ' + Vue.auth.getToken())
    request.headers.set('Accept', 'application/json')
    next()
})

现在,一切正常 - 无需刷新 url。

【讨论】:

    猜你喜欢
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    • 2014-10-30
    相关资源
    最近更新 更多