[JS] [Node.js] facebook authentication demo

流程

這是不使用任何facebook sdk的方法

首先要去fb新開一個app
https://developers.facebook.com/apps/3xxx21/summary?save=1
在裡面填入app的uri, eg.http://localhost:8888/demo.html
(注意:之後app要redirect_uri的uri,必須填在裡面)




參考 Client-side authentication without the JS SDK
要填入的只有以下項目:
https://www.facebook.com/dialog/oauth?
   client_id=YOUR_APP_ID
  &redirect_uri=YOUR_REDIRECT_URI
  &scope=COMMA_SEPARATED_LIST_OF_PERMISSION_NAMES
  &response_type=token


所以我們知道要用app redirect此url到fb做認證
https://www.facebook.com/dialog/oauth?client_id=3xxx021&redirect_uri=http://localhost:8888/demo.html&response_type=token

在認證成功後,fb會redirect到你指定出的redirect_uri,
http://localhost:8888/demo.html#access_token=AAAxxxxWPTM2xF&expires_in=6807

由url hash可以得到access_token
就可以使用fb graph api了

可以參考fb的流程圖:

demo

app.js

var server,
   ip   = "localhost",
   port = 8888,
   http = require('http'),
   fs = require("fs"),
   filename = "demo.html",
   encode = "utf8";

server = http.createServer(function (req, res) {
   fs.readFile(filename, encode, function(err, file) {
       if (err) {
       res.writeHead(404, {'Content-Type': 'text/plain'});
       res.end();
       return;
       }

       res.writeHead(200, {'Content-Type': 'text/html'});
       res.write(file);
       res.end();
       });
   });

server.listen(port, ip);
console.log("Server running at http://" + ip + ":" + port);



app.js作為一個單純的server,開啟demo.html靜態網頁。
為什麼要用內嵌javascript去跟fb做認證而不直接用node.js,主要是因為graph api的token是放在url hash,所以node.js會讀不到,可以看:[JS] [Node.js] Express error on windows evirement 這篇。

demo.html

<html>
<head>
<title>Client-side OAuth Example</title>
</head>
<body>
<p id="userName"></p>
<script>
function displayUser(user) {
       var userName = document.getElementById('userName');
       var greetingText = document.createTextNode('Greetings, '
                       + user.name + '.');
       userName.appendChild(greetingText);
}

if (window.location.hash.length == 0) {
       window.open('https://www.facebook.com/dialog/oauth?client_id=3xxx021&redirect_uri=http://localhost:8888/demo.html&response_type=token');
} else {
       var accessToken = window.location.hash.substring(1);
       var path = "https://graph.facebook.com/me?";
       var queryParams = [accessToken, 'callback=displayUser'];
       var query = queryParams.join('&');
       var url = path + query;

       // use jsonp to call the graph
       var script = document.createElement('script');
       script.src = url;
       document.body.appendChild(script);    
}
</script>
</body>
</html>


demo.html內嵌javascript,
如果url沒有hash就去做轉址等動作,
反之,用graph api去要使用者資料,顯示username到網頁。

補充

javascript class and method

join('&')
用'&'字符合併字串

window.open(url)
前往url

window.location
取得目前url

window.location.hash
取得#後面字串

document.createElement('xxx');
建立 <xxx> </xxx> Element

appendChild()
可向節點的子節點列表的末尾添加新的子節點。

jsonp請看wiki說明
http://zh.wikipedia.org/wiki/JSONP

fb範例

<html>
<head>
<title>Client-side OAuth Example</title>
</head>
<body>
<script>
function displayUser(user) {
       var userName = document.getElementById('userName');
       var greetingText = document.createTextNode('Greetings, '
                       + user.name + '.');
       userName.appendChild(greetingText);
}

var appID = YOUR_APP_ID;
if (window.location.hash.length == 0) {
       var path = 'https://www.facebook.com/dialog/oauth?';
       var queryParams = ['client_id=' + appID,
           'redirect_uri=' + window.location,
           'response_type=token'];
       var query = queryParams.join('&');
       var url = path + query;
       window.open(url);
} else {
       var accessToken = window.location.hash.substring(1);
       var path = "https://graph.facebook.com/me?";
       var queryParams = [accessToken, 'callback=displayUser'];
       var query = queryParams.join('&');
       var url = path + query;

       // use jsonp to call the graph
       var script = document.createElement('script');
       script.src = url;
       document.body.appendChild(script);       
}
</script>
<p id="userName"></p>
</body>
</html>


Reference

http://developers.facebook.com/docs/authentication/client-side/
http://developers.facebook.com/docs/authentication/server-side/
http://zh.wikipedia.org/wiki/JSONP

留言

這個網誌中的熱門文章

Mac起步:常用軟體及設定

台灣可用線上音樂串流網站

醍醐味