环球快看:使用 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>Sign-in in progress... 正在登录中……
然后,需要在路由里配置好这个回调页面:
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文件。
给 API 请求添加认证头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 请求添加上认证头。前提是,后端接口也使用同样的 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 前端
-
全球热消息:海南省沉香工程技术研究中心优良种苗培育基地揭牌
-
【天天新要闻】体育营销Top10|王鹤棣代言特步 常规赛MVP奖杯命名乔丹杯
-
7个月亏逾20%,大幅跑输基准!华安基金套牢投资人-热点在线
-
天天精选!太康县发改委优化营商环境提升招投标监管水平
-
报道:“西北帮”演员有多厉害,打下娱乐圈半壁江山,个个都是实力派
-
天天微资讯!英媒:锂离子电池价格十多年来首涨
-
天天亮点!蛤蜊干怎么泡发 蛤蜊干如何泡发
-
当前快播:海兰信:UDC市场空间巨大,后续订单陆续落地
-
涨停雷达:房地产个股异动 中交地产触及涨停
-
友联租赁(01563.HK)与Bright Enterprise订立融资租赁协议:滚动
-
打印的遗嘱有没有法律效力?
-
信用社养猪贷款利息多少(贷款利率现在多少)
-
世界短讯!海容冷链: 关于2021年股票期权与限制性股票激励计划预留授予限制性股票第一个限售期解除限售暨上市的公告
-
庆丰收 迎盛会 树品牌 谋发展 孟津区小浪底2022年农民丰收节开幕
-
广州数个发热门诊就诊量上升但未达到以往高峰 医生呼吁:将门诊资源留给更有需要的人:每日简讯
-
睿智医药(300149):独立董事提名人声明(杨凌) 世界看热讯
-
宣泰医药等6只科创板股融资余额增幅超20%
-
四川长虹: 四川长虹关于召开2022年第三次临时股东大会的通知
-
聚焦联通人的平凡之美|不负韶华扎根高原谱写服务乐章
记青海联通玉树治多县营业厅巾帼团体:观速讯 -
环球视讯!南岭民爆: 湖南南岭民用爆破器材股份有限公司发行股份购买资产并募集配套资金暨关联交易申请文件反馈意见的回复
-
北方铜业董秘回复:目前北铜新材铜箔车间轧机正在带料试车,已轧制出18微米铜箔,铜箔轧机预计12月底完成试车
-
IP版权争夺再起硝烟:价值与纠纷齐飞,内容开发受掣肘 全球观焦点
-
盛新锂能: 盛新锂能集团股份有限公司非公开发行A股股票发行情况报告书
-
陕西太白一金矿巷道涌入泥石流事故致4人死亡
-
福建莆田集中医学观察人员“清零”
-
14天内有二连浩特市旅居史来(返)海口人员需凭核酸检测阴
-
卧冰拍摄珍稀野生动物获赞千万:60岁斜杠大爷学摄影出名了
-
从京东副总裁到渐冻症患者:人生中场 他开始生命的抗争
-
强冷空气影响中东部地区 局地降温可达14℃以上
-
名校硕士开摩的,积极人生何谈“浪费”
-
大风+寒潮!北京双预警生效中 北风劲吹需防风保暖
-
如果人间真有花花世界,一定是在这儿……
-
30分钟190元 “一日男友”游走在灰色地带
-
“我们的太空家园一定会越建越好!”