实时

您的位置:首页>产品 >

今日最新!使用 IdentityServer 保护 Vue 前端

前情提要

《使用 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保护Web应用(AntDPro前端+SpringBoot后端)》中记录了使用IdentitySer

2022-12-20 18:27:11

万泽股份(000534)12月20日在投资者关系平台上答复了投资者关心的问题。投资者:您好董秘,请问贵公司近期的业务是否有转型的导向?或者近期有

2022-12-20 11:33:48

网贷逾期一般会上征信,有些借贷机构在用户逾期后一天后就会上报给征信机构,而有些借贷机构则是会在几天后上报给征信机构,因为有些借贷机构可

2022-12-20 03:43:34

补充协议里要约定好过户时间和过户条件,如果急着拿到房产证,可以在补充协议中约定产证的具体办理日期,并注明赔偿责任。比如,超过一个月不

2022-12-19 17:09:43

(原标题:我国实现生物航煤绿色国际货运首飞)证券时报e公司讯,据中国石化消息,近日,中国大陆首个使用可持续航空燃料的商业货运航班完成首

2022-12-19 11:59:48

网贷逾期一般会上征信,有些借贷机构在用户逾期后一天后就会上报给征信机构,而有些借贷机构则是会在几天后上报给征信机构,因为有些借贷机构可

2022-12-19 05:29:59

达刚控股集团股份有限公司      关于本次重大资产出售前 12 个月内购买             出售相关资产情况的说明  达刚控

2022-12-18 17:00:09

参考消息网12月17日报道据法新社12月16日报道,俄罗斯大使馆表示,一名俄罗斯驻中非共和国代表16日在打开一个包裹炸弹后身受重(@参考消息)

2022-12-17 18:25:31

在法律规定的国家考试中,组织作弊的,处三年以下有期徒刑或者拘役,并处或者单处罚金;情节严重的,处三年以上七年以下有期徒刑,并处罚金。

2022-12-17 06:40:16

北京德恒(昆明)律师事务所    关于云南能源投资股份有限公司                 法律意见             北

2022-12-16 18:50:03

小尺寸的小米13在续航上给首批用户留下深刻影响,不少用户称自己完整使用一天完全没问题,而正常使用之前的手机需要一天两充或者三充。小米13

2022-12-16 11:27:46

《刑法》第二百九十二条关于聚众斗殴怎么判的规定:聚众斗殴的,对首要分子和其他积极参加的,处三年以下有期徒刑、拘役或者管制;有下列情形

2022-12-16 02:04:14

股票代码:002759     股票简称:天际股份        公告编号:2022-106              天际新能源科技股份有限公司

2022-12-15 16:51:31

1)极重度智能损伤;2)面部重度毁容,同时伴有表B2中二级伤残之一者;3)双眼无光感或仅有光感但光定位不准者;4)四肢瘫肌力3级或三肢瘫肌力

2022-12-15 11:08:51

12月14日,汇丰晋信大盘股票A最新单位净值为3 9407元,累计净值为4 0007元,较前一交易日下跌0 31%。历史数据显示该基金近1个月上涨1 02%,近3

2022-12-15 00:54:48

金秋时节,硕果累累。走进西峡县回车镇东沟村镇千亩猕猴桃产业基地,一大片色泽苍翠、枝繁叶茂的果树排列整齐,一个个椭圆形、黄褐色、绿褐色

2022-12-14 15:42:11

乐享集团(06988 HK)涨超14%。截至发稿,涨10 18%,报1 84港元,成交额1933 18万港元。

2022-12-14 09:34:16

证券之星讯,根据11月22日市场公开信息、上市公司公告及交易所披露数据整理,新化股份(603867)(603867)最新董监高及相关人员股份变动情况:2022年

2022-12-13 20:05:00

12月13日,旅游板块走强,旅游ETF(562510 SH)涨2 80%,旅游ETF(159766 SZ)涨2 44%。据开源证券统计,12月初以来全国民航执飞

2022-12-13 12:20:47

汪小菲和大S在网上你来我往,真是让大家看了好大一出热闹。起初两人相爱相恋,一切都显得那么美好,谁能够想到今日的他们居然会沦落到如今这番

2022-12-13 03:36:31