What is a single sign-on system? How to implement it using nodejs? The following article will introduce to you how to use node to implement a single sign-on system. I hope it will be helpful to you!
Single Sign On SSO (Single Sign On) is to separate the login functions in two or more business systems to form a new A system that achieves the effect of no need to log in to any business system after logging in once.
Source = protocol Domain name port
Take http://www.a.com as an example:
The same origin policy is browsing The behavior of the server, which ensures security by ensuring that resources under the application can only be accessed by this application.
Since the http protocol is a stateless protocol(the data exchange between client and server is completed, The connection will be closed and the connection will be re-established next time the request is made), but when we need to do functions such as remembering passwords, it is obvious that the session needs to be recorded. [Related tutorial recommendations: nodejs video tutorial]
Commonly used session tracking is cookie and session. A simple understanding of them is a data structure that can store key and value. The difference is that the cookie is stored in the client On the server side, the session is saved on the server side.
Same parent domain , such as www.app1.aaa.com
, www.app2.aaa.com
These two servers are the parent domain name of .aaa.com.
By default, cookies between pages on the two servers are not accessible to each other.
But we can set the domain attribute of the cookie to a common parent domain name so that the cookies between the pages on the two servers can be accessed from each other.
router.get('/createCookie', async (ctx, next) => { ctx.cookies.set('username', '123', { maxAge: 60 * 60 * 1000, httpOnly: false, path: '/', domain:'.a.com' //设置domain为共通的父域名 }); ctx.body = "create cookie ok"})router.get('/getCookie', async (ctx, next) => { let username=ctx.cookies.get('username') if (username){ ctx.body=username }else{ ctx.body='no cookie' }})
When our domain name is www.a .com
,www.b.com
, no matter how you set the domain, it will be useless.
Then we have to find a wayWrite the identity credentials (token) into the cookies of all domains.
Sending a network request directly to https://www.c.com:3000/sso in http://www.a.com/index.js will not allow cross-domain cookies to be written.
<script> $.ajax({ url: 'https://www.c.com:3000/sso?key=username&value=123', method: 'get', }) </script>
But we can initiate cross-domain requests through the <script></script> tag and write cookies
<script></script>
or use jquery jsonp to initiate cross-domain requests and write cookies. This The principle of this method can also be implemented across domains through the tag.
$.ajax({ url: 'https://www.c.com:3000/sso?key=username&value=123', method: 'get', dataType:'jsonp' })
In this way, through the tag, the cross-domain cookie with the domain of www.c.com is written to www.a.com.
Backend
const options = { key: fs.readFileSync(path.join(__dirname, './https/privatekey.pem')), cert: fs.readFileSync(path.join(__dirname, './https/certificate.pem')), secureOptions: 'TLSv1_2_method' //force TLS version 1.2}var server = https.createServer(options,app.callback()); //只能使用https协议写cookierouter.get('/sso', async (ctx, next) => { let { key, value } = ctx.request.query ctx.cookies.set(key, value, { maxAge: 60 * 60 * 1000, //有效时间,单位毫秒 httpOnly: false, //表示 cookie 是否仅通过 HTTP(S) 发送,, 且不提供给客户端 JavaScript (默认为 true). path: '/', sameSite: 'none', //限制第三方 Cookie secure: true //cookie是否仅通过 HTTPS 发送 }); ctx.body = 'create Cookie ok'})
Note:
The browser did not write the cookie and reported an errorhis set-cookie was blocked due to http-only
http-only: Indicates whether the cookie is only sent through HTTP(S), and is not provided to client JavaScript (default is true).
So set httpOnly to false.
The browser did not write the cookie and reported an errorthis set-cookie was blocked due to user preference
This is really a pitfall, because I opened the browser in incognito mode. However, the Chrome browser disables third-party cookies in incognito mode by default. Just change it to allow all cookies.
The browser does not write cookies and reports an error this set cookie was blocked because it has the SameSite attribute but Secure not set
Need to set the sameSite and secure attributes
The browser does not write the cookie and reports an errorserver error Error: Cannot send secure cookie over unencrypted connection
I think this is a limitation of the koa framework for writing cookies. It can only support https writing cookies..., so I changed www.c.com to an https server.
The jsonp method mentioned above runs perfectly in the chrome browser. However, the IE browser is more strict about cookies and cannot write cookies using the above method. The solution is to add the p3p response header.
router.get('/sso', async (ctx, next) => { let { key, value } = ctx.request.query ctx.cookies.set(key, value, { maxAge: 60 * 60 * 1000, //有效时间,单位毫秒 httpOnly: false, path: '/', sameSite: 'none', secure: true }); ctx.set("P3P", "CP='CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR'") //p3p响应头 ctx.body = 'create Cookie ok'})
Visit http://www.c.com:3000/createToken?from=http:// www.a.com/createCookie
www.c.com上生成token后将url重写,带上token,重定向到www.a.com
router.get('/createToken', async (ctx, next) => { let { from } = ctx.request.query let token = "123"; ctx.response.redirect(`${from}?token=${token}`)})
www.a.com上从url上获取token,存入cookie
router.get('/createCookie', async (ctx, next) => { let { token } = ctx.request.query ctx.cookies.set('token', token, { maxAge: 60 * 60 * 1000, //有效时间,单位毫秒 httpOnly: false, path: '/', }); ctx.body = 'set cookie ok'})
这样就实现了跨域信息的传递.与上面的方式不同,这种方法只是单纯的http请求,适用于所有浏览器,但是缺点也很明显,每次只能分享给一个服务器。
之前2.1.1利用标签在www.a.com中写入了www.c.com的cookie(username,123),现在想要www.a.com请求的时候携带上www.c.com的cookie,也就是说要跨域读cookie.
其实也是同样的方法,在www.a.com上利用跨域访问访问www.c.com,会自动的带上domain为www.c.com的cookie。www.a.com/index.js
<script></script>
www.c.com
router.get('/readCookie', async (ctx, next) => { let username = ctx.cookies.get('username') console.log('cookie', username)})
可以看到读取到了存储在www.a.com里面domain为www.c.com的cookie.
效果如图所示:
第一次访问www.a.com首页
跳转到www.c.com:3000登录页面,登录成功后跳转www.a.com首页
再次访问www.a.com首页,无需登录直接跳转
访问www.b.com首页,无需登录直接跳转
源码: https://github.com/wantao666/sso-nodejs
详细设计:
更多node相关知识,请访问:nodejs 教程!
The above is the detailed content of What is a single sign-on system? How to implement it using nodejs?. For more information, please follow other related articles on the PHP Chinese website!