OAuth Authentication

OAuth Authentication Google, Facebook, LinkedIn

Hi this is Sandeep i Would like to share my work on OAuth Authentication for the external Providers like Google, Facebook, LinkedIn. For this demo i used Visual Studio 2015.

Step 1

Create Project in Visual Studio

From Templates Select Web after that select Asp.net Web application

Step 2

Select MVC Layout

In this MVC Layout we will get the basic structure of the MVC project with Models, Views and Controllers

Step 3

Once Run the Project F5

After Running the project home page will appear this is basic template in the MVC, after Clicking on the login button the login view will appear

Step 4

Open the solution explorer and go to App_start Folder, this folder contains some core configuration files that is applicable for entire MVC application. Now open App_start.cs file which contains Authorization stuffs.

Google

You  have get the credentials for accessing the data from the external providers go to Google developers console and create credentials for your project.

now you you have to give your project name and the url's like redirect url with /signin-google appended
ex: http://localhost:0000/signin-google  port address in case localhost otherwise your web site address.


now you will get the credentials for the OAuth Authentication with google copy those credentials.
and you have to enable the google api to work. Go to Libraries and there you will find the google api click on the link and Click on Enable button.


Step 5

Adding  Client Id , Client Secret Code and Claims

Claim is piece of information that describes given identity on some aspect. Take claim as name-value pair. Claims are held in authentication token that may have also signature so you can be sure that token is not tampered on its way from remote machine to your system. You can think of token as envelop that contains claims about user.
Token may contain different claims like username or user ID in remote system,full name of user,e-mail address,membership in security groups,phone number,color of eyes...etc
in App_start.cs file add these claims. 
            var googleOptions = new GoogleOAuth2AuthenticationOptions()
            {
                ClientId = "xxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
                ClientSecret = "xxxxxxxxxxxxxxxx",
                Provider = new GoogleOAuth2AuthenticationProvider() {
                    OnAuthenticated = (context) =>{
                        context.Identity.AddClaim(new Claim("urn:google:name", context.Identity.FindFirstValue(ClaimTypes.Name)));
                        context.Identity.AddClaim(new Claim("urn:google:email", context.Identity.FindFirstValue(ClaimTypes.Email)));
                        ////This following line is need to retrieve the access token
                        context.Identity.AddClaim(new System.Security.Claims.Claim("urn:google:accesstoken", context.AccessToken, ClaimValueTypes.String, "Google"));
                        return Task.FromResult(0);
                    }
                }
            };
            app.UseGoogleAuthentication(googleOptions);
Now again run the project and go to login page there you will find the Google provider button enabled in the login page before it is in disable state after adding the credentials it is in active state.
Click on Google button it will redirect you to gmail to ask the permissions.click on allow
if you are not getting this page means you make mistake in the redirect url in the  Google developers console once check that and run the project again and try.
after click on allow it will redirect you to the registration page with login user credentials like email 
you can check how the flow is going by keeping a break point in the account controller at "ExternalLogin" Action and after successful call it will come back to the "ExternalLoginCallback" Action in this action you can get the client data in the "logininfo" variable you can check the client claims and access token too.

Facebook

For Facebook also you have to create app.Go to this Facebook Developers page and create app


you have to select www option while creating which is for web after that you have to enter the redirect url ex:http://localhost:0000 or the website address which you want to redirect and copy the App id  and the secret code.

Step 6:

Facebook App Id and Secret Code 

Paste the App id and the secret code in the App_start.cs file in the project 

    app.UseFacebookAuthentication(
              appId: "xxxxxxxxxxxxxxxxxx",
              appSecret: "xxxxxxxxxxxxxxxxxxxxxxxxxxxx");

and run the project now you can see the Facebook button also in the login page,but this time you will get only name and the identifier of the user because we have to add claims externally for the Facebook provider.

For getting user details like Email, Profile picture, access token etc... we have to add claims 

  app.UseFacebookAuthentication(new FacebookAuthenticationOptions
            {
                AppId = "xxxxxxxxxxx",
                AppSecret = "xxxxxxxxxxxxxxxxxxxxxxxxx",
                Provider = new FacebookAuthenticationProvider
                {
                    OnAuthenticated = context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
                        return Task.FromResult(true);
                    }
                },
                BackchannelHttpHandler = new FacebookBackChannelHandler(),
//this graph url is for the user details 
                UserInformationEndpoint = "https://graph.facebook.com/v2.8/me?fields=id,name,email,first_name,last_name,location"
            });

and here we are also using the FacebookBackChannelHandler to get the access token this code can be written in the same file App_start.cs

        public class FacebookBackChannelHandler : HttpClientHandler
        {
            /// <summary>
            /// Creates an instance of  <see cref="T:System.Net.Http.HttpResponseMessage" /> based on the information provided in the <see cref="T:System.Net.Http.HttpRequestMessage" /> as an operation that will not block.
            /// </summary>
            /// <param name="request">The HTTP request message.</param>
            /// <param name="cancellationToken">A cancellation token to cancel the operation.</param>
            /// <returns>
            /// Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.
            /// </returns>
            protected override async System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
            {
                // Replace the RequestUri so it's not malformed
                if (!request.RequestUri.AbsolutePath.Contains("/oauth"))
                {
                    request.RequestUri = new Uri(request.RequestUri.AbsoluteUri.Replace("?access_token", "&access_token"));
                }

                return await base.SendAsync(request, cancellationToken);
            }
        }

after adding this Facebook back channel handler we can get the access token for the Facebook 
NOTE: In the graph url we have to specify the version of app we are using you can get from the Facebook Developers page Dashboard.



LinkedIn

For LinkedIn we have to create Application in the linkedIn go to the LinkedIn developers page


Loading ..............................

Comments

  1. Thanks a lot you saved my day. Haven't seen such an awesome post anywhere (:

    ReplyDelete

Post a Comment