简体   繁体   中英

Vue.js 2 Authentication JWT

[ Post has been edited: see below for answer ]

I am trying to make a Vue.js2 application using this boilerplate https://github.com/vuejs-templates/webpack

I am stuck on the Authentication process, using this library: https://github.com/websanova/vue-auth and attempting to use JWT as the authentication method. Never having rolled my own authentication before, I am slightly lost.

Packages I have installed which may be relevant: passport, passport-jwt, jsonwebtokens , passport-local, passport-local-mongoose

Looking at my logs I get a successful login response, but then it attempts to get /auth/user and responds with a 401 (unauthorized error). Perusing the auth library code, a GET req to /auth/user seems to be the expected behavior.

Here is the login code (client side):

methods: {
  login() {
    this.$auth.login({
      body: this.data.body
      success(res) {
        console.log('Success: '+this.context);
        this.localStorage.setItem('auth-token', res.body.token);
      },
      error(res) {
        console.log("Error: " + this.context);
        this.error = res.data;
      },
      rememberMe: true,
      fetchUser: true
    });
  }
}

And here is the appropriate code server-side:

  • Removed Link | See Edits Section *

What I am sure of is this: the server does in fact create a JWT which is valid (checked on jwt.io) during the login request. It does not appear to be set anywhere afterwards. It just sits there and then dies. There are mentions of an Authorization Bearer header in the response, which I am certain is not being set. Nor do I understand where or how to do this. There is no token set in localStorage after the login request. I'm not sure if this should exist, but think it likely that it should. In my console, searching local storage yields some strings and large integers, but no mention of a token in it.

Edits (8+ months later)

Gist to Solution here (slashes replaced by dashes in filenames): https://gist.github.com/wcarron27/b0db7a16df9ceff924d4a75050093c55

The reason my login method originally did not work was that the localStorage token was not set correctly, and thus failed to pass the getData method on the client-side redirect. vue-auth does this by default. By editing the url it hits in the vue-auth config, I was able to direct it to the proper route(BUT only after I properly set the localstorage token. Use Vue.http.options.rootUrl (or something, it's in the main.js file in the gist) to set the Authorization header.

In the code, You must register vue-auth on the client side main.js , and call to it in the Login.vue "login" method. The client side config directs the http calls to the specified route in main.js . In the callback, the user and tokens are set in localStorage and the Vuex store.

The Http reqs go the the API side and hit the route in accounts.js. That route uses a passport strategy defined in ./util/passport.js , as well as a setJWT function defined in ./util/jwtLib.js .

After this, the client is redirected to a route of my choice, and data is populated by my store and ajax calls. Keep in mind, that while this should solve logins, i have not verified code correctness, as basically I would have needed to post the whole of two separate codebases.

Additionally, this does not account for refresh errors. State is dropped on refresh, so do not rely on vuex for persistence. A combination of localStorage and vuex does the trick, though.

I didn't verify this but, does remove the 'this' from your code on line 7 do the magic?

methods: {
  login() {
    this.$auth.login({
      body: this.data.body
      success(res) {
        console.log('Success: '+this.context);
        // original code here --> this.localStorage.setItem('auth-token', res.body.token);
        localStorage.setItem('auth-token', res.body.token);
      },
      error(res) {
        console.log("Error: " + this.context);
        this.error = res.data;
      },
      rememberMe: true,
      fetchUser: true
    });
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM