search
HomeWeb Front-endJS TutorialWhat is a single sign-on system? How to implement it using nodejs?

What is a single sign-on system? How to implement it using nodejs?

Feb 24, 2023 pm 07:33 PM
nodejsnodeSingle sign-on system

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!

What is a single sign-on system? How to implement it using nodejs?

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.

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.

1.2 Session Mechanism

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.

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'
  }})

What is a single sign-on system? How to implement it using nodejs?

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: &#39;https://www.c.com:3000/sso?key=username&value=123&#39;,
      method: &#39;get&#39;,
    })
  </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.
What is a single sign-on system? How to implement it using nodejs?
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.
    What is a single sign-on system? How to implement it using nodejs?

  • 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.

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 parameters to realize cross-domain information transfer

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请求,适用于所有浏览器,但是缺点也很明显,每次只能分享给一个服务器。
What is a single sign-on system? How to implement it using nodejs?

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)})

What is a single sign-on system? How to implement it using nodejs?
可以看到读取到了存储在www.a.com里面domain为www.c.com的cookie.

3. nodejs实现单点登录系统实战

What is a single sign-on system? How to implement it using nodejs?
效果如图所示:

  • 第一次访问www.a.com首页

  • 跳转到www.c.com:3000登录页面,登录成功后跳转www.a.com首页

  • 再次访问www.a.com首页,无需登录直接跳转

  • 访问www.b.com首页,无需登录直接跳转

源码: https://github.com/wantao666/sso-nodejs

详细设计:
What is a single sign-on system? How to implement it using 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!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor