2014-01-08 69 views
0

如何使用django在您的网页上实现Google登录?如果您只需要实现登录并使用谷歌登录在您的网络应用程序中授权用户,而无需使用google + signin javascript按钮。这是如何完成的。如何在django中实现Google登录

回答

0

下面是在django中google登录的基本实现。这只是为了学习的目的。它会提供执行谷歌登录的步骤。

这是的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> 

在urls.py的urlpatters是如下

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 \基本上重定向到https://accounts.google.com/o/oauth2/auth用所需参数从谷歌

结果oauth通过loginverif视图。以下是loginverif视图。

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}) 

要获得完整的理解请到通 https://developers.google.com/accounts/docs/OAuth2Login#validatinganidtoken

&

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

希望这有助于!