How to implement a single sign-on system? 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 from two or more business systems to form a new system. This achieves the effect of no need to log in to any business system after logging in once.
1. Basic knowledge
1.1 Same origin policy
Source = protocol Domain name port
Take http://www.a.com as an example:
- https://www.a.com ❌(different protocols)
- http://www.b.com ❌(Domain name is different)
- http://www.a.com:3000 ❌(Port is different)
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. [Related tutorial recommendations: nodejs video tutorial]
1.2 Session mechanism
Because the http protocol isnone Status protocol (After the data exchange between the client and the 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.
Commonly used session tracking is cookie and session. To simply understand them, they are data structures that can store keys and values. The difference is that cookies are stored on the client side and sessions are stored on the server side.
2. Single sign-on
1. Same parent domain SSO
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' }})
2. Cross-domain SSO
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.
2.1 Writing cookies across domains
2.1.1 Using the tag to write cookies across domains (jsonp)
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 error
his 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 error
this 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 attributesThe browser does not write the cookie and reports an error
server 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.
2.1.2 The p3p protocol header implements IE browser cross-domain
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'})
2.1.3 url参数实现跨域信息传递
访问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.2 跨域读cookie
2.2.1 利用标签跨域读cookie(jsonp)
之前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.
3. nodejs实现单点登录系统实战
效果如图所示:
第一次访问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 A brief analysis of how node implements a single sign-on system. For more information, please follow other related articles on the PHP Chinese website!

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.