使用vue和express保存令牌和用户

时间:2017-10-06 20:01:17

标签: session express vue.js token

我试图建立一个身份验证系统。一切顺利,但这是一个小问题,每次刷新页面时用户都会断开连接。我想我已经以某种方式在会话中保存了令牌和用户,但我不知道如何。

完整项目在这里:ElasticSearch's Support Diagnostics

procedure ImpInsData(fileN varchar2,Tname VARCHAR2)
as
begin
   IXRBI.EXternalChange ( fileN,Tname);      
   declare
      cursor cur_extenal is select * from Tname WHERE A IN ('1','2');
   begin 
      FOR rec IN cur_extenal LOOP 
         vId :=sys_guid();
         vRowStatus:=rec.A;
         vTag:=rec.C;
       end loop
   end;
end;

我如何发送数据

// Token setup
function jwtSignUser(user) {
    const ONE_WEEK = 60 * 60 * 24 * 7;
    return jwt.sign(user, process.env.JWT_SECRET, {
    expiresIn: ONE_WEEK
  });
}

解决方案: 我解决了这个问题,你可以在这里找到最终项目 Github

我更改了将令牌保存到localStorage的方法

1 个答案:

答案 0 :(得分:1)

问题似乎是你将令牌存储在内存中,而不是localStorage

https://github.com/gnome1337/coworking-lab/blob/Authentification/client/src/store/store.js#L15

state.token = token

如果刷新,实际上并不存储商店,但localStarage会存在。这里有一篇很好的文章:https://auth0.com/blog/build-an-app-with-vuejs/可以帮助你实现这一目标。阅读文章,或者tl; dr;下面...

// src/auth/index.js

import {router} from '../index'

// URL and endpoint constants
const API_URL = 'http://localhost:3001/'
const LOGIN_URL = API_URL + 'sessions/create/'
const SIGNUP_URL = API_URL + 'users/'

export default {

  // User object will let us check authentication status
  user: {
    authenticated: false
  },

  // Send a request to the login URL and save the returned JWT
  login(context, creds, redirect) {
    context.$http.post(LOGIN_URL, creds, (data) => {
      localStorage.setItem('id_token', data.id_token)
      localStorage.setItem('access_token', data.access_token)

      this.user.authenticated = true

      // Redirect to a specified route
      if(redirect) {
        router.go(redirect)        
      }

    }).error((err) => {
      context.error = err
    })
  },

  signup(context, creds, redirect) {
    context.$http.post(SIGNUP_URL, creds, (data) => {
      localStorage.setItem('id_token', data.id_token)
      localStorage.setItem('access_token', data.access_token)

      this.user.authenticated = true

      if(redirect) {
        router.go(redirect)        
      }

    }).error((err) => {
      context.error = err
    })
  },

  // To log out, we just need to remove the token
  logout() {
    localStorage.removeItem('id_token')
    localStorage.removeItem('access_token')
    this.user.authenticated = false
  },

  checkAuth() {
    var jwt = localStorage.getItem('id_token')
    if(jwt) {
      this.user.authenticated = true
    }
    else {
      this.user.authenticated = false      
    }
  },

  // The object to be passed as a header for authenticated requests
  getAuthHeader() {
    return {
      'Authorization': 'Bearer ' + localStorage.getItem('access_token')
    }
  }
}