Home Web Front-end JS Tutorial How nodejs implements single sign-on Demo through jsonp

How nodejs implements single sign-on Demo through jsonp

Mar 12, 2018 am 09:54 AM
javascript jsonp nodejs

This time I will bring you how nodejs implements single sign-on demo through jsonp. What are the precautions for nodejs to implement single sign-on demo through jsonp. The following is a practical case, let's take a look.

Instructions: Use redis as the session storage method
Use the dynamic js address introduced into the sso server to obtain the cookie
After the application server obtains the special identifier provided by the single-point server such as sessionId or others,
Go directly to redis to query through the identifier, or submit (through rpc) to a single server to query and obtain the login information results

Server code example

const Koa = require('koa');const Router = require('koa-router');const bodyParser = require('koa-bodyparser');const app = new Koa(); 
const router = new Router(); 
app.use(bodyParser());//====session s=====var session = require('koa-generic-session');var redisStore = require('koa-redis');
app.keys = ['keys', 'c29tZSBzZWNyZXQgaHVycg'];
app.use(session({//配置session
    store: redisStore({}),    cookie: {        path: '/',        httpOnly: true,        maxAge: 1 * 60 * 60 * 1000,        rewrite: true,        signed: true
    }
}));//====session e=====router.get('/login', function* (next) {//登录页面 
    this.session=null;//删除cookie
    this.body=`
    <form action="/login" method="post">
        <p>用户名: <input type="text" name="name" /></p>
        <p>密码: <input type="text" name="pwd" /></p>
        <input type="submit" value="提交" />
    </form>   
    `;
}).post(&#39;/login&#39;, function* (next) {//提交登录数据 
    var sinfo = JSON.stringify(this.request.body);//<==获取post数据
    this.session.sinfo =sinfo;//<===存入session,模拟登录成功
    this.redirect(&#39;/&#39;);//<===跳转向到你要的页面});
router.get(&#39;/&#39;, function* (next) {    if(this.session&&this.session.sinfo){//判断是否有cookie
        this.body=`已登录 `;
    }else{        this.redirect(&#39;/login&#39;);//<===跳转向到你要的页面    
    }
});
router.get(&#39;/sso.js&#39;, function* (next) { //动态js
    if(this.session&&this.session.sinfo&&this.session.sinfo.length>0){        this.body=`var kosid=&#39;${this.sessionId}&#39;;`;//示例写入sessionId,也就是存入到redis的key
    }else{         this.body=`window.location.href="http://sso.com/login";`;
    }
});
app.use(router.routes()).use(router.allowedMethods());
app.listen(8087);
Copy after login

Application code example:

const Koa = require(&#39;koa&#39;);const Router = require(&#39;koa-router&#39;);const bodyParser = require(&#39;koa-bodyparser&#39;);const app = new Koa(); 
const router = new Router(); 
app.use(bodyParser());//====session s=====可以直接用普通session app.keys = [&#39;c29tZSBzZWNyZXQgaHVycg%3D%3D&#39;];var CONFIG = {
    key: &#39;koa:sess&#39;, /** (string) cookie key (default is koa:sess) */
    maxAge: 2000, /** (number) maxAge in ms (default is 1 days) */
    overwrite: true, /** (boolean) can overwrite or not (default true) */
    httpOnly: true, /** (boolean) httpOnly or not (default true) */
    signed: true, /** (boolean) signed or not (default true) */};
app.use(session(CONFIG, app));//====session e=====/*
//====session s===== 或者一样吧
var session = require(&#39;koa-generic-session&#39;);
var redisStore = require(&#39;koa-redis&#39;);
app.keys = [&#39;keys&#39;, &#39;c29tZSBzZWNyZXQgaHVycg&#39;];
app.use(session({//配置session
    store: redisStore({}),
    cookie: {
        path: &#39;/&#39;,
        httpOnly: true,
        maxAge: 1 * 60 * 60 * 1000,
        rewrite: true,
        signed: true
    }
}));
//====session e=====
*/router.get(&#39;/&#39;, function* (next) {
     this.body=`
        <script type="text/javascript" src="http://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
        <script type="text/javascript" src="http://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
        <script src=&#39;http://sso.com:8087/sso.js&#39;></script>
        <script>
            $.cookie("sid",kosid);            if(kosid){
                document.write(&#39;key:&#39;,kosid);
            }else{
                document.write(&#39;未登录&#39;);                
            }
            console.log("this",document.cookie);
        </script>`;    return;
});
app.use(router.routes()).use(router.allowedMethods());
app.listen(8088);
Copy after login

Modify hosts file under windows system
(usually under C:\Windows\System32\drivers\etc)
Add:

127.0.0.1 sso.com127.0.0.1 testsso.com
Copy after login

Browser access:

http://sso.com:8087
http://testsso.com:8088
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Related reading:

What is the difference between python3 and JS

How to make an image upload preview component in H5

How to use s-xlsx to import and export Excel files

The above is the detailed content of How nodejs implements single sign-on Demo through jsonp. For more information, please follow other related articles on the PHP Chinese website!

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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is nodejs a backend framework? Is nodejs a backend framework? Apr 21, 2024 am 05:09 AM

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

How to connect nodejs to mysql database How to connect nodejs to mysql database Apr 21, 2024 am 06:13 AM

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

What are the global variables in nodejs What are the global variables in nodejs Apr 21, 2024 am 04:54 AM

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

What is the difference between npm and npm.cmd files in the nodejs installation directory? What is the difference between npm and npm.cmd files in the nodejs installation directory? Apr 21, 2024 am 05:18 AM

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

Is there a big difference between nodejs and java? Is there a big difference between nodejs and java? Apr 21, 2024 am 06:12 AM

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Is nodejs a back-end development language? Is nodejs a back-end development language? Apr 21, 2024 am 05:09 AM

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

How to deploy nodejs project to server How to deploy nodejs project to server Apr 21, 2024 am 04:40 AM

Server deployment steps for a Node.js project: Prepare the deployment environment: obtain server access, install Node.js, set up a Git repository. Build the application: Use npm run build to generate deployable code and dependencies. Upload code to the server: via Git or File Transfer Protocol. Install dependencies: SSH into the server and use npm install to install application dependencies. Start the application: Use a command such as node index.js to start the application, or use a process manager such as pm2. Configure a reverse proxy (optional): Use a reverse proxy such as Nginx or Apache to route traffic to your application

Which one to choose between nodejs and java? Which one to choose between nodejs and java? Apr 21, 2024 am 04:40 AM

Node.js and Java each have their pros and cons in web development, and the choice depends on project requirements. Node.js excels in real-time applications, rapid development, and microservices architecture, while Java excels in enterprise-grade support, performance, and security.

See all articles