programing

Vue SPA - 사용자가 인증되었는지 확인하고 인증되지 않은 경우 로그인으로 수정합니다.

itsource 2022. 7. 14. 20:39
반응형

Vue SPA - 사용자가 인증되었는지 확인하고 인증되지 않은 경우 로그인으로 수정합니다.

나는 가지고 있다VueJSJWT 인증을 사용합니다.

페이지를 새로고침한 후 사용자가 인증되었는지 확인하고 인증되지 않은 경우 로그인 페이지로 리디렉션하는 방법을 알아보려고 합니다.

accessToken그리고.refreshToken에 저장됩니다.cookies에도Vuex

Vuex.state:

auth: {
        user: {},
        isAuthenticated: false,
        accessToken: null,
        refreshToken: null
    },

Vuex.actions.refresh상품권

    refreshToken: async ({state, commit, dispatch}) => {
        try {
            await api.jwtRefresh(state.auth.refreshToken).then(response => {
                if (response.status === 200) {
                    dispatch("setAuthData",{
                        accessToken:response.data.access,
                        isAuthenticated:true
                    })
                }
            }).catch(err => {
                dispatch('logout')
            });
        } catch (e) {
            dispatch('logout')
        }
    },

App.vue

export default {
  data: () => ({}),
  mounted() {
    this.$store.dispatch('setAuthDataFromCookies')
    this.$store.dispatch('refreshToken') // checks if user is authenticated, redirect to login page if not
    this.$router.push('/dashboard')
  }
}

JWT 토큰을 새로 고치는 것이 제 생각입니다.정상적으로 갱신된 경우는, 유저는 다음의 순서로 진행할 수 있습니다./dashboard그렇지 않으면 사용자는 로 리다이렉트 됩니다./login

문제는 말이다mounted까지 기다리지 않는다refreshToken실행이 완료되어 사용자가 즉시 로 리다이렉트 됩니다./dashboard토큰이 새로 고쳐지기 전이라도.

어떻게 하면 기다리게 할 수 있을까요?(내용이)refreshToken로 사용자를 리다이렉트 합니다./login에러가 있는 경우

메타를 설정할 수 있습니다.auth라우터의 필드 및 글로벌beforeEnter또는beforeEachVuex(또는 쿠키 또는 둘 다)에서 토큰을 체크하는 가드입니다.

고객님의 고객명router.js파일 같은 걸 가지고 있을 거예요

routes: [
  {
    name: 'Login'
  },
  {
    name: 'Dashboard', // + path, component, etc
    meta: {
      auth: true
    }
  }
]

그런 다음 다음과 같은 글로벌 가드를 설정합니다.

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.auth)) {
    if (!store.getters.authToken) {
      next({ name: 'Login' });
    } else {
      next();
    }
  } else {
    next(); // Very important to call next() in this case!
  }
})

각 루트가 이행하기 전에 다음 루트에 다음 루트가 있는지 여부를 확인합니다.auth메타 필드이 경우 Vuex 상태에 토큰이 있는지 확인하고 그렇지 않으면 정상적으로 이동합니다.

네비게이션 가드에 관한 Vue 라우터 문서

사용자의 경우 사용자 인증을 시도하고 있기 때문에 내부 엔드포인트에 전화를 걸기만 하면 됩니다.beforeEach그런 식으로 경계하고 리다이렉트하는 거죠콜백이 비동기화 되어 있는지 확인해 주세요.router.beforeEach(async (to, from, next) => {})

언급URL : https://stackoverflow.com/questions/68609776/vue-spa-check-if-user-is-authenticated-redirect-to-login-if-not

반응형