2017-09-08 6 views
3

VueJS를 프런트 엔드로, Laravel을 백엔드로 사용하여 단일 페이지 응용 프로그램 (SPA)을 작성하려고합니다. 나는 등 인증 토큰
Laravel API - 페이지를 다시로드 한 직후 인증이 작동합니다.


문제 관리 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', '[email protected]'); 
}); 

Laravel 기능

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


오류 메시지

enter image description here,617,
페이지를 다시로드하면 오류 메시지가 사라지고 성공적으로 인증됩니다.


나는 어떤 종류의 도움에 매우 만족할 것입니다!

+1

resposne보다 중요한 것은 실패한 호출에 대한 요청 헤더입니다. 토큰이 실제로 전송되었는지 확인할 수 있습니까? 내가 본 것에서는 로그인 후 기본 요청 헤더 설정이 누락되었습니다. 아마 응용 프로그램의 시작에 한 번 발생하고 따라서 다시로드 후 작동 –

+0

정말 고마워요! 그게 정확히 문제 였어! 모든 요청과 함께 헤더를 보내지 않았습니다! – Schwesi

답변

2

Frank Provost 덕분에 나는 대답을 알아 냈습니다. 다른 사람이 같은 문제를 겪는 경우 :

요청할 때마다 토큰을 전달하지 않았습니다. URL을 새로 고침 할 필요 -

나는 모든 것이 예상대로 작동 지금이

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

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

을 변경할 수 없었다.