0.0.3 • Published 2 years ago

@oneauth/sdk-vue v0.0.3

Weekly downloads
-
License
-
Repository
-
Last release
2 years ago

@oneauth/sdk-vue

需搭配@oneauth/sdk-core 使用

安装

除了本 sdk,也需要安装@oneauth/sdk-core

npm i --save @oneauth/sdk-core @oneauth/sdk-vue

实例化@oneauth/sdk-core

在使用@oneauth/sdk-vue 之前,需要初始化@oneauth/sdk-core, 查看教程

开始使用@oneauth/sdk-vue

@oneauth/sdk-vue 提供了一个登录重定向的页面,和一个用于鉴权的导航守卫

你需要把登录重定向页面配置到路由当中。

并在需要鉴权的路由的 meta 上添加 auth 参数

  1. 实例化@oneauth/sdk-core 和@oneauth/sdk-vue
import App from "./App.vue";
import router from "./router";

import OneAuth from "oneauth-sdk-core";
import OneAuthVue from "oneauth-sdk-vue";
const oneAuth = new OneAuth({
  issuer: `kang.oneauth.cn/oauth/v1`,
  clientId: `2YXXZ78611K0c8906MX6RJ8c0s84VcQB`,
  redirectUri: `http://localhost:8080/callback`,
  scopes: ["openid", "profile", "email"],
});
  1. 注入$oneauth

    把 @oneauth/sdk-core 实例注入到 Vue 的原型上

Vue.use(OneAuthVue, {
  oneAuth,
});
  1. 添加登录按钮

在页面中添加一个按钮,并对其调用

this.$oneauth.login();
<template>
  <button @click="login">login</button>
</template>
<script lang="ts">
  import { Component, Vue } from "vue-property-decorator";
  @Component({
    components: {},
  })
  export default class App extends Vue {
    private login() {
      this.$oneAuth.login();
    }
  }
</script>
  1. 添加登录重定向页面

从@oneauth/sdk-vue 得到登录重定向页面,并配置到路由中。

路由的路径需要与@oneauth/sdk-core 的实例化参数redirectUri一致。

import { LoginCallback } from "@oneauth/sdk-vue";

const routes: Array<RouteConfig> = [
  {
    path: "/callback",
    component: LoginCallback,
  },
];
  1. 添加路由鉴权和导航守卫

从@oneauth/sdk-vue 中获取导航守卫navigationGuard,并配置到路由中。

在需要鉴权的路由的 meta 中配置 auth 属性

这样,在打开该路由时都会检查是否登录了。

如果没有登录则会跳转到登录页。

登录完成后会跳转回来。

import { LoginCallback, navigationGuard } from "@oneauth/sdk-vue";

const routes: Array<RouteConfig> = [
  {
    path: "/callback",
    component: LoginCallback,
  },
  {
    path: "/about",
    name: "About",
    meta: {
      auth: true,
    },
    component: () => import("../views/About.vue"),
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

router.beforeEach(navigationGuard);

export default router;