简体   繁体   English

Nuxt.js + Auth(jwt 刷新令牌)

[英]Nuxt.js + Auth ( jwt refresh token )

I have used Auth library for my Vue/Nuxt project.我为我的 Vue/Nuxt 项目使用了 Auth 库。 JWT Authentication works for me just fine, but there is a problem with refresh token . JWT 身份验证对我来说很好,但刷新令牌有问题。

First of all refreshToken cookie is always set to null:首先,refreshToken cookie 始终设置为 null:

在此处输入图像描述

Secondly, when i call this.$auth.refreshTokens() i got an error:其次,当我调用 this.$auth.refreshTokens() 时出现错误:

this.$auth.refreshTokens is not a function this.$auth.refreshTokens 不是 function

I have been trying for a long time to solve this, but i finally give up:(我已经尝试了很长时间来解决这个问题,但我终于放弃了:(

You can see my server side and client side code on my GitHub.你可以在我的 GitHub 上看到我的服务器端客户端代码。

For a shortcat, below is fragment of nuxt.config.js file:对于 shortcat,下面是 nuxt.config.js 文件的片段:

   auth: {
    strategies: {
      local: {
        scheme: 'refresh',
        token: {
          property: 'token',
          maxAge: 30,
          // type: 'Bearer'
        },
        refreshToken: {
          property: 'refreshToken',
          data: 'refreshToken',
          maxAge: 60
        },
        user: {},
        endpoints: {
          login: { url: 'users/login', method: 'post' },
          refresh: { url: 'users/refreshToken', method: 'post' },
          user: { url: 'users/me', method: 'get', propertyName: '' },
          logout: false
        },
        // autoLogout: false
      }
    }
 },

I have already checked if all names in the client config file and server are meet.我已经检查了客户端配置文件和服务器中的所有名称是否都符合。 Thank you in advance for your help and i am so sorry for mistakes in my English, i did my best...预先感谢您的帮助,对于我的英语错误,我深表歉意,我已尽力...

I think I made it, let me share with you what i did I worte a plugin called auth this plugin basicly co the following我想我做到了,让我与你分享我做了什么我写了一个名为 auth 的插件,这个插件基本上与以下内容有关

  • check if there is a token stored or not检查是否存储了令牌
  • then check if the stored token has been expiried or not by making a request to get the user data然后通过请求获取用户数据来检查存储的令牌是否已过期
  • if the request fails we make a request to /refresh endpoint which refresh the current token in the request headers then send it back in the response如果请求失败,我们向/refresh端点发出请求,该端点刷新请求标头中的当前令牌,然后在响应中将其发送回
  • we take this new token and store at in the client side我们获取这个新令牌并存储在客户端
  • if the refresh request fails too, we cleared the auth object如果refresh请求也失败,我们清除了授权 object

This is the plugin code这是插件代码

const strategy = 'local'
const FALLBACK_INTERVAL = 900 * 1000 * 0.75

async function refreshTokenF($auth, $axios, refreshToken) {
    try {
        const response = await $axios.post('/refresh')
        let token = 'Bearer ' + response.data.token
        console.log(refreshToken);
        console.log(token);
        $auth.setToken(strategy, token)
        $axios.setToken(token)
        return decodeToken.call(this, token).exp
    } catch (error) {
        $auth.logout()
        throw new Error('Error while refreshing token')
    }
}

export default async function ({app}) {

    const {$axios, $auth} = app

    let token = $auth.getToken(strategy)
    let refreshInterval = FALLBACK_INTERVAL
    if (token) {
        $axios.get('/me').then((resp) => {
            $auth.setUser(resp.data.data)
        }).catch(async () => {
            try {
                await refreshTokenF($auth,$axios,token);
            } catch (e) {
                $auth.logOut();
            }
        })
    }

    setInterval(async function () {
        token = $auth.getToken(strategy)
        await refreshTokenF($auth, $axios, token)
    }, refreshInterval)

}

Also have a look on my controller to refresh the token也看看我的 controller 刷新令牌

<?php


namespace App\Http\Controllers\Api\Auth;


use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Mpdf\Tag\THead;
use Tymon\JWTAuth\JWTAuth;

class RefreshController extends Controller
{

    protected $auth;
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct(JWTAuth $auth)
    {
        $this->auth = $auth;
    }

    public function refresh(Request  $request)
    {
        $this->auth->setRequest($request);
        $arr = $this->auth->getToken();
        $arr = $this->auth->refresh();
        $this->auth->setToken($arr);
        return response()->json([
            'success' => true,
            'data' => $request->user(),
            'token' => $arr
        ], 200);    }

}

Have a nice day祝你今天过得愉快

You have been looking at DEV docs.您一直在查看 DEV 文档。 The refreshToken will be available from version 5 of nuxt-auth. refreshToken 将从 nuxt-auth 版本 5 开始提供。 Try installing dev branch of auth module to have access to refreshToken()尝试安装 auth 模块的 dev 分支以访问 refreshToken()

https://github.com/nuxt-community/auth-module/issues/761 https://github.com/nuxt-community/auth-module/issues/761

As already pointed out by @Hvitis, this is not supported on versions < 5 of @nuxt/auth .正如@Hvitis 已经指出的那样, @nuxt/auth < 5的版本不支持此功能。 In order to use the newest version of the package instructed in the docs , you have to add the @nuxt/auth-next package - which will add version 5.0.0 to your Nuxt application.为了使用文档中指示的最新版本package ,您必须添加@nuxt/auth-next package - 这会将版本 5.0.0 添加到您的 Nuxt 应用程序。

yarn add @nuxt/auth-next

On the nuxt.config.js , register the module - make sure you exclude @nuxt/auth as well -, and add the refresh schemas as below:nuxt.config.js ,注册模块 - 确保你也排除了@nuxt/auth -,并添加如下refresh模式:

export default {
    ...
    modules = [
        ...
        "@nuxtjs/axios",
        "@nuxt/auth-next"
    ],
    ...
    auth: {
        strategies: {
            local: {
                  scheme: 'refresh',
                  token: {
                      property: 'access',
                      maxAge: 300,
                      global: true,
                      // type: 'Bearer'
                  },
                  refreshToken: {
                      property: 'refresh',
                      data: 'refresh',
                      maxAge: 60 * 60 * 24
                  },
                  user: {
                      property: 'data',
                      // autoFetch: true
                  },
                  endpoints: {
                      login: { url: 'api/token/', method: 'post' },
                      refresh: { url: 'api/token/refresh/', method: 'post' },
                      user: { url: 'api/current_user/', method: 'get' },
                      logout: false
                  }
                }
           }
    },
    ...

Here is what I did to make it work:这是我为使其工作所做的工作:

npm install --save @nuxtjs/auth-next

nuxt.config.js nuxt.config.js

    strategies: {
        refresh: {
            scheme: 'refresh',
            token: {
                property: 'access_token',
                maxAge: 1800,
                global: true,
            },
            refreshToken: {
                property: 'refresh_token',
                data: 'refresh_token',
                maxAge: 60 * 60 * 24 * 30,
            },
            user: {
                property: false,
            },
            endpoints: {
                login: {
                    url: `${process.env.OAUTH_URL}/oauth/token`,
                    method: "post",
                    propertyName: false
                },
                user: {
                    url: `${process.env.OAUTH_URL}/api/user`,
                    method: 'get',
                },
                logout: false,
            }
        },
    }

The user property: false flag is important because my user payload has all the user fields directly in the response: user property: false标志很重要,因为我的用户有效负载直接在响应中包含所有用户字段:

{
    id: '',
    email: '',
    name: '',
    role: '',
}

login.vue登录.vue

            await this.$auth.loginWith("refresh", {
                data: {
                    grant_type: "password",
                    client_id: process.env.CLIENT_OAUTH_ID,
                    client_secret: process.env.CLIENT_OAUTH_KEY,
                    scope: "*",
                    username: this.credentials.email,
                    password: this.credentials.password
                }
            });

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

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