使用 IdentityServer 保护 Vue 前端|世界观速讯

2022-12-21 11:01:13 来源: 分享到:
前情提要

《使用 IdentityServer 保护 Web 应用(AntD Pro 前端 + SpringBoot 后端)》中记录了使用 IdentityServer 保护前后端的过程,其中的前端工程是以 UMI Js 为例。今天,再来记录一下使用 IdentityServer 保护 Vue 前端的过程,和 UMI Js 项目使用 umi plugin 的方式不同,本文没有使用 Vue 相关的插件,而是直接使用了 oidc-client js。

另外,我对 Vue 这个框架非常不熟,在 vue-router 这里稍微卡住了一段时间,后来瞎试居然又成功了。针对这个问题,我还去 StackOverflow 上问了,但并没有收到有效的回复:https://stackoverflow.com/questions/74769607/how-to-access-vues-methods-from-navigation-guard

准备工作

首先,需要在 IdentityServer 服务器端注册该 Vue 前端应用,仍然以代码写死这个客户端为例:


(相关资料图)

new Client{ClientId = "vue-client",ClientSecrets = { new Secret("vue-client".Sha256()) },ClientName = "vue client",AllowedGrantTypes = GrantTypes.Implicit,AllowAccessTokensViaBrowser = true,RequireClientSecret = false,RequirePkce = true,RedirectUris ={"http://localhost:8080/callback","http://localhost:8080/static/silent-renew.html",},AllowedCorsOrigins = { "http://localhost:8080" },AllowedScopes = { "openid", "profile", "email" },AllowOfflineAccess = true,AccessTokenLifetime = 90,AbsoluteRefreshTokenLifetime = 0,RefreshTokenUsage = TokenUsage.OneTimeOnly,RefreshTokenExpiration = TokenExpiration.Sliding,UpdateAccessTokenClaimsOnRefresh = true,RequireConsent = false,};

在 Vue 工程里安装 oidc-client

yarn add oidc-client

在 Vue 里配置 IdentityServer 服务器信息

在项目里添加一个 src/security/security.js文件:

import Oidc from "oidc-client"function getIdPUrl() {return "https://id6.azurewebsites.net";}Oidc.Log.logger = console;Oidc.Log.level = Oidc.Log.DEBUG;const mgr = new Oidc.UserManager({authority: getIdPUrl(),client_id: "vue-client",redirect_uri: window.location.origin + "/callback",response_type: "id_token token",scope: "openid profile email",post_logout_redirect_uri: window.location.origin + "/logout",userStore: new Oidc.WebStorageStateStore({store: window.localStorage}),automaticSilentRenew: true,silent_redirect_uri: window.location.origin + "/silent-renew.html",accessTokenExpiringNotificationTime: 10,})export default mgr

在 main.js 里注入登录相关的数据和方法数据

不借助任何状态管理包,直接将相关的数据添加到 Vue 的 app 对象上:

import mgr from "@/security/security";const globalData = {isAuthenticated: false,user: "",mgr: mgr}

方法

const globalMethods = {async authenticate(returnPath) {console.log("authenticate")const user = await this.$root.getUser();if (user) {this.isAuthenticated = true;this.user = user} else {await this.$root.signIn(returnPath)}},async getUser() {try {return await this.mgr.getUser();} catch (err) {console.error(err);}},signIn(returnPath) {returnPath ? this.mgr.signinRedirect({state: returnPath}) : this.mgr.signinRedirect();}}

修改 Vue 的实例化代码

new Vue({router,data: globalData,methods: globalMethods,render: h => h(App),}).$mount("#app")

修改 router

在 src/router/index.js中,给需要登录的路由添加 meta 字段:

Vue.use(VueRouter)const router = new VueRouter({{path: "/private",name: "private page",component: resolve => require(["@/pages/private.vue"], resolve),meta: {requiresAuth: true}}});export default router

接着,正如在配置中体现出来的,需要一个回调页面来接收登录后的授权信息,这可以通过添加一个 src/views/CallbackPage.vue文件来实现:

<script>export default {async created() {try {const result = await this.$root.mgr.signinRedirectCallback();const returnUrl = result.state ?? "/";await this.$router.push({path: returnUrl})}catch(e){await this.$router.push({name: "Unauthorized"})}}}</script>

然后,需要在路由里配置好这个回调页面:

import CallbackPage from "@/views/CallbackPage.vue";Vue.use(VueRouter)const router = new VueRouter({routes: {path: "/private",name: "private page",component: resolve => require(["@/pages/private.vue"], resolve),meta: {requiresAuth: true}},{path: "/callback",name: "callback",component: CallbackPage}});export default router

同时,在这个 router 里添加一个所谓的“全局前置守卫”(https://router.vuejs.org/zh/guide/advanced/navigation-guards.html#%E5%85%A8%E5%B1%80%E5%89%8D%E7%BD%AE%E5%AE%88%E5%8D%AB),注意就是这里,我碰到了问题,并且在 StackOverflow 上提了这个问题。在需要调用前面定义的认证方法时,不能使用 router.app.authenticate,而要使用 router.apps[1].authenticate,这是我通过 inspect router发现的:

...router.beforeEach(async function (to, from, next) {let app = router.app.$data || {isAuthenticated: false}if(app.isAuthenticated) {next()} else if (to.matched.some(record => record.meta.requiresAuth)) {router.apps[1].authenticate(to.path).then(()=>{next()})}else {next()}})export default router

到了这一步,应用就可以跑起来了,在访问 /private 时,浏览器会跳转到 IdentityServer 服务器的登录页面,在登录完成后再跳转回来。

添加 silent-renew.html

注意 security.js,我们启用了 automaticSilentRenew,并且配置了 silent_redirect_uri的路径为 silent-renew.html。它是一个独立的引用了 oidc-client js 的 html 文件,不依赖 Vue,这样方便移植到任何前端项目。

oidc-client.min.js

首先,将我们安装好的 oidc-client 包下的 node_modules/oidc-client/dist/oidc-client.min.js文件,复制粘贴到 public/static目录下。

然后,在这个目录下添加 public/static/silent-renew.html文件。

Silent Renew Token<script src="oidc-client.min.js"></script><script>console.log("renewing tokens");new Oidc.UserManager({userStore: new Oidc.WebStorageStateStore({ store: window.localStorage })}).signinSilentCallback();</script>

给 API 请求添加认证头

最后,给 API 请求添加上认证头。前提是,后端接口也使用同样的 IdentityServer 来保护(如果是 SpringBoot 项目,可以参考《[使用 IdentityServer 保护 Web 应用(AntD Pro 前端 + SpringBoot 后端) - Jeff Tian的文章 - 知乎](https://zhuanlan.zhihu.com/p/533197284) 》);否则,如果 API 是公开的,就不需要这一步了。

对于使用 axios 的 API 客户端,可以利用其 request interceptors,来统一添加这个认证头,比如:

import router from "../router"import Vue from "vue";const v = new Vue({router})const service = axios.create({// 公共接口--这里注意后面会讲baseURL: process.env.BASE_API,// 超时时间 单位是ms,这里设置了3s的超时时间timeout: 20 * 1000});service.interceptors.request.use(config => {const user = v.$root.user;if(user) {const authToken = user.access_token;if(authToken){config.headers.Authorization = `Bearer ${authToken}`;}}return config;}, Promise.reject)export default service

标签:

使用 IdentityServer 保护 Vue 前端|世界观速讯

来源: 2022-12-21 11:01:13

H5开屏从龟速到闪电,企微是如何做到的 世界视点

来源: 2022-12-21 03:11:50

环球动态:国家药监局:布洛芬、对乙酰氨基酚等药品原料产能充足

来源: 2022-12-20 16:13:02

这家游戏公司转型直播带货,毛利率98%!

来源: 2022-12-20 10:39:35

环球速讯:明日教育聘任李双双为公司财务负责人2022上半年公司净利197.66万

来源: 2022-12-19 21:54:36

沃顿科技董秘回复:RO膜孔径远小于新型冠状病毒,可有效截留水中的病毒

来源: 2022-12-19 15:50:46

国金证券:维持信达生物(01801.HK)“买入”评级 后续股价催化剂密集_消息

来源: 2022-12-19 09:49:15

许昌市魏都区委常委、政法委书记常江辉督导社区疫情防控工作

来源: 2022-12-19 00:13:39

45+准星79%!追平天勾 KD:睡醒就知道自己会爆发

来源: 2022-12-18 11:29:40

药品保供进行时!海淀市场监管执法人员变身物流配送

来源: 2022-12-17 13:52:23

位于欧洲的荷兰队 为什么有那么多的黑人球员?

来源: 2022-12-16 22:40:45

谷歌公司否认操纵香港地区的国歌搜索结果,外交部回应

来源: 2022-12-16 15:36:50

中科电气:12月15日获融资买入2870.17万元,占当日流入资金比例21.38%

来源: 2022-12-16 09:17:46

舆情追踪|益阳市大通湖区千山红镇新一佳服装店新增严重违法信息

来源: 2022-12-15 20:45:54

合富中国(603122)12月15日主力资金净买入1401.90万元

来源: 2022-12-15 15:03:21

美称可控核聚变实现历史性突破 专家:离商业化使用还很遥远|每日速看

来源: 2022-12-15 09:38:08

华贸物流(603128.SH):拟以3400万元收购华贸铁运合计50%股份

来源: 2022-12-14 19:41:37

定期会商 破解难题 服务实体 精彩看点

来源: 2022-12-14 14:55:41

赛腾股份(603283)12月13日主力资金净卖出1120.76万元 天天短讯

来源: 2022-12-14 07:40:21

《2022中国城市新能源汽车发展指数》正式发布-热点

来源: 2022-12-13 16:45:38

聚焦:东旭蓝天:12月12日获融资买入341.63万元

来源: 2022-12-13 10:44:18

“背书包 上学校” 第一步这样迈更从容

来源: 2022-12-12 14:54:52

经济观察:中国旅游业多项数据显著回升

来源: 2022-12-11 09:08:04

鞍重股份(002667)12月8日主力资金净卖出7360.84万元-播资讯

来源: 2022-12-09 08:50:58

德新科技(603032)12月7日主力资金净卖出1040.10万元 全球观热点

来源: 2022-12-08 07:36:21

天天热点评!股票行情快报:中新集团(601512)12月6日主力资金净买入79.37万元

来源: 2022-12-06 19:38:33

去年美国注册电动汽车数量翻番 特斯拉牢牢占据市场主导地位

来源:网易科技 2022-07-18 19:22:14

安心消费呼唤监管亮出科技之剑

来源:工人日报 2022-03-18 13:57:54

陕西榆林:念好乡村振兴“小康经”

来源:工人日报 2022-03-18 13:57:08

2月份70个大中城市商品住宅销售价格环比上涨

来源:工人日报 2022-03-18 13:56:01

Copyright   2015-2022 南方知识产权网 版权所有  备案号:粤ICP备18023326号-21   联系邮箱:855 729 8@qq.com