Home > Web Front-end > JS Tutorial > A brief analysis of how node implements a single sign-on system

A brief analysis of how node implements a single sign-on system

青灯夜游
Release: 2022-10-28 09:49:37
forward
2084 people have browsed it

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!

A brief analysis of how node implements a single sign-on system

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'
  }})
Copy after login

A brief analysis of how node implements a single sign-on system

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>
Copy after login

But we can initiate cross-domain requests through the <script></script> tag and write cookies

<script></script>
Copy after login
Copy after login

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'
    })
Copy after login

In this way, through the tag, the cross-domain cookie with the domain of www.c.com is written to www.a.com.
A brief analysis of how node implements a single sign-on system
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'})
Copy after login

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.
    A brief analysis of how node implements a single sign-on system

  • 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'})
Copy after login
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}`)})
Copy after login

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'})
Copy after login

这样就实现了跨域信息的传递.与上面的方式不同,这种方法只是单纯的http请求,适用于所有浏览器,但是缺点也很明显,每次只能分享给一个服务器。
A brief analysis of how node implements a single sign-on system

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>
Copy after login
Copy after login

www.c.com

router.get('/readCookie', async (ctx, next) => {
  let username = ctx.cookies.get('username')
  console.log('cookie', username)})
Copy after login

A brief analysis of how node implements a single sign-on system
可以看到读取到了存储在www.a.com里面domain为www.c.com的cookie.

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

A brief analysis of how node implements a single sign-on system
效果如图所示:

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

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

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

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

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

详细设计:
A brief analysis of how node implements a single sign-on system

更多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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template