jwt跨域身份验证

jsonwebtoken

流程:

1、前端用户向服务器以post的方式发送账户密码

2、服务器对收到的账户密码和数据库中存储的账户密码进行验证,并存储验证信息

3、服务器返回一个口令给前端,

4、前端保存口令,(localstorage),下次访问服务器的时候,将口令返回给服务器

5、服务器验证口令,判断用户的信息和登录状态

6、重置口令过期时间,

 checkAuth(){

    let token = this.ctx.headers['x-token'];

    const {secret,cookie,exipre} = this.config('jwt')

    try {

      var tokenObj = token? jsonwebtoken.verify(token,secret):{};

      this.ctx.state.username = tokenObj.name;

    } catch (error) {

      return this.authFail()

    }

    if(!tokenObj.name){

      return this.authFail()

    }

    this.updateAuth(token.name)

  }


updateAuth(userName){

    const userInfo = {

      name:userName

    };

    // 获取jwt的配置信息

    const {secret,cookie,expire} = this.config('jwt')

    const token = jsonwebtoken.sign(userInfo,secret,{expiresIn:expire});

    this.cookie(cookie,token);

    this.header('authorization',token);  //将token加入在请求头中,

    return token;

  }


  //根据用户名username查询数据库中该用户的用户名以及密码,并进行比对,如果比对成功,更新token,同时可以将token返回

if (user.password == this.verifyPassword(password)) {

                //完成登陆-更新token

                const token = this.updateAuth(username);

                this.json({ state: '登陆成功', token: token })

            } else {

                return this.json({ state: "登陆失败" })

            }

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。