IT이야기

Vue JS에서 로그인 API 토큰 처리

cyworld 2022. 4. 10. 21:39
반응형

Vue JS에서 로그인 API 토큰 처리

다음 로그인 구성 요소를 사용 중:

var Login = Vue.extend({
    template: '#auth',
    data: function () {
        return {username: '',password: '',errorMessage:''};
    },
    methods : {
        login: function (e) {
            var _this = this;
            $.ajax({
                url: "/vue/api/login",
                type: "POST",
                async:false,
                data:{
                    username:_this.username,
                    password: _this.password
                },
                success: function (data) {
                // store the token in global variable ??
                    router.push({
                        path: '/employeeList',
                    });
                },
                error:function (xhr, status, error) {

                    _this.errorMessage = xhr.responseText
                }
            });
        }
    }
});

로그인 API는 성공적인 인증을 위해 토큰 문자열을 반환한다.글로벌 변수 또는 로컬 스토리지에 저장해야 하는가?사용자가 애플리케이션에 로그인했는지 확인한 후 그에 따라 리디렉션할 수 있는 필터가 있는가?

가장 좋은 방법은 VUEX : vue 상태 관리 시스템을 사용하는 것이다.

vuex store.js 파일에서 다음과 같이 사용자의 상태를 정의할 수 있다.

const store = new Vuex.Store({ 
    state: { 
        user: {
            userName:'',
            loggedInStatus: true,
            authToken: ''
        }
    }, 
    mutations: { 
        addWebToken: function(state, webToken){
            state.user.authToken = webToken;
        },
        removeWebToken: function(state){
            state.user.authToken = '';
        }
    },
    actions: {
        login: function(context, userInput){
            $.ajax({
                url: "/vue/api/login",
                type: "POST",
                async:false,
                data:{
                    username:userInput.username,
                    password: userInput.password
                },
                success: function (data) {
                // store the token in global variable ??

                context.commit('addWebToken', webToken); // pass the webtoken as payload to the mutation

                    router.push({
                        path: '/employeeList',
                    });
                },
                error:function (xhr, status, error) {

                    _this.errorMessage = xhr.responseText
                }
            });
        },
        logput: function(context){
            //your logout functionality
            context.commit('removeWebToken');
        }
    }

})

이제 당신의 컴포넌트 > 메소드 > 로그인 x 당신은 당신의 vuex srore에서 당신이 선언했던 로그인 동작을 다음과 같이 발송할 수 있다.

var Login = Vue.extend({
        template: '#auth',
        data: function () {
            return {username: '',password: '',errorMessage:''};
        },
        methods : {
            login: function () {
                //passing the username and password in an object as payload to the login action
                this.$store.dispatch('login', {username: this.username, ppassword: password});
            },
            logout: function(){
                this.$store.dispatch('logout');
            }
        }
    });

그렇게 하는 것의 이점:

  • 중앙 집중식 상태에서 해당 상태의 사용자 정보를 관리할 수 있는 경우

  • 아래 나온 것처럼 vuex 유지 상태를 사용하여 로컬 스토어에 상태 또는 쿠키로 저장하면 웹토큰을 포함한 사용자의 상태가 저장되고 페이지 새로 고침 시 상태도 유지된다.즉, 사용자가 로그인하여 페이지를 새로 고칠 때, 상점에서 사용자 상태를 유지하므로 웹토큰에 접속하여 로그인 상태를 유지할 수 있다.

const store = new Store({ // ... plugins: [ createPersistedState({ getState: (key) => Cookies.getJSON(key), setState: (key, state) => Cookies.set(key, state, { expires: 3, secure: true }) }) ] })

vuex-persistedstate 설명서에 따라 원하는 경우 vuex 지속 상태 플러그인을 저장소에 추가하고 jscookies 라이브러리를 사용하여 쿠키 또는 다른 로컬 저장소에 사용자 상태를 저장하십시오.

참조URL: https://stackoverflow.com/questions/43581958/handle-login-api-token-in-vue-js

반응형