简体   繁体   English

Vue.js 2 身份验证 JWT

[英]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我正在尝试使用此样板https://github.com/vuejs-templates/webpack制作 Vue.js2 应用程序

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.我被困在身份验证过程中,使用这个库: https : //github.com/websanova/vue-auth并尝试使用 JWT 作为身份验证方法。 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我安装的可能相关的软件包: passport, passport-jwt, jsonwebtokenspassport-local, passport-local-mongoose passport, passport-jwt, jsonwebtokens

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).查看我的日志,我得到了成功的登录响应,但随后它尝试获取/auth/user并以 401(未经授权的错误)进行响应。 Perusing the auth library code, a GET req to /auth/user seems to be the expected behavior.仔细阅读 auth 库代码,对/auth/user的 GET req 似乎是预期的行为。

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.我可以肯定的是:服务器实际上在登录请求期间创建了一个有效的 JWT(在 jwt.io 上检查)。 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.响应中提到了Authorization Bearer标头,我确信它没有被设置。 Nor do I understand where or how to do this.我也不明白在哪里或如何做到这一点。 There is no token set in localStorage after the login request.登录请求后localStorage中没有设置token。 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)编辑(8 个月后)

Gist to Solution here (slashes replaced by dashes in filenames): https://gist.github.com/wcarron27/b0db7a16df9ceff924d4a75050093c55解决方案的要点(斜线替换为文件名中的破折号): 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.我的登录方法最初不起作用的原因是 localStorage 令牌设置不正确,因此无法在客户端重定向上传递 getData 方法。 vue-auth does this by default. vue-auth 默认执行此操作。 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.通过编辑它在 vue-auth 配置中点击的 url,我能够将它定向到正确的路由(但只有在我正确设置了 localstorage 令牌之后。使用Vue.http.options.rootUrl (或其他东西,它在主目录中) .js 文件)来设置Authorization标头。

In the code, You must register vue-auth on the client side main.js , and call to it in the Login.vue "login" method.代码中,你必须在客户端main.js注册 vue-auth ,并在Login.vue “登录”方法中调用它。 The client side config directs the http calls to the specified route in main.js .客户端配置将 http 调用定向到main.js的指定路由。 In the callback, the user and tokens are set in localStorage and the Vuex store.在回调中,用户和令牌设置在 localStorage 和 Vuex 存储中。

The Http reqs go the the API side and hit the route in accounts.js. Http 请求进入 API 端并命中accounts.js.的路由accounts.js. That route uses a passport strategy defined in ./util/passport.js , as well as a setJWT function defined in ./util/jwtLib.js .这条路使用中定义的护照战略./util/passport.js ,以及在定义的setJWT功能./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.在此之后,客户端被重定向到我选择的路由,数据由我的 store 和 ajax 调用填充。 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.状态在刷新时被丢弃,所以不要依赖 vuex 来持久化。 A combination of localStorage and vuex does the trick, though.不过,localStorage 和 vuex 的组合可以解决问题。

I didn't verify this but, does remove the 'this' from your code on line 7 do the magic?我没有验证这一点,但是,从第 7 行的代码中删除“this”是否有用?

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
    });
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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