programing

Vue.js & Vuex - 액세스 토큰을 스토어에 저장하고 사용자를 URL로 리다이렉트하여 로그인을 합니다.

bestcode 2022. 8. 16. 23:22
반응형

Vue.js & Vuex - 액세스 토큰을 스토어에 저장하고 사용자를 URL로 리다이렉트하여 로그인을 합니다.

액세스 토큰을 createStore(index.js)에 저장한 후 사용자가 로그인하면 다른 웹 페이지로 이동하도록 리디렉션하려고 합니다.

이를 위해 액세스 토큰과 새로 고침 토큰을 설정할 수 있도록 mutoriations.js 내에 변환을 생성해야 합니다.새로 고침은 타임스탬프처럼 해야 합니다.

시험.vue는 사용자를 검증하기 위한 로그인 코드입니다.

따라서 기본적으로 기능을 만들고 액세스 토큰을 설정하고 새로 고침 토큰을 설정한 후 로그인 버튼을 누르면 사용자를 다른 웹 페이지로 리디렉션해야 합니다.

잘 부탁드립니다!

index.syslog:

import vuex from 'vuex';
import mutations from './mutations';

const createStore = () =>{
    return new vuex.Store({
        state: {
            accessToken: "halo",
            access_token: response.data.access_token,
            refresh: response.data.refresh_token
        },
        getters:{
            accessToken(state, getters){
                return state.accessToken;
            }
        },
        mutations
    });
};

export default createStore;

modiations.modiations:

const mutations = {
    setToken(state, token) {
      state.accessToken = token;
    }
  }

  export default mutations;

test.vue:

<template>
    <form>
        <div class="login">
            <div>
                <input name="email" type="text" v-model="email" v-validate="'required'" placeholder="Email" class="eSection" id="email">
                <p v-show="wrong.email">
                    Email is missing or incorrect. Please try again!
                </p>

                <i name="emailFormat" type="text" v-validate="'required|emailFormat'" placeholder="Email" class="eSection" id="email"></i>
                <p v-show="wrong.emailFormat">
                    Not valid email!
                </p>

                <input name="password" type="password" v-model="password" v-validate="'required'" placeholder="Password" class="pSection"
                    id="password">
                <p v-show="wrong.password">
                    Password is missing or incorrect. Please try again!
                </p>

                <p v-show="wrong.all">
                    Login Details Incorrect!
                </p>

                <button type="button" class="log" @click="login">LogIn</button>
            </div>
        </div>
    </form>
</template>

<script>
import axios from 'axios';
export default {
    data() {
        return {
            email: "test@gmail.com",
            password: "123456",
            flag: false,
            wrong: {
                email: false,
                emailFormat: false,
                password: false,
                all: false
            },
        }
    },

    methods: {
        login: function (index) {

            this.wrong.email = false;
            this.wrong.password = false;
            this.wrong.all = false;
            this.wrong.emailFormat = false;

            axios.post(`https://api.ticket.co/auth/login`, {
                    email: this.email,
                    password: this.password
                })

                .then(response => {
                    // JSON responses are automatically parsed.
                    console.log(response.data)
                    console.log(response.status)
                })

                .catch(e => {
                    console.log(e)
                    console.log(e.response.status)

                    var vueObject = this

                    switch (e.response.status) {
                        case 400:
                            if (!vueObject.email) {
                                console.log(1)
                                this.wrong.email = true;
                            } else if (!vueObject.emailFormat) {
                                console.log(2)
                                this.wrong.emailFormat = true;
                            };

                            if (!vueObject.password) {
                                console.log(3)
                                this.wrong.password = true;
                            }
                            break;

                        case 401:
                            console.log(4)
                            this.wrong.all = true;
                            break;
                    }
                })
        },
    },
}
</script>

저는 이 문제에 대해 두 가지 해결책이 있다고 생각합니다.

  • 첫 번째: vue-router를 사용할 수 있습니다.이 경우 페이지 새로 고침은 없으며 구성 요소만 변경됩니다.이렇게 하면 페이지를 새로 고칠 때까지 모든 vuex 상태가 유지됩니다(단, 최적의 솔루션은 아닙니다).
  • 둘째, 사용자가 인증한 경우 실제 사용자 토큰을 반환하는 rest call을 쓸 수 있습니다.따라서 이 rest api 호출만이 세션 인증 및/또는 CSRF 토큰을 사용합니다(모르는 경우 wiki 체크).Axios 인터셉터(각 Axios 호출 전에 실행)를 사용하는 경우 가장 우아한 방법 중 하나는 사용자가 인증되었을 때 토큰을 얻는 방법입니다.자세한 내용은 이 github 코멘트를 확인해 주세요.(세션의 타임아웃이 토큰의 라이프 타임보다 긴 것을 확인해 주세요:)

언급URL : https://stackoverflow.com/questions/50610195/vue-js-vuex-store-access-token-in-store-and-redirect-user-to-an-url-for-logi

반응형