Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authentication with Google using OpenOAuthProvider

I created the default ASP.NET project template in Visual Studio and went to the AuthConfig inside App_Start folder. Then I uncommented the following line:

OpenAuth.AuthenticationClients.AddGoogle();

I got the button for logging in with Google like this:

enter image description here When I click on Google button, I'm getting this error:

An exception of type 'DotNetOpenAuth.Messaging.ProtocolException' 
occurred in DotNetOpenAuth.OpenId.RelyingParty.dll but was not handled in user code

Additional information: No OpenID endpoint found.

WE.config file

    <?xml version="1.0" encoding="utf-8"?>
    <!--
      For more information on how to configure your ASP.NET application, please visit
      http://go.microsoft.com/fwlink/?LinkId=169433
      -->
    <configuration>
      <configSections>


     <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
      </configSections>          
      <system.web>
        <compilation debug="true" targetFramework="4.5" />
        <httpRuntime targetFramework="4.5" />
        <pages>


<namespaces>
    <add namespace="System.Web.Optimization" />
  </namespaces>
<controls>
  <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
</controls></pages>
<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" defaultUrl="~/" />
</authentication>
<profile defaultProvider="DefaultProfileProvider">
  <providers>


<add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
  </providers>
</profile>
<membership defaultProvider="DefaultMembershipProvider">
  <providers>
    <add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
  </providers>
</membership>
<roleManager defaultProvider="DefaultRoleProvider">
  <providers>


         <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
          </providers>
        </roleManager>

        <sessionState mode="InProc" customProvider="DefaultSessionProvider">
          <providers>
            <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
          </providers>
        </sessionState>
      </system.web>
      <runtime>


     <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
            <assemblyIdentity name="DotNetOpenAuth.Core" publicKeyToken="2780ccd10d57b246" />
            <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.1.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="DotNetOpenAuth.AspNet" publicKeyToken="2780ccd10d57b246" />
            <bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
          </dependentAssembly>
        </assemblyBinding>
      </runtime>
      <entityFramework>
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
      </entityFramework>

    <appSettings>
          <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
        </appSettings>

    </configuration>

Please help me. What am I missing?

like image 627
Liquid Avatar asked Oct 31 '22 17:10

Liquid


2 Answers

Actually this kind of implementation (OpenId) is deprecated. If it is possible, you should change to MVC5. In MVC5, it's very straightforward. That solution will still work. If you can't, you need to either write this yourself or use a third-party component which uses OAuth2 to communicate with Google. See this answer for more information around the deprecated functionality.

like image 85
Anders Stensaas Avatar answered Nov 08 '22 11:11

Anders Stensaas


As you mentioned in your chat comment using Web Form Application.On click Event of Google.

protected void lnkbtngplus_Click(object sender, EventArgs e) 
{ 
try 
{ 
var Googleurl = "https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=" + ConfigurationManager.AppSettings["googleplus_redirect_url"] + "&scope=googleapis.com/auth/…" + ConfigurationManager.AppSettings["googleplus_client_id"]; 
Session["loginWith"] = "google"; 
Response.Redirect(Googleurl); 
} 

catch (Exception ex) 
{ 
Master.Messages(ex.Message); 
} 
}

On your Redirect url you can collect the parameter values as shown below

  try
                {
                    var url = Request.Url.Query;
                    if (url != "")
                    {
                        string queryString = url.ToString();
                        char[] delimiterChars = { '=' };
                        string[] words = queryString.Split(delimiterChars);
                        string code = words[1];
                        SocialNetwork.GoogleUserOutputData json_data = SocialNetwork.Googlemethod(code);
                        String email = String.Empty;
                        String id = String.Empty;
                        email = json_data.email;
                        id = json_data.given_name;
                        if (email != null && email != "")
                        {
                            txtFname.Text = id;
                            txtemail.Text = email;


                        }


                    }
                }

                catch (Exception ex)
                {

                }

In SocialNetwork class file i have these following methods

#region Google



     protected static string Parameters;


     public static GoogleUserOutputData Googlemethod(string code)
     {
         GoogleUserOutputData serStatus1 = new GoogleUserOutputData();
         string json_data = string.Empty;
         if (code != null)
         {
             //get the access token 
             HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
             webRequest.Method = "POST";
             Parameters = "code=" + code + "&client_id=" + googleplus_client_id + "&client_secret=" + googleplus_client_sceret + "&redirect_uri=" + googleplus_redirect_url + "&grant_type=authorization_code";
             byte[] byteArray = Encoding.UTF8.GetBytes(Parameters);
             webRequest.ContentType = "application/x-www-form-urlencoded";
             webRequest.ContentLength = byteArray.Length;
             Stream postStream = webRequest.GetRequestStream();
             // Add the post data to the web request
             postStream.Write(byteArray, 0, byteArray.Length);
             postStream.Close();

             WebResponse response = webRequest.GetResponse(); 
             postStream = response.GetResponseStream();
             StreamReader reader = new StreamReader(postStream);
             string responseFromServer = reader.ReadToEnd();

             GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject<GooglePlusAccessToken>(responseFromServer);//JsonConvert.DeserializeObject<GooglePlusAccessToken>(responseFromServer);
             //GooglePlusAccessToken serStatus = new GooglePlusAccessToken();
             if (serStatus != null)
             {
                 string accessToken = string.Empty;
                 accessToken = serStatus.access_token;

                 if (!string.IsNullOrEmpty(accessToken))
                 {
                     using (var w = new WebClient())
                     {
                         json_data = w.DownloadString("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + accessToken);
                         serStatus1 = JsonConvert.DeserializeObject<GoogleUserOutputData>(json_data);
                     }
                 }
                 else
                 { }
             }
             else
             { }
         }
         return serStatus1;
     }

     public class GoogleUserOutputData
     {
         public string id { get; set; }
         public string name { get; set; }
         public string given_name { get; set; }
         public string email { get; set; }
         public string picture { get; set; }
     }
     public class GooglePlusAccessToken
     {
         public string access_token { get; set; }
         public string token_type { get; set; }
         public int expires_in { get; set; }
         public string id_token { get; set; }
         public string refresh_token { get; set; }
     }

    #endregion

adding the screenshot of autentication from google based on my working example as provided above

enter image description here

like image 37
Tummala Krishna Kishore Avatar answered Nov 08 '22 13:11

Tummala Krishna Kishore