NodeJS實(shí)現(xiàn)單點(diǎn)登錄原理解析
什么是單點(diǎn)登錄
隨著公司業(yè)務(wù)的增多,必然會(huì)產(chǎn)生各個(gè)不同的系統(tǒng),如果每個(gè)系統(tǒng)都需要單獨(dú)登錄的話就會(huì)很不方便。
因此產(chǎn)生了單點(diǎn)登錄這樣的解決方案,單點(diǎn)登錄全稱 Single Sign On,簡(jiǎn)稱SSO,意思是在多個(gè)系統(tǒng)應(yīng)用群中登錄一個(gè)系統(tǒng),便可在其他所有系統(tǒng)中得到授權(quán)而無需再次登錄。
比如小明今天登錄了淘寶,如果沒有登錄,就會(huì)被要求輸入認(rèn)證信息(用戶名密碼等),登錄過后再去訪問天貓的頁面時(shí)就不需要登錄可以直接訪問。
單點(diǎn)登錄原理

SSO 需要有一個(gè)獨(dú)立的認(rèn)證中心,只有獨(dú)立的驗(yàn)證中心能接受用戶的用戶名密碼等安全信息,其他系統(tǒng)不提供登錄入口,只接受認(rèn)證中心的間接授權(quán)。 整個(gè)過程可以簡(jiǎn)單的用上圖描述:
- 當(dāng)用戶登錄訪問應(yīng)用A時(shí),應(yīng)用A發(fā)現(xiàn)用戶未登錄,跳轉(zhuǎn)至SSO認(rèn)證中心,并將自己的地址作為參數(shù)方便回調(diào)
- SSO認(rèn)證中心發(fā)現(xiàn)用戶沒有登錄過,將用戶引導(dǎo)至登錄頁面;用戶填寫用戶名密碼提交登錄申請(qǐng);SSO認(rèn)證中心校驗(yàn)用戶信息,創(chuàng)建用戶雨SSO認(rèn)證中心的會(huì)話(這時(shí)會(huì)把信息保存到cookie中),同時(shí)創(chuàng)建授權(quán)令牌token
- sso認(rèn)證中心帶著令牌跳轉(zhuǎn)到最初的請(qǐng)求地址(應(yīng)用A)
- 應(yīng)用A拿到令牌去SSO認(rèn)證中心認(rèn)證是否有效,如果返回有效注冊(cè)應(yīng)用A
- 應(yīng)用A創(chuàng)建與用戶之間的會(huì)話,展示資源并維持用戶登錄態(tài)
- 當(dāng)用戶訪問應(yīng)用B時(shí),發(fā)現(xiàn)用戶未登錄(SSO認(rèn)證服務(wù)器與應(yīng)用A應(yīng)用B不是同一個(gè)域,不能提供登錄態(tài)),跳轉(zhuǎn)到SSO認(rèn)證中心,并將自己的地址和之前和SSO認(rèn)證中心會(huì)話的cookie信息帶入
- SSO認(rèn)證中心發(fā)現(xiàn)用戶已登錄,跳轉(zhuǎn)回應(yīng)用B地址,并附上令牌token
- 同樣的應(yīng)用B拿到令牌去SSO認(rèn)證中心認(rèn)證是否有效,如果返回有效注冊(cè)應(yīng)用B
- 應(yīng)用B創(chuàng)建與用戶之間的會(huì)話,展示資源并維持用戶登錄態(tài)
NodeJS 演示
三個(gè)不同的服務(wù)
這里我們需要啟動(dòng)三個(gè)服務(wù)來分別模擬 應(yīng)用A,SSO認(rèn)證服務(wù)器和應(yīng)用B

這里端口號(hào) 8383的服務(wù)是SSO認(rèn)證服務(wù)器,其余的 :8686 和 :8787 分別代表應(yīng)用A與應(yīng)用B。
其實(shí)應(yīng)用A與應(yīng)用B的代碼幾乎一樣,如上圖所示我們可以通過穿參的方式來設(shè)置不同的端口及應(yīng)用名。
先來看下效果

首次訪問跳轉(zhuǎn)至登錄頁
應(yīng)用A判斷登錄態(tài),跳轉(zhuǎn)到SSO認(rèn)證服務(wù)器
應(yīng)用A
const Koa=require('koa');
const Router=require('koa-router')
const views=require('koa-views')
const static=require('koa-static')
const path=require('path');
const app=new Koa();
const router=new Router();
const session=require('koa-session')
const koa2Req=require('koa2-request');
//模版引擎相關(guān)配置
app.use(views(path.join(__dirname,'./views')),{
extension:'ejs'
})
app.keys=['key']
const keyMap={
'8686':'koa:sess8686',
'8787':'koa:sess8787'
}
const CONFIG={
key:keyMap[process.env.PORT] || 'koa:sess',
maxAge:1000*60*60*24,
httpOnly:true
}
app.use(session(CONFIG,app))
const system=process.env.SERVER_NAME
router.get("/",async (ctx)=>{
//通過 session來判斷 應(yīng)用A的登錄狀態(tài)
let user=ctx.session.user
if(user){
//...
}
else //1、當(dāng)用戶登錄訪問應(yīng)用A時(shí),應(yīng)用A發(fā)現(xiàn)用戶未登錄(應(yīng)為服務(wù)器沒有保存對(duì)應(yīng)的session)
{
let token=ctx.query.token
//第一次登錄url上也不會(huì)有令牌
if(!token)
{
//1、跳轉(zhuǎn)到SSO認(rèn)證服務(wù)器
ctx.redirect(`http://localhost:8383/login?redirectUrl=${ctx.host+ctx.originalUrl}`)
}
else
{
//...
}
}
})
app.use(router.routes())
const port=process.env.PORT||8888
app.listen(port,()=>{
console.log(`app ${system} running at ${port}`)
})認(rèn)證服務(wù)器判斷登錄態(tài),渲染登錄頁
認(rèn)證服務(wù)器SSO
認(rèn)證服務(wù)器的目錄結(jié)構(gòu)如下 主要處理兩個(gè)功能,一是登錄邏輯,二是之后驗(yàn)證令牌的有效性,分別有路由 login.js 和 check-token.js 處理

Auth/index.js
const Koa=require('koa');
const Router=require('koa-router')
const views=require('koa-views')
const path=require('path');
const app=new Koa();
const router=new Router();
const login=require("./routes/login")
const checkToken=require('./routes/check-token')
const bodyparser=require('koa-bodyparser')
app.use(views(path.join(__dirname,'./views')),{
extension:'ejs'
})
app.use(bodyparser())
//處理登錄相關(guān)的邏輯
router.use('/login',login.routes())
//處理令牌驗(yàn)證的邏輯
router.use('/check_token',checkToken.routes())
app.use(router.routes())
app.listen(8383,()=>{
console.log(`app listen at 8383`)
})剛才我們從應(yīng)用A跳轉(zhuǎn)到 http://localhost:8383/login?redirectUrl=localhost:8686 來看login中的邏輯
Auth/routes/login.js
const service = require("../service");
const router=require("koa-router")()
router.get('/',async (ctx)=>{
const cookies=ctx.cookies;
const token=cookies.get('token');
//從cookie中判斷應(yīng)用A的登錄態(tài)
if(token && service.isTokenVailid(token)){
//。。。如果有登錄過
}else{
//2、SSO認(rèn)證中心發(fā)現(xiàn)用戶沒有登錄過,于是渲染登錄頁面登錄頁面;
await ctx.render('login.ejs',{
extension:'ejs'
})
}
})
//。。。
module.exports=router登錄頁面
Auth/views/login.ejs
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>統(tǒng)一登錄</title>
</head>
<body>
<h1>統(tǒng)一登錄</h1>
<form method="post">
<div>用戶名: <input type="text" name="name"/></div>
<div>密碼 <input type="text" name="password" /></div>
<div><input type="submit" value='登錄'></div>
</form>
</body>
</html>校驗(yàn)用戶信息,創(chuàng)建令牌
Auth/routes/login.js
router.post('/',async (ctx)=>{
//2、用戶填寫用戶名密碼提交登錄申請(qǐng);
const body=ctx.request.body;
const {name,password}=body;
//2、SSO認(rèn)證中心校驗(yàn)用戶信息,
if(name==="admin" && password==="123456"){
//2、創(chuàng)建用戶雨SSO認(rèn)證中心的會(huì)話(這時(shí)會(huì)把信息保存到cookie中),同時(shí)創(chuàng)建授權(quán)令牌token
const token="passport";
await ctx.cookies.set('token',token,{
maxAge:1000*60*60*24*30,
httpOnly:true
})
if(ctx.query.redirectUrl){
//3、sso認(rèn)證中心帶著令牌跳轉(zhuǎn)到最初的請(qǐng)求地址(應(yīng)用A)
ctx.redirect(`${ctx.protocol}://${ctx.query.redirectUrl}?token=${token}`)
//回跳地址是 http://localhost:8686/?token=passport
}else{
ctx.body="<h1>登錄成功!</h1>"
}
}else{
ctx.response.body={
error:1,
msg:'用戶名或密碼錯(cuò)誤'
}
}
})從認(rèn)證服務(wù)器攜帶令牌跳轉(zhuǎn)回應(yīng)用A
令牌校驗(yàn) 返回資源
應(yīng)用A
app.use(views(path.join(__dirname,'./views')),{
extension:'ejs'
})
//...
const system=process.env.SERVER_NAME
router.get("/",async (ctx)=>{
let user=ctx.session.user
if(user){
//...
}
else
//這時(shí)應(yīng)用A依舊沒有登錄態(tài) 但url上有了令牌 http://localhost:8686/?token=passport
{
let token=ctx.query.token
if(!token)
{
//...跳轉(zhuǎn)去SSO登錄頁面
}
else
//跳回應(yīng)用A時(shí)走這里的邏輯
{
//ajax請(qǐng)求 4. 應(yīng)用A拿到令牌去SSO認(rèn)證中心認(rèn)證是否有效,如果返回有效注冊(cè)應(yīng)用A
const url=`://localhost:8383/check_token?token=${token}&t=${new Date().getTime()}`
let data = await koa2Req(ctx.protocol + url);
if(data && data.body){
try {
const body=JSON.parse(data.body)
const {error,userId}=body;
// console.log(error,userId) 0,admin
if(error==0){
if(!userId){
ctx.redirect(`http://localhost:8383/login?redirectUrl=${ctx.host+ctx.originalUrl}`)
return
}
//驗(yàn)證通過后注冊(cè)session,渲染頁面
//5. 應(yīng)用A創(chuàng)建與用戶之間的會(huì)話,展示資源并維持用戶登錄態(tài)
ctx.session.user=userId;
await ctx.render('index.ejs',{
user:userId,
system
})
}else{
ctx.redirect(`http://localhost:8383/login?redirectUrl=${ctx.host+ctx.originalUrl}`)
}
} catch (error) {console.log(error)}
}
}
}
})
app.use(router.routes())
const port=process.env.PORT||8888
app.listen(port,()=>{
console.log(`app ${system} running at ${port}`)
})與之對(duì)應(yīng)的 SSO中處理驗(yàn)證令牌的邏輯
Auth/routes/check-token
const router=require("koa-router")()
const service=require("../service")
router.get('/',async (ctx)=>{
const token=ctx.query.token;
const result={
error:1
}
//當(dāng)token 是 password時(shí)
if(service.isTokenVailid(token)){
result.error=0;
result.userId='admin'
}
ctx.body=result
})
module.exports=routerAuth/service/index.js
module.exports={
isTokenVailid: function(token){
if(token && token==='passport'){
return true
}
return false
}
}至此用戶已經(jīng)能正常訪問應(yīng)用A,SSO服務(wù)器和應(yīng)用A服務(wù)器上都有了用戶登錄過的信息。
訪問應(yīng)用B
帶cookie跳轉(zhuǎn)至SSO認(rèn)證服務(wù)器
應(yīng)用B
//...
router.get("/",async (ctx)=>{
let user=ctx.session.user
if(user){
//...
}else{
let token=ctx.query.token
//...
if(!token)
{
//同樣既沒有session也沒有令牌,跳轉(zhuǎn)到SSO認(rèn)證服務(wù)器
//6、當(dāng)用戶訪問應(yīng)用B時(shí),發(fā)現(xiàn)用戶未登錄(SSO認(rèn)證服務(wù)器與應(yīng)用A應(yīng)用B不是同一個(gè)域,不能提供登錄態(tài)),跳轉(zhuǎn)到SSO認(rèn)證中心,并將自己的地址和之前和SSO認(rèn)證中心會(huì)話的cookie信息帶入
ctx.redirect(`http://localhost:8383/login?redirectUrl=${ctx.host+ctx.originalUrl}`)
}
else
{
//。。。驗(yàn)證令牌的部分
}
}
})
app.use(router.routes())
const port=process.env.PORT||8888
app.listen(port,()=>{
console.log(`app ${system} running at ${port}`)
})從認(rèn)證服務(wù)器攜帶令牌跳轉(zhuǎn)回應(yīng)用B
SSO認(rèn)證服務(wù)器 ,再次登錄時(shí)攜帶了cookie,因此不會(huì)再請(qǐng)求登錄頁面 Auth/routes/login
//...
router.get('/',async (ctx)=>{
const cookies=ctx.cookies;
const token=cookies.get('token');
//7. SSO認(rèn)證中心發(fā)現(xiàn)用戶已登錄,跳轉(zhuǎn)回應(yīng)用B地址,并附上令牌token
if(token && service.isTokenVailid(token)){
const redirectUrl=ctx.query.redirectUrl;
if(redirectUrl){
//帶著令牌跳轉(zhuǎn)回應(yīng)用B
ctx.redirect(`${ctx.protocol}://${redirectUrl}?token=${token}`)
}else{
ctx.body="<h1>登錄成功!</h1>"
}
}else{
//...渲染登錄頁面
}
})
//..令牌校驗(yàn) 返回資源
這里的邏輯和5,6兩步一樣,因?yàn)閠oken容易偽造,所以要檢驗(yàn)真?zhèn)巍?應(yīng)用B
app.use(views(path.join(__dirname,'./views')),{
extension:'ejs'
})
//...
const system=process.env.SERVER_NAME
router.get("/",async (ctx)=>{
let user=ctx.session.user
if(user){
//...
}
else
//這時(shí)應(yīng)用B依舊沒有登錄態(tài) 但url上有了令牌 http://localhost:8787/?token=passport
{
let token=ctx.query.token
if(!token)
{
//...跳轉(zhuǎn)去SSO登錄頁面
}
else
//跳回應(yīng)用B時(shí)走這里的邏輯
{
//ajax請(qǐng)求 8. 同樣的應(yīng)用B拿到令牌去SSO認(rèn)證中心認(rèn)證是否有效,如果返回有效注冊(cè)應(yīng)用B
const url=`://localhost:8383/check_token?token=${token}&t=${new Date().getTime()}`
let data = await koa2Req(ctx.protocol + url);
if(data && data.body){
try {
const body=JSON.parse(data.body)
const {error,userId}=body;
// console.log(error,userId) 0,admin
if(error==0){
if(!userId){
ctx.redirect(`http://localhost:8383/login?redirectUrl=${ctx.host+ctx.originalUrl}`)
return
}
//驗(yàn)證通過后注冊(cè)session,渲染頁面
//9. 應(yīng)用B創(chuàng)建與用戶之間的會(huì)話,展示資源并維持用戶登錄態(tài)
ctx.session.user=userId;
await ctx.render('index.ejs',{
user:userId,
system
})
}else{
ctx.redirect(`http://localhost:8383/login?redirectUrl=${ctx.host+ctx.originalUrl}`)
}
} catch (error) {console.log(error)}
}
}
}
})
app.use(router.routes())
const port=process.env.PORT||8888
app.listen(port,()=>{
console.log(`app ${system} running at ${port}`)
})至此單點(diǎn)登錄的大部分邏輯都已經(jīng)完成,之后再session有效期內(nèi)再訪問頁面,就不需要再登錄,直接返回資源
router.get("/",async (ctx)=>{
//如果session中有用戶信息,說明已經(jīng)登錄過,直接返回請(qǐng)求資源
let user=ctx.session.user
if(user){
await ctx.render('index.ejs',{
user,
system
})
}
//...
})到此這篇關(guān)于NodeJS實(shí)現(xiàn)單點(diǎn)登錄的文章就介紹到這了,更多相關(guān)nodejs單點(diǎn)登錄內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
在?node?中使用?koa-multer?庫(kù)上傳文件的方式詳解
本文主要介紹了上傳單個(gè)文件、多個(gè)文件,文件數(shù)量大小限制、限制文件上傳類型和對(duì)上傳的圖片進(jìn)行不同大小的裁剪,對(duì)node使用?koa-multer?庫(kù)上傳文件相關(guān)知識(shí)感興趣的朋友一起看看吧2024-01-01
node.js中的http.createServer方法使用說明
這篇文章主要介紹了node.js中的http.createServer方法使用說明,本文介紹了http.createServer的方法說明、語法、接收參數(shù)、使用實(shí)例和實(shí)現(xiàn)源碼,需要的朋友可以參考下2014-12-12
Node.js中Koa2在控制臺(tái)輸出請(qǐng)求日志的方法示例
這篇文章主要給大家介紹了關(guān)于Node.js中Koa2在控制臺(tái)輸出請(qǐng)求日志的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Node.js具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-05-05
Node.js中的http請(qǐng)求客戶端示例(request client)
本篇文章主要介紹了Node.js中的http請(qǐng)求客戶端示例(request client),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05
Nodejs下用submit提交表單提示cannot post錯(cuò)誤的解決方法
這篇文章主要介紹了Nodejs下用submit提交表單提示cannot post錯(cuò)誤的解決方法,非常不錯(cuò),具有參考借鑒價(jià)值,感興趣的朋友一起看看吧2016-11-11
nodejs實(shí)現(xiàn)的http、https 請(qǐng)求封裝操作示例
這篇文章主要介紹了nodejs實(shí)現(xiàn)的http、https 請(qǐng)求封裝操作,結(jié)合實(shí)例形式分析了node.js針對(duì)http、https 請(qǐng)求的封裝與使用相關(guān)操作技巧,需要的朋友可以參考下2020-02-02

