在做项目的时候常常会获取某个页面的数据,但是需要认证,而且认证是SSO What is SSO?的方式。自己在网上查了好长一段时间都没有找到如何写js认证SSO的例子,最后还是组里的大牛写了个,我觉得是个非常好的例子,于是就放在自己的博客里,分享给大家,同时也算勉励自己吧!
那么什么是SSO呢?
Definition - What does Single Sign-On (SSO) mean?
SSO advantages include:
Eliminates credential reauthentication and help desk requests; thus, improving productivity. Streamlines local and remote application and desktop workflow. Minimizes phishing. Improves compliance through a centralized database. Provides detailed user access reporting.那么如何用ajax + nodejs 获取呢? 同时添加了个loading的动画,请看下面的代码吧。保证是可用,本人已亲测!
前端AJAX 代码:
<!DOCTYPE html> <head> <script type="text/javascript"> /******************************************************************/ /* use ajax to get data according to nodejs---access through SSO certifications. */ var account = '*****'; var pw = '****'; var prurl = 'https://test.test.changpzh/prontoapi/rest/api/latest/problemReport/prNum' var url = Settings.dataServerUrl + "/api/issues/pr"; // this is nodejs link. var parameters = { "prurl": prurl, }; $.ajax({ url: url, dataType: "json", type: "post", data: parameters, beforeSend: function() { // add a loading process during data loading. var loadingDiv = "<div><img src='img/loading.gif'></img></div>"; $("#loading").append(loadingDiv); }, success: function (data) { console.log(data); }, complete:function(){ //remove loading process after finish data loading. $("#loading .loadingFlag").remove(); }, error: function (e) { alert(JSON.stringify(e)); } }); </script> </head> <body> </body> <html>后端nodejs代码
var express = require('express'); var router = express.Router(); var mongoskin = require('mongoskin'); var async = require('async'); var moment = require('moment'); var _ = require('lodash-node'); var db = require('../../settings').DB; var logger = require('../../logging').getLogger('api/issues'); var es = require('../../eventstore')(); /******************************************************************/ /* use ajax to get data according to nodejs---access through SSO certifications. */ var http = require('http'); var url_obj = require('url'); router.use("/pr",function (req, res, next) { res.header('Access-Control-Allow-Origin', '*'); var prurl=url_obj.parse(req.body.prurl); console.log(req.body.prurl); // 'https://mydata.informaion.com/prontoapi/rest/api/latest/problemReport/PR195666' var account = 'username'; var pw = 'password'; var post_options = { host: prurl.host,//'mydata.informaion.com', port: '80', path: prurl.path,//'/prontoapi/rest/api/latest/problemReport/PR195666', method: 'GET', auth: account+':'+pw, }; http.get(post_options, function(res1) { const statusCode = res1.statusCode; const contentType = res1.headers['content-type']; var error; if (statusCode !== 200) { error = new Error('statuscode!=200'); } else if (!/^application\/json/.test(contentType)) { error = new Error("Invalid content-type.\nExpected application/json but received ${contentType}"); } console.log(error); if (error) { res1.resume(); return res.send({}) } // res1.setEncoding('utf8'); var rawData = ''; res1.on('data', function(chunk){ rawData += chunk; }); res1.on('end', function() { try { // var parsedData = JSON.parse(rawData); res.send(rawData); } catch (e) { console.log(e.message); } }); }).on('error', function(e){ console.log(e); }); });============后记:===============
其实我的这个还是可以通过CURL实现的,而且本人也是用的这种方式:代码如下
前端AJAX代码:
<!DOCTYPE html> <head> <script type="text/javascript"> /******************************************************************/ /* use ajax to get data according to curl. */ var pr_api_url = Settings.apiUrl + "/issues/prInfo_get?prNum="+pr_num; console.log(pr_api_url); $.ajax({ url: pr_api_url, dataType: "json", data: null, async: false, beforeSend: function() { // add a loading process during data loading. var loadingDiv = "<div><img src='img/loading.gif'></img></div>"; $("#loading").append(loadingDiv); }, success: function(myData) { console.log(data); }, complete:function(){ //remove loading process after finish data loading. $("#loading .loadingFlag").remove(); }, error:function(err){ console.log(err); } }); </script> </head> <body> </body> <html>后端代码
//'use strict'; var express = require('express'); var router = express.Router(); var mongoskin = require('mongoskin'); var async = require('async'); var moment = require('moment'); var _ = require('lodash-node'); var db = require('../../settings').DB; var logger = require('../../logging').getLogger('api/issues'); var es = require('../../eventstore')(); /*For get data from PR system API*/ /******************************************************************/ /* use ajax to get data according to curl. */ var exec = require('child_process').exec; router.get("/prInfo_get", function(req, res, next) { var url = 'https://mydata.informaion.com/prontoapi/rest/api/latest/problemReport/'; var prNum = req.query.prNum; // pr_url = req.body.prurl; var USER = "username"; var PASSWD = "password"; var cmdStr = "curl -u \"" + USER + ":" + PASSWD + "\" " + url + prNum; //cmdStr = 'curl -u "username:password" https://mydata.informaion.com/prontoapi/rest/api/latest/problemReport/PR178847' exec(cmdStr, function(err,stdout,stderr){ if(err) { console.log('get pr api error:'+stderr); } else { var data = JSON.parse(stdout); console.log(data); res.send({data:data}); } }); });