如何使用Nuxt Auth模块在Vuex中保存JWT令牌? [英] How to save JWT Token in Vuex with Nuxt Auth Module?

查看:124
本文介绍了如何使用Nuxt Auth模块在Vuex中保存JWT令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试使用VueJS将VueJS页面转换为NuxtJS.不幸的是,我在验证用户身份时遇到了一些问题,我在Google中找不到解决方案.我仅将Nuxt用于客户端.该API在表达上是完全独立的,并且可以与现有的VueJS网站一起使用.

I am currently trying to convert a VueJS page to NuxtJS with VueJS. Unfortunately I have some problems with authenticating the user and I can't find a solution in Google. I only use Nuxt for the client. The API is completely separate in express and works with the existing VueJS site.

在Nuxt中,我现在使用Auth模块将带有用户名和密码的请求发送到我的Express Server/Api. Api接收数据,对其进行检查,然后在MongoDB中找到该帐户.这完全可以正常工作.还是我认为应该的.现在,我获取用户对象并从中生成jwt.我可以调试到这里的所有内容,并且可以正常工作. 现在我可能只是不知道如何继续调试它.我将带有res.json(user,token)的答案发送回Nuxt客户端(以下代码).正如我所说,在当前的VueJS页面中,我也可以处理此问题.同样在Nuxt页面上,我在开发控制台中看到了答案,并且据我所知,答案很合适.

In Nuxt I send now with the Auth module a request with username and password to my express Server/Api. The Api receives the data, checks it, and finds the account in MongoDB. This works exactly as it should. Or as I think it should. Now I take the user object and generate the jwt from it. I can debug everything up to here and it works. Now I probably just don't know how to keep debugging it. I send an answer with res.json(user, token) back to the Nuxt client (code follows below). As I said, in my current VueJS page I can handle this as well. Also in the Nuxt page I see the answer in the dev console and to my knowledge the answer fits.

现在输入一些代码. 快递Api上的登录部分:

Now some code. The login part on the express Api:



    const User = require('../models/User')
    const jwt = require('jsonwebtoken')
    const config = require('../config/config')

    function jwtSignUser(user){
        const ONE_YEAR = 60 * 60 * 24 * 365
        return jwt.sign(user,config.authentication.jwtSecret, {
            expiresIn: ONE_YEAR
        })
    }
    module.exports = {
        async login (req, res){
            console.log(req.body)
            try{
                const {username, password} = req.body
                const user = await User.findOne({
                    username: username
                })

                if(!user){
                    return res.status(403).send({
                        error: `The login information was incorrect.`
                    })
                }

                const isPasswordValid = await user.comparePassword(password)
                if(!isPasswordValid) {
                    return res.status(403).send({
                        error: `The login information was incorrect.`
                    })
                }

                const userJson = user.toJSON()
                res.json({
                    user: userJson,
                    token: jwtSignUser(userJson)
                })

            } catch (err) {
                console.log(err)
                res.status(500).send({
                    error: `An error has occured trying to log in.`
                })
            }
        }
    }

nuxt.config.js:

nuxt.config.js:



    auth: {
        strategies: {
          local: {
            endpoints: {
              login: {url: '/login', method: 'post' },
              user: {url: '/user', method: 'get' },
              logout: false,
            }
          }
        },
        redirect: {
          login: '/profile',
          logout: '/',
          user: '/profile',
          callback:'/'
        }
      }

甚至尝试了几乎所有可能的"propertyName".

even tried it with nearly any possible "propertyName".

,最后但并非最不重要的,是我login.vue上的方法:

and, last but not least, the method on my login.vue:




    async login() {
          try {
            console.log('Logging in...')
            await this.$auth.loginWith('local', {
              data: {
                "username": this.username,
                "password": this.password
              }
            }).catch(e => {
              console.log('Failed Logging In');
            })
            if (this.$auth.loggedIn) {
              console.log('Successfully Logged In');
            }
          }catch (e) {        
            console.log('Username or Password wrong');
            console.log('Error: ', e);
          }
        }

我在这里真正不了解的内容...我总是在控制台中显示"Loggin in ...".没有错误消息.

What I really don't understand here... I always get "Loggin in..." displayed in the console. None of the error messages.

每次我提出请求(按登录"按钮)时,我都会在Chrome Dev Tools的网络"标签中获得4个新条目.两次登录",然后直接两次用户".

I get 4 new entries in the "Network" Tag in Chrome Dev Tools every time I make a request (press the Login Button). Two times "login" and directly afterwards two times "user".

第一个登录"条目如下(在常规标题"中):

The first "login" entry is as follow (in the General Headers):


Request URL: http://localhost:3001/login
Request Method: OPTIONS
Status Code: 204 No Content
Remote Address: [::1]:3001
Referrer Policy: no-referrer-when-downgrade

第一个用户"条目:


Request URL: http://localhost:3001/user
Request Method: OPTIONS
Status Code: 204 No Content
Remote Address: [::1]:3001
Referrer Policy: no-referrer-when-downgrade

都没有任何回应.

第二个登录条目:


Request URL: http://localhost:3001/login
Request Method: POST
Status Code: 200 OK
Remote Address: [::1]:3001
Referrer Policy: no-referrer-when-downgrade

,响应是带有令牌的对象和用户对象.

and the Response is the object with the token and the user object.

第二个用户条目:


Request URL: http://localhost:3001/user
Request Method: GET
Status Code: 200 OK
Remote Address: [::1]:3001
Referrer Policy: no-referrer-when-downgrade

,响应是用户对象.

我认为对于登录,仅应与登录请求相关,否则我错了?用户请求之所以有效,是因为客户端请求了用户路线和用户路线,所以总是将答案与实际用户对象一起发送到我的Express API中.

I think for the login should only the login request be relevant, or I'm wrong? And the user request works because the client has asked for the user route and the user route, always send the answer with the actual user object in my Express API.

因为我认为问题出在登录响应中?这里是Chrome开发人员工具中网络"标签中的一些屏幕截图,其中包含登录请求/响应.

Because I think, the problem is in the login response? Here some screenshots from the Network Tab in Chrome Dev Tools with the Request/Response for login.

首次登录请求无响应
第二次登录请求
响应第二次登录请求

First login request without response
Second login request
Response to second login request

我必须在Vuex商店中做点什么吗?在使用google时使用身份验证模块的示例中,我从未发现任何已配置的Vuex商店,因此我不必在这里进行任何更改.

Do I have to do something with my Vuex Store? I never found any configured Vuex Stores in examples for using the Auth Module while using google so I thougt I do not have to change here anything.

这是我的Vuex商店(Chrome中的Vue开发工具)在尝试登录后未成功的情况:

Thats my Vuex Store (Vue Dev Tools in Chrome) after trying to login without success:


{"navbar":false,"token":null,"user":null,"isUserLoggedIn":false,"access":false,"auth":{"user":"__vue_devtool_undefined__","loggedIn":false,"strategy":"local","busy":false},"feedType":"popular"}

我的实际VueJS网站也使用了一些逻辑.当身份验证模块正常工作时,我将删除该地址.

There is also some logic I use for my actual VueJS site. I will remove that when the Auth Module is working.

@imreBoersma询问: 我在Express上的/user端点看起来像:

Asked by @imreBoersma : My /user endpoint on Express looks like:



    app.get('/user', 
            isAuthenticated,
            UsersController.getUser)

我首先检查用户是否已通过身份验证:

I first check if the User is authenticated:



    const passport = require('passport')

    module.exports = function (req, res, next) {
        passport.authenticate('jwt', function (err, user) {
            if(err || !user) {
                res.status(403).send({
                    error: 'You are not authorized to do this.'
                })
            } else {
                req.user = user
                next()
            }
        })(req, res, next)
    }

之后,我在MongoDB中搜索用户"文档,并将该文档发送给客户端:

After that I search the User document in MongoDB and send the document to the client:



    const User = require('../models/User')

    module.exports = {
        [...]
        getUser (req, res) {
            User.findById(req.user._id, function (error, user){
                if (error) { console.error(error); }
                res.send(user)
            })
        }
        [...]

    }

随时询问更多信息.

推荐答案

我认为我可以回答自己的问题.

I think I can answer my own question.

我一直在搜索有关我的api响应的错误. 问题是nuxt.config.js中用户端点上的"propertyName".

I searched the whole time for an error regarding to my api response. The problem was the "propertyName" on user endpoint in the nuxt.config.js.

默认设置为"user".当我将其设置为"propertyName: false",时,一切都会正常进行.

It is set to "user" as default. When I set it to "propertyName: false", than everything works as it should.

 auth: {
    strategies: {
      local: {
        endpoints: {
          login: {url: '/login', method: 'post', propertyName: 'token' },
          user: {url: '/user', method: 'get', propertyName: false },
          logout: false,
        }
      }
    }
  },

这篇关于如何使用Nuxt Auth模块在Vuex中保存JWT令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆