最简洁的就是用 Authing,超简单就可以实现:
``` javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Authing 单点登录实现示例</title>
<style>
body {
font-family: Avenir,Helvetica,Arial,sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
a {
color: #42b983;
cursor: pointer;
text-decoration: underline;
}
</style>
</head>
<body>
<div style="margin-bottom:22px">
<img data-v-1129b33e="" alt="Vue logo" height="200" src="
https://cdn.authing.cn/authing-logo@2.png">
<h1>使用 Authing 五分钟实现单点登录</h1>
<h2>当前状态:<span id="status">检测中</span></h2>
<h3 id="track-session-tip" style="display:none">以下是你的 session 信息:</h3>
<pre style="text-align: left;" id="session"></pre>
</div>
<a id="btn-login">登录</a>
<a id="btn-logout">退出</a>
<p>
<a href="
https://authing.cn/login" target="_blank">使用 Authing</a>
<a href="
https://github.com/Authing/web-sso-sample" target="_blank" style="margin-left:11px">本示例代码</a>
<a href="
https://docs.authing.cn/authing/quickstart/implement-sso-with-authing" target="_blank" style="margin-left:11px">开发文档</a>
</p>
<p>
<a href="
https://github.com/Authing/oidc-window">在单窗口中打开登录页面的代码示例</a>
</p>
<script src="
https://cdn.jsdelivr.net/npm/@authing/sso/dist/AuthingSSO.umd.min.js"></script>
<script src="
https://cdn.authing.cn/js-beautify/1.7.5/beautify.min.js"></script>
<script>
const authing = new AuthingSSO({
appId: "5d70d0e991fdd597019df70d", // OIDC 应用的 ID
appType: "oidc", // SSO 类型为 OIDC 类型
appDomain: "
sample-sso.authing.cn"
});
const callTrackSession = async function() {
const res = await authing.trackSession();
if (!res.session) {
status.innerHTML = '未登录';
logout.setAttribute('style', 'display:none');
}else {
status.innerHTML = `${res.userInfo.username || res.userInfo.email || res.userInfo.nickname} 你好,你已处于登录状态`;
login.setAttribute('style', 'display:none');
sessionTip.setAttribute('style', 'display: block');
sessionPre.innerHTML = js_beautify(JSON.stringify(res));
}
};
// 检查登录状态
callTrackSession()
const login = document.getElementById('btn-login');
const logout = document.getElementById('btn-logout');
const status = document.getElementById('status');
const sessionPre = document.getElementById('session');
const sessionTip = document.getElementById('track-session-tip');
login.onclick = function() {
authing.login();
};
logout.onclick = async function() {
let res = await authing.logout();
alert(JSON.stringify(res));
location.reload();
};
</script>
</body>
</html>
```
线上体验:
sample.authing.cnhttps://github.com/Authing/web-sso-sample/blob/master/index.html