Sometimes you may need to add Login/Hallmark of users using in that location social media accounts like Google, Facebook etc, and so in this article, I have explained how you lot can add a Google authectication button in your ASP.NET MVC awarding and get user details from user's google account using Asp.Internet Identity OAuth and relieve information technology in the database.

By using such feature , users can use their social media identities or any other identities from Providers like Gmail,Facebook etc.  to login to various other services across the web.

If y'all might visit e-commerce site then this option is bachelor there for ease for users to shopping.

So hither is the step by step procedure of implementing Google Authentication in your MVC App:

ane .Create a new project in your Visual Studio(File-> New->Project->From web(Left pane)-> Select "Asp.Net Web Application"(correct pane)) .

    a) Enter a Name, Click "Ok"
    b) Select "MVC" template from projection and click "Ok"

Topic_MvcApp_one.png-min.jpg

c) Click on Modify Authentication Push button -> Select Individual User Accounts.

Topic_Step_Two-min.png

Topic_Step_three-min.png

 By Selecting Individual User Accounts , application will be configured to use ASP.Net Identity   where user register in the application and so sign in via Social Accounts such as Facebook,Twitter,Linkedin ,Google and other providers.

All user credential data will be stored in database.

ii. After creating project successfully now let'southward add connectedness string to projection in Spider web.Config File :

          <connectionStrings>     <add name="DefaultConnection" connectionString="Data Source=HPLAPTOP;Initial Catalog=SNE;UID=sa;Password=sasasa;Integrated Security=True" providerName="Organization.Data.SqlClient" /> </connectionStrings>        

3. Salve the current project and Run the application .

After homepage appears only click on Annals link, then Register page volition appear. After Registeration folio appear enter details required for registration.

After filling data merely click on Register push meanwhileMicrosoft.AspNet.Identity will generate tables in the database every bit shown below.

After Registering user, tables volition be created in database as follows :

Along with this , the credentials we have filled in registration form are saved in table dbo.AspNetUsers as post-obit :

Tables and its Details used for this application :

AspNetRoles : - which stored information related to Role.

AspNetUserRoles: - which stored information related to Role assigned to User.

AspNetUsers: - which stored data related to User.

AspNetUserLogins: - which stored data related to Login Provider [Google, Facebook etc ].

This tabular array contains respective ProviderKey and User id class tabular array AspNetUsers.

4 . Now permit'southward  move towards  Implementing External Authentication provider similar Google :

In your new Project, Install this package for Google Hallmark, using Nuget Package managing director(For Nuget Package manager console, browse Tools-> Nuget Package Manager-> Nuget package manager panel) console, and then enter these commands :

          Install-Package Microsoft.Owin.Security.Google –Version three.0.1        

Startup.Auth.cs file is created by default when we create application and it is located within App_Start as shown below :

To login with gmail account , nosotros first need to Register Awarding with Google.

five. Annals your application with Google to enable OAuth Login :

  • We tin can use existing gmail account or we volition create new one for this applicationn.
  • For this, go to url :    http://console.developers.google.com/
  • and login with gmail login credentials.

      After  Login , click on create project button, new window volition open up with proper name New Project as shown below :

After that we are going to enter project name as"GmailFbOAuth" and click on create a will show youCredentials screen.:

On Credentials screen, there is Create credentials driblet-down list from thatselect OAuth client ID :

Afterward choosing OAuth client ID a new screen will appear with alarm

"y'all must first set a product proper name on the consent tab" with push "Configure consent screen" : every bit below :

"OAuth consent screen" as shown below :

 Enter [Product proper noun to display to users] enter " GmailFbOAuth " and click on save push.

Information technology volition again take yous back to Credentials tab, afterwards once again choosingOAuth customer ID option will take yous to Create ClientID screen equally shown below :

Select Parameteers as follows :

 Application Blazon -> Spider web Awarding

Name ->GmailFbOAuthWebClient

Authorized Javascript option -> the project url [Port No in which application is running].

Hither is  : http://localhost:62054

Authorized Redirected URI  -> This URI is user is redirected later on successfully authenticated by Google.

Here is  : http://localhost:62054/sign-in-google

After clicking on Create button, a new alert will pop up with Name "OAuth Client" .

Information technology contains ClientID and Client secret which nosotros desire to use for OAuth Google integration.

Just copy and paste ClientID and Customer hole-and-corner keys and replace the existing code  to Startup.Auth.cs class equally shown below :

GoogleOAuth2AuthenticationOptions is used to redirect uri with google, is present in the namespace :

using Microsoft.Owin.Security.Google .

          app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()             {                 ClientId = "833953275560-sk3dvhc6p4radtg06h04tm6fv8lneqeh.apps.googleusercontent.com",                 ClientSecret = "x5c1C-PQqpIuz_nfVY8hBjqM"              });                  

Supplant the existing code of views -> Account -> _ExternalLoginsListPartial.cshtml as shown below :

          <div>    <button type="submit" grade="btn btn-default" id="idbtnGoogle" name="idbtnGoogle" value="Google"></button> </div>                  

And so Save awarding and run.

Beneath Login screen volition appear with Google button :

Later on clicking on Google button if it is non Logging in and so we exercise non have permission to the  Google+ API to application.

6. We need to ready access to of Google+ API to "GmailFbOAuth Project" which we have created or Enabling Permission of Google+ API :

  •  Become to URL :https://console.developers.google.com/projectselector/apis/credentials
  • Select Project -> click on Enable API button [+Enable API],it volition accept you to Library View equally shown below
  • Search for Google+ API as below :

  • SelectGoogle+ API link below screen volition announced with Enable push just click on it to enable button.

  • After enabling Google+ API the below view appear :

Later on clicking on Google push  of  projection login it volition take you lot to Google Login page and enquire you to enter credentials for Sign in  or if you are logged in select detail business relationship as below :

google-oauth-login-in-mvc-min.png

Here, subsequently  selecting existing business relationship it volition redirect to ExternalLoginCallback view and on that view it will show your Email ID of Google from which we take logged in, and then finally click on annals button as beneath :

google-oauth-login-in-asp-net-mvc-application-min.png

 it shows bulletin :

"You've successfully authenticated with Google. Please enter a user name for this site beneath and click the Register button to cease logging in."

After clicking on Register push it will annals y'all and along with that information technology also login into the application every bit shown below :

vii.Data has been stored in database afterward this process as below :

 AspNetUserLogins table : stores data related toLoginProvider.

Topic_DbSave.png

AspNetUsers table : stores data related to all Users from OAuth Login .

If it contains PasswordHash then it is registered by general registeration Login and if it is PasswordHash is empty then it is done past OAuth login.

That's it we are done, Thank you for reading. Y'all tin can also download source lawmaking from below link :

https://bulldoze.google.com/file/d/14ZXMxSeAueYdXNabPNLyKWdI0TM6NbVg/view

You may likewise like to read:

How to Create login & registration page in MVC with database (ASP.Internet)

MVC tutorial part-2 connecting to database, fetching/inserting data

Paging, sorting and filtering in ASP.NET MVC C#