>  기사  >  웹 프론트엔드  >  nodejs가 jsonp를 통해 Single Sign-On 데모를 구현하는 방법

nodejs가 jsonp를 통해 Single Sign-On 데모를 구현하는 방법

php中世界最好的语言
php中世界最好的语言원래의
2018-03-12 09:54:032366검색

이번에는 nodejs가 jsonp를 통해 Single Sign-On 데모를 구현하는 방법을 보여드리겠습니다. Nodejs가 jsonp를 통해 Single Sign-On 데모를 구현하는 경우 주의할 점은 무엇인가요?

지침: redis를 세션 저장 방법으로 사용
sso 서버에 도입된 동적 js 주소를 사용하여 쿠키를 얻습니다.
애플리케이션 서버가 sessionId 또는 기타와 같은 단일 지점 서버에서 제공하는 특수 식별을 얻은 후
이동 식별 쿼리를 통해 Redis에 직접 연결하거나 단일 서버에 제출(rpc를 통해)하여 로그인 정보 결과를 쿼리하고 얻습니다

서버 코드 예

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

애플리케이션 코드 예:

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

Windows 시스템에서 호스트 파일을 수정
(보통 C:WindowsSystem32driversetc)
추가:

127.0.0.1 sso.com127.0.0.1 testsso.com

브라우저 액세스:

http://sso.com:8087
http://testsso.com:8088

이 기사의 사례를 읽으신 후 방법을 마스터하셨다고 생각합니다. 더 흥미로운 정보를 보려면 PHP 중국어 웹사이트의 다른 관련 기사에 주목하세요. !

관련 읽기:

python3과 JS의 차이점은 무엇입니까

H5에서 이미지 업로드 미리 보기 구성 요소를 만드는 방법

s-xlsx를 사용하여 Excel 파일 가져오기 및 내보내기를 구현하는 방법

위 내용은 nodejs가 jsonp를 통해 Single Sign-On 데모를 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.