版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明,盗版必究。
本文链接:https://blog.csdn.net/weixin_44656298/article/details/134807881
-
实施背景
由于项目中有个需求,想要把geoscene中搭建好的某个应用在别人的项目里面实现嵌入,但是又不想要弹出登录的窗口,所以不得不去研究下这个实现路径。在没有登录时,想要打开geoscene某个应用时就会弹出下面的登录窗口。
-
实现思路
经过对geoscene的研究,发现在登录后,浏览器就会多出一些Cookies信息。所以我的办法就是去抓取这个能在登录成功后给Cookies赋值的这个接口,然后尝试调用这个接口,看下是否可以在调用成功后自动的在浏览器的Cookies里面进行赋值,假设赋值成功后,打开一个geoscene里面的服务或者应用地址,看下是否能正常查看。 -
从抓取的过程中发现,需要用到两个接口,主要的登录接口是signin接口,而authorize接口主要是用来获取oauth_state来为signin接口服务,下面是接口展示:
// arcgis登录
export const signin = async (oauth_state: any) => {
return request({
method: "post",
url: YourPortalAddress + `/portal/sharing/oauth2/signin`,
data: {
oauth_state: oauth_state,
username: 'test',
password: '1234'
},
withCredentials: true,
headers: { 'content-type': 'application/x-www-form-urlencoded' },
})
}
// arcgis权限验证
export const authorize = async () => {
return request({
method: "post",
url: YourPortalAddress + `/portal/sharing/oauth2/authorize`,
data: {
client_id: 'arcgisonline',
response_type: 'token',
state: '{"portalUrl":YourPortalAddress + "/portal"}',
expiration: '20160',
redirect_uri:YourPortalAddress + '/portal/apps/webappviewer3d/index.html?id=1234',
locale: 'zh-cn',
},
withCredentials: true,
headers: { 'content-type': 'application/x-www-form-urlencoded' },
})
}
- 实现步骤
①.首先我们需要调用authorize接口获取到oauth_state参数的值,由于authorize接口返回的值是一个html,所以我们需要一些特殊的过滤手段来获取。authorize接口回调数据看下图
②.下面直接附上我的实现代码(根据自己的实际情况调整过滤步骤)
//登录
const login = async () => {
const getoauth_state = await authorize();
let parser = new DOMParser();
let doc: any = parser.parseFromString(getoauth_state.request.response, 'text/html');
let scriptElement = doc.head.querySelectorAll('script');
if (scriptElement && scriptElement.length && scriptElement.length >= 3) {
let scriptContent = scriptElement[2].innerText;
let match = scriptContent.match(/var\s+oAuthInfo\s*=\s*({[^;]+);/);
if (match) {
var myVariableValue = match[1];
const paramse = JSON.parse(myVariableValue.match(/\{[^}]+\}/)[0])
await signin(paramse.oauth_state);
status.value = true
}
} else {
status.value = true
}
}
③. 最后在调用signin接口成功后,浏览器就会自动赋值上Cookies信息,因为这些这口都有使用cookie进行通信,只要你的浏览器附带上cookies信息后,就可以跳转(window.location.href=‘你的应用或者服务地址’)到任何一个你拥有的geoscene服务或者应用的页面进行查看。