Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# google login

I'm maintaining some code that I want to add a chat feature to. I already have a client/server/database setup, but what I would like to do is use Google accounts for logins, instead of people having to create new accounts and such. Could anyone point me in the right direction? I've already downloaded this http://code.google.com/p/google-gdata/ Am I on the right track?

Just to clarify as well, this isn't an asp project, it's a desktop project.

like image 849
Kelly Elton Avatar asked Apr 29 '26 05:04

Kelly Elton


1 Answers

After lots tinkering around, I was able to come up with this solution. It looks so easy, yet I wasn't able to find any proper documentation on it. I'm sure people will find this extremely helpful. Just get the Google API from http://code.google.com/p/google-gdata/ and add Google.GData.Client.dll as a reference(it's under the redist folder)

using Google.GData.Client;
public bool Google_Login(string email,string password, string captcha,string captchatoken)
{
    String AppName = "MyCompany-MyApp-1.0.0.0";
    Service s = new Service("code", AppName); //Can use any service, I just happened to want to use GoogleCode
    s.setUserCredentials(email, password);
    if(captcha != null && captchatoken != null) //If we already tried to log in, but we needed to captcha
    {
        if(!String.IsNullOrWhiteSpace(captcha) || !String.IsNullOrWhiteSpace(captchatoken))
        {
            s.Credentials.CaptchaToken = captchatoken;
            s.Credentials.CaptchaAnswer = captcha;
        }
    }
    try
    {
        string ret = s.QueryClientLoginToken();
        //If we end up here, then the credentials are correct.
    }
    catch(Google.GData.Client.CaptchaRequiredException ce)
    {
        //ce.Url is the full url of the Captcha image
        //If you would rather handle the captcha from
        //a webpage, you can make your user go here "https://www.google.com/accounts/DisplayUnlockCaptcha"

        //TODO Some way to display the captcha image and get user feedback
        //we'll just say you did that and returned a string named retCaptcha
        return Google_Login(email,password, retCaptcha,ce.Token);
    }
    catch(Google.GData.Client.AuthenticationException re)
    {
        //re.Message is the specific message google sends back about the login attempt.
        return false;
    }
    catch(WebException e)
    {
        //Haven't ended up here yet, but I'm sure it's possible.
        return false;
    }
    //If we somehow end up here
    return false;
}

This isn't the exact code I used, I just pulled the skeleton of it out and rewrote it in a more generic way.

like image 128
Kelly Elton Avatar answered Apr 30 '26 18:04

Kelly Elton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!