在auth0回调上获取哈希值

时间:2019-04-02 15:21:34

标签: vue.js oauth routes vue-router

我正在使用Vue路由器为SPA写auth。我无权访问服务器,因此必须使用哈希路由。问题是我无法将哈希值从返回的路由对象中拉出。我的router.js是:

import Vue from "vue";
import Router from "vue-router";
import Home from "./views/Home.vue";
import Callback from "./views/Callback.vue";
import NotFound from "./views/NotFound.vue";

Vue.use(Router);

const router = new Router({
  mode: "hash",
  routes: [
    {
      path: "/",
      name: "home",
      component: Home
    },
    {
      path: "/callback",
      name: "callback",
      component: Callback
    },
    {
      path: "*",
      name: "NotFound",
      component: NotFound
    }
  ]
});

// very basic "setup" of a global guard
// here we will check if authorization is in localStorage.
// will go thru checks calling appropriate route.
router.beforeEach((to, from, next) => {
  // check if "to"-hash is "callback" and allow access
  if (to.hash == "callback") {
    console.log("callback route invoked");
    console.log("The path is: " + to.path);
    console.log("The hash is: " + to.hash);
    next();
  } else if (router.app.$auth.isAuthenticated()) {
    // if authenticated allow access
    console.log("Authenticated route invoked");
    next();
  } else {
    // trigger auth0 login if not been authenticated before.
    // router.app refers to the root Vue instance the router was injected into
    console.log("fallback route invoked");
    console.log("Hash is: " + to.hash); // outputs "Hash is: "
    console.log("The path is: " + to.path); // outputs access_token=eyJ0eXAiOi...
    router.app.$auth.login();
  }
});

export default router;

和我的auth0.webAuth配置对象是:

let webAuth = new auth0.WebAuth({
  domain: authConfig.domain,
  redirectUri: `${window.location.origin}/#/callback`,
  clientID: authConfig.clientId,
  audience: "https://" + authConfig.domain + "/api/v2/",
  responseType: "token id_token",
  scope: "openid profile"
});

因此,由于我无法获取回调哈希,因此永远不会调用回调路由,而我们只是无限次调用后备路由。在浏览器的开发工具中查看,返回的回调地址为“ /”,并且to.hash值为null。感谢您的任何帮助。

0 个答案:

没有答案