programing

Laravel API - 페이지를 새로고침한 직후에 인증이 동작합니다.

bestcode 2022. 7. 10. 21:20
반응형

Laravel API - 페이지를 새로고침한 직후에 인증이 동작합니다.

VueJs를 프런트엔드로, Larabel을 백엔드로 사용하여 Single Page Application(SPA)을 구축하려고 합니다.
는 라라벨의 여권을 사용하여 인증 토큰 등을 관리하고 있습니다.


문제: After login I have to reload the page to be successfully authenticated.


로그인 방법

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 })
    }
})


라라벨 루트

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

라라벨 함수

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


에러 메시지

여기에 이미지 설명 입력
When I reload the page the error message disappears and I am successfully authenticated.


I would be very happy for any kind of help!

프랭크 프로보스트 덕분에 나는 답을 알아냈다.다른 사람이 같은 문제에 직면했을 경우:

나는 모든 요청에 대해 토큰을 전달하지 않았다.

나는 이것을 바꿔야 했다.

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을 새로 고칠 필요가 없습니다.

언급URL : https://stackoverflow.com/questions/46112610/laravel-api-authentication-works-just-after-reloading-the-page

반응형