2015年12月18日 星期五

[C#][MVC] Facebook OAuth 驗證與登入

1. 申請自己的app : https://developers.facebook.com/apps/




 





2. 選擇要建立的app (範例網站)

3. 輸入app名稱

4. 選擇你的類型後, 點擊新增


























5. 看到此頁面就是成功了申請囉, 然後照著步驟走
5.1 記得設定你的網站網址 : ex. http://localhost:7115/




6. 回到 https://developers.facebook.com/apps/ 選擇TestWeb
7. 記住你的App ID
8. 在你的網站js輸入以下code (請自行重構)


// For FB
window.fbAsyncInit = function() {
    FB.init({
        appId: xxxxxx// App ID
        status     : true, // check login status
        cookie     : true, // enable cookies to allow the server to access the session
        xfbml: true,  // parse XFBML
        version: 'v2.5'
    });

    // Additional initialization code here
    FB.Event.subscribe('auth.authResponseChange', function (response) {
        if (response.status === 'connected') {
            // the user is logged in and has authenticated your
            // app, and response.authResponse supplies
            // the user's ID, a valid access token, a signed
            // request, and the time the access token
            // and signed request each expire
            var uid = response.authResponse.userID;
            var accessToken = response.authResponse.accessToken;
            var data = {
                token: accessToken
            }
            // TODO: Handle the access token
            console.log(uid);
            console.log(accessToken);
            ajaxServer('Home/FacebookLogin', data);
        } else if (response.status === 'not_authorized') {
            // the user is logged in to Facebook,
            // but has not authenticated your app
        } else {
            // the user isn't logged in to Facebook.
        }
    });
};

function fbLogout() {
    FB.logout(function (response) {
        window.location.reload();
        // user is now logged out
    });
}

// Load the SDK Asynchronously
(function(d){
    var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement('script'); js.id = id; js.async = true;
    js.src = "//connect.facebook.net/en_US/all.js";
    ref.parentNode.insertBefore(js, ref);

}(document));

function ajaxServer(url, data) {
    $.ajax({
        url: url,
        data: data,
        type: "POST",
        dataType: 'json',
        success: function (msg) {
            console.log(msg);
        },

        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
        }
    });
}

註.裡面的ajax 就是post到你的server, 

9. 至html頁面放入以下 :
<div class="fb-login-button" scope="public_profile,email" data-show-faces="true" data-width="400" data-max-rows="1"></div>
<a href="#" onclick="fbLogout();">FB Sign out</a>
<div id="fb-root"></div>
標籤scope就是你希望請求的資訊,可參考此 : https://developers.facebook.com/docs/facebook-login/permissions#reference


9.  server端(.net), 請到nuget 下載facebook套件  http://facebooksdk.net/docs/web/getting-started/

10. 寫一個Action :

        [HttpPost]
        public JsonResult FacebookLogin(string token)
        {
            var client = new FacebookClient(token);
            dynamic result = client.Get("me", new { fields = "name,id,email" });
            string name = result.name;
            string id = result.id;
            return Json(name, JsonRequestBehavior.AllowGet);
        }