Pages

Sunday, 28 December 2014

Oauth and Oauth2 authentication in .NET



Registering on websites is hard. So is trying to remember yet another username and password combination. Social logins makes it easy for people to register on your site and quickly sign in using the social network or email identities they already have.

To implement social Login in asp.net website follow these steps

Step 1:

Install OAuth2 package via NuGet
Install-Package OAuth2

Step 2:


Configure library in web.config
<configuration>
  <configSections>
    <section name="oauth2" type="OAuth2.Configuration.OAuth2ConfigurationSection, OAuth2, Version=0.1.*, Culture=neutral"/>
  </configSections>

  <oauth2>
    <services>
      <add clientType="GoogleClient"
           enabled="false"
           clientId="000000000000.apps.googleusercontent.com"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAA"
           scope="https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email"
           redirectUri="http://mymachine.net:53023/Auth" />
      <add clientType="FacebookClient"
           enabled="false"
           clientId="000000000000000"
           clientSecret="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
           scope="email"
           redirectUri="http://mymachine.net:53023/Auth" />
      <add clientType="VkClient"
           enabled="false"
           clientId="AAAAAAAAAAAA"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
           scope="offline"
           redirectUri="~/Auth" />
      <add clientType="TwitterClient"
          enabled="false"
           clientId="AAAAAAAAAAAAAAAAAAAAAA"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
           redirectUri="http://mymachine.net:53023/Auth" />
      <add clientType="LinkedInClient"
          enabled="false"
           clientId="aaaaaaaaaaaa"
           clientSecret="AAAAAAAAAAAAAAAA"
           redirectUri="http://mymachine.net:53023/Auth" />
      <add clientType="OdnoklassnikiClient"
           enabled="false"
           clientId="AAAAAAA"
           clientSecret="AAAAAAAAAAAA"
           clientPublic="AAAAAAAAAAAAAAAAA"
           redirectUri="~/auth" />
      <add clientType="YandexClient"
           enabled="false"
           clientId="AAAAAAAAAAAAAAAAA"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAAAA"
           redirectUri="~/auth" />
      <add clientType="MailRuClient"
           enabled="false"
           clientId="AAAAAAAAAAAAAAAAAAA"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
           redirectUri="~/auth" />
      <add clientType="FoursquareClient"
           enabled="false"
           clientId="AAAAAAAAAAAAAAAAAAAAAAAAAAA"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
           redirectUri="~/auth" />
      <add clientType="WindowsLiveClient"
           enabled="false"
           clientId="AAAAAAAAAAAAAAA"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
           scope="wl.basic wl.emails"
           redirectUri="~/auth" />
      <add clientType="InstagramClient"
           clientId="AAAAAAAAAAAAAAAAAAA"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
           scope="basic"
           redirectUri="~/auth" />
      <add clientType="DigitalOceanClient"
           clientId="AAAAAAAAAAAAAAAAAAA"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
           scope="read write"
           redirectUri="~/auth" />
    </services>
  </oauth2>

Step 3:

Add a private variable in your Accounts controller
AuthorizationRoot authorizationRoot = new AuthorizationRoot();

Step 4:

Add Social Login Action in your Accounts Controller. 
public ActionResult SocialLogin(string ProviderName)
{
    //user will hit the following action on button click 
}

Step 5:

Add Get client private Method in your controller
private IClient GetClient(string ProviderName) 
{ 
   return authorizationRoot.Clients.First(c => c.Name == ProviderName); 
} 

Step 6:

Add following code in your Social login Action 
public ActionResult SocialLogin(string ProviderName)
{
 Session["ProviderName"] = providerName;      return new RedirectResult(GetClient().GetLoginLinkUri());
}

Step 7:

Add oauth Action method to the controller
public ActionResult Auth() 

 { 

 if (Session["ProviderName"] == "google") 

 { 

 GoogleClient google = GetClient(Session["ProviderName"] ) as GoogleClient; 

 //User basic info 

 UserInfo userInfo = google.GetUserInfo(Request.QueryString); 

 myUser.Email = userInfo.Email; 

 myUser.AvatarUri = userInfo.AvatarUri; 

 myUser.FirstName = userInfo.FirstName; 

 myUser.LastName = userInfo.LastName; 

 //Store this if you want to make api calls 

 Session["googleAccessToken"] = google.AccessToken; 

} 
if (Session["ProviderName"] == "twitter") 
 { 
 TwitterClientgoogle = GetClient(Session["ProviderName"] ) as TwitterClient; 

 //User basic info 

 UserInfo userInfo = google.GetUserInfo(Request.QueryString); 

 myUser.Email = userInfo.Email; 

 myUser.AvatarUri = userInfo.AvatarUri; 

 myUser.FirstName = userInfo.FirstName; 

 myUser.LastName = userInfo.LastName; 

 //Store token if you want to make api calls 

 Session["twitterAccessToken"] = google.AccessToken; 

} 
//and so on for other social logins
} 

Step 8:

Making Api calls Define scope in config to get user permission for the resources
<add clientType="GoogleClient"
           enabled="false"
           clientId="000000000000.apps.googleusercontent.com"
           clientSecret="AAAAAAAAAAAAAAAAAAAAAAAA"
           scope="https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email"
           redirectUri="http://mymachine.net:53023/Auth" />
and add following code to the any action where you want the user data
RequestFactory _factory = new RequestFactory(); 

 var client = _factory.CreateClient(new Endpoint { BaseUri = "https://www.google.com", Resource = "/m8/feeds/contacts/default/full" }); 

 var request = _factory.CreateRequest(new Endpoint { BaseUri = "https://www.google.com", Resource = "/m8/feeds/contacts/default/full" }); 

 request.AddParameter("alt", "json"); 

 request.AddHeader("Authorization", "Bearer " + Session["googleAccessToken"]); 

request.RequestFormat = RestSharp.DataFormat.Json; 

 RestSharp.RestResponse a = RestClientExtensions.ExecuteAndVerify(client, request) as RestSharp.RestResponse; 

jsonData = a.Content; 
and do whatever you want to do with it !!!.

:)