📜 ⬆️ ⬇️

Integration of ASP.NET MVC 3 applications with Facebook OAuth API. Part 1: Authorization

Why do you need authorization on your site through Facebook ?
At the moment, the social networking site Facebook has over 500 million users. Many sites provide an opportunity to log in without additional registration, where you need to fill in many fields of information about yourself. If you have an account on Facebook, then you just need to login to the site using it. This saves time, because registration often requires spending 5-10 minutes.

If you implement authorization through Facebook, you will most likely be able to get more users on the site, because not everyone wants to go through the registration stage for the sake of writing a few comments.

So let's get started ...

Before creating the application, you must register your site on Facebook.
developers.facebook.com/setup
After registration you will receive 2 keys: App ID and App Secret.
')
Now let's create a new ASP.NET MVC 3 application.
image

We will have to work with Json, so you can download the library here and connect it in the project:
using Newtonsoft.Json.Linq;
Or use the NuGet package manager and write " Install-Package Newtonsoft.Json "

To get started, load the JavaScript SDK to our page.

Copy Source | Copy HTML
  1. $ (document) .ready ( function () {
  2. if (document.getElementById ( 'fb-root' )! = undefined) {
  3. var e = document.createElement ( 'script' );
  4. e.type = 'text / javascript' ;
  5. e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js' ;
  6. e.async = true ;
  7. document.getElementById ( 'fb-root' ) .appendChild (e);
  8. }
  9. });


Next, we initialize our page using App Id, which was obtained when registering a domain on Facebook.

Copy Source | Copy HTML
  1. FB.init ({
  2. appId: 'YOUR_APP_ID' , cookie: true ,
  3. status: true , xfbml: true
  4. });


Let's display the login button via Facebook on the site page.

Copy Source | Copy HTML
  1. < fb: login-button perms = "email, user_checkins"
  2. onlogin = "onConnect ();" autologoutlink = "false">
  3. </ fb: login-button >


This uses the xmlns:fb="http://www.facebook.com/2008/fbml" namespace.
You can generate a button here .

The onlogin event of the fb-button button is triggered after confirming or canceling authorization in the popup window.

image

On the onlogin event, the onConnect () method is called , in which we receive
access_token .

Copy Source | Copy HTML
  1. function onConnect () {
  2. FB.getLoginStatus ( function (response) {
  3. if (response.session) {
  4. window.location = "../Account/FbLogin?token=" + response.session.access_token;
  5. } else {
  6. // if user cancel
  7. }
  8. });
  9. };


This key can be used to retrieve user information. The FbLogin () method of the AccountController controller is called , which receives information about the user:

Copy Source | Copy HTML
  1. public ActionResult FbLogin ( string token)
  2. {
  3. WebClient client = new WebClient ();
  4. string JsonResult = client.DownloadString ( string .Concat ( "https://graph.facebook.com/me?access_token=" , token));
  5. JObject jsonUserInfo = JObject.Parse (JsonResult);
  6. UInt64 facebook_userID = jsonUserInfo.Value < UInt64 > ( "id" );
  7. string username = jsonUserInfo.Value < string > ( "username" );
  8. string email = jsonUserInfo.Value < string > ( "email" );
  9. // can save this information
  10. FormsAuthentication.SetAuthCookie (username, true );
  11. return RedirectToAction ( "Index" , "Home" );
  12. }


What information can be obtained from the user can be found here .

All _LogOnPartial.cshtml code:

Copy Source | Copy HTML
  1. @if (Request.IsAuthenticated)
  2. {
  3. < text > Welcome < strong > @ User.Identity.Name </ strong > ! [@ Html.ActionLink ("Log Off", "LogOff", "Account")] </ text >
  4. }
  5. else
  6. {
  7. < fb: login-button perms = "email, user_checkins" onlogin = "onConnect ();" autologoutlink = "false"> </ fb: login-button >
  8. < div id = "fb-script" st yle = "display: inline; margin-left: 20px;">
  9. </ div >
  10. @: [@ Html.ActionLink ("Log On", "LogOn", "Account")]
  11. }
  12. < script language = "javascript" type = "text / javascript" >
  13. window.fbAsyncInit = function () {
  14. FB.init ({appId: '177572352298948' , status: true , cookie: false , xfbml: true });
  15. };
  16. function afterConnect () {
  17. FB.getLoginStatus ( function (response) {
  18. if (response.session) {
  19. window.location = "../Account/FbLogin?token=" + response.session.access_token;
  20. } else {
  21. // if user cancel
  22. }
  23. });
  24. };
  25. $ (document) .ready ( function () {
  26. if (document.getElementById ( 'fb-root' )! = undefined) {
  27. var e = document.createElement ( 'script' );
  28. e.type = 'text / javascript' ;
  29. e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js' ;
  30. e.async = true ;
  31. document.getElementById ( 'fb-root' ) .appendChild (e);
  32. }
  33. });
  34. </ script >


Before logging in:
image
After authorization:
image

Source: https://habr.com/ru/post/120837/


All Articles