Question

How to implement google login on your webpage using django? If you need to implement just the login and authorize the user in your web apps using google login without using there google+signin javascript button. Here is how it can be done.

Was it helpful?

Solution 2

Below is a basic implementation for google login in django. This is just for learning purpose.It would provide the steps of implementing google login.

This is login.html

<html>
<head>
    <title>Login Page</title>
</head>
<body>

<form action=/mylogin/ method = get>
    <input type="submit" value="Go to Google">
</form>

 </body>
</html>

The urlpatters in urls.py is as below

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'juicy.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),
    url(r'^login/','juicy.views.login'),
    url(r'^loginverif/','juicy.views.loginverif'),
       url(r'^mylogin/',RedirectView.as_view(permanent=False,url="https://accounts.google.com/o/oauth2/auth?redirect_uri=http://localhost:8000/loginverif&response_type=code&client_id=XXXXXXXXX-o0ovvb6ihdc8asdcuuc3nib1e05l3rha.apps.googleusercontent.com&scope=https://www.googleapis.com/auth/plus.login")),

)

\mylogin\ basically redirects to https://accounts.google.com/o/oauth2/auth with required parameters

the results from google oauth is passed loginverif view. Below is the loginverif view.

def loginverif(request):
    if request.method =="GET":
        gcode = request.GET['code']
        client_id='XXXXXXX-o0ovvb6ihdc8asdcuuc3nib1e05l3rha.apps.googleusercontent.com'
        redirect_uri='http://localhost:8000/loginverif'
        grant_type='authorization_code'
        client_secret='XXXXXXXX'
        post_data = [('code',gcode),('client_id',client_id),('redirect_uri',redirect_uri),('grant_type',grant_type),('client_secret',client_secret)]     # a sequence of two element tuples
        result = urllib2.urlopen('https://accounts.google.com/o/oauth2/token', urllib.urlencode(post_data))
        content = result.read()
        dct = json.loads(content)
        access_token = dct['access_token']
        headers = { 'Authorization':'OAuth %s'% access_token }
        req = urllib2.Request('https://www.googleapis.com/plus/v1/people/me',  headers=headers)
        result2 = urllib2.urlopen(req)
        content = result2.read()
        dct = json.loads(content)
        person_dict = dict()
        person_dict['id'] = dct['id']
        person_dict['personname']=dct['displayName']
    return render_to_response('signedhome.html',{'dictionary':person_dict})

To get the complete understanding please go thru https://developers.google.com/accounts/docs/OAuth2Login#validatinganidtoken

&

https://developers.google.com/oauthplayground/

Hope this helps!

OTHER TIPS

You should use django-social-auth that will help you to achieve more.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top