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

青灯夜游
Release: 2023-02-24 19:33:33
forward
2133 people have browsed it

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 astateless 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 aswww.app1.aaa.com,www.app2.aaa.comThese 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

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

2. Cross-domain SSO

When our domain name iswww.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.

Copy after login

But we can initiate cross-domain requests through the tag and write cookies

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.
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'})
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.
    What is a single sign-on system? How to implement it using nodejs?

  • The browser does not write cookies and reports an errorthis 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 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}`)})
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请求,适用于所有浏览器,但是缺点也很明显,每次只能分享给一个服务器。
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

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

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!

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!