更新时间:2023-12-03 15:43:46
经过很长时间,浪费了很多时间,我放弃了 OAuth2,因为它很难配置,我只需要登录一个user in. 下面的代码应该可以帮助需要做类似事情的人,并且可以自定义.我所做的只是按照有关形成 url 的说明进行操作 -> https://developers.google.com/accounts/docs/OAuth2Login
After a long time, and many hours spent gone to waste, I gave up with OAuth2 since it is difficult to configure, and all I need is to log a user in. The following code should help someone who needs to do something similar, and can be customized. All I did was follow the instructions on forming the urls and such here -> https://developers.google.com/accounts/docs/OAuth2Login
我创建了两个视图(对于不使用 Django 的任何人 - 页面)并创建了第一个的链接:这个页面我调用了 login/google 并从登录页面创建了一个链接.
I made two views (for anyone not using Django - pages) and made a link to the first one: This page I called login/google and made a link to it from the login page.
def google_login(request):
token_request_uri = "https://accounts.google.com/o/oauth2/auth"
response_type = "code"
client_id = XXXXXX-your_client_id
redirect_uri = "http://mysite/login/google/auth"
scope = "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email"
url = "{token_request_uri}?response_type={response_type}&client_id={client_id}&redirect_uri={redirect_uri}&scope={scope}".format(
token_request_uri = token_request_uri,
response_type = response_type,
client_id = client_id,
redirect_uri = redirect_uri,
scope = scope)
return HttpResponseRedirect(url)
上面的代码重定向到了第二个页面(这个页面必须在google app定义中定义为重定向uri).我称这个页面为 login/google/auth:
The above code redirected to the second page (this page must be defined as a redirect uri in the google app definitions). I called this page login/google/auth:
def google_authenticate(request):
parser = Http()
login_failed_url = '/'
if 'error' in request.GET or 'code' not in request.GET:
return HttpResponseRedirect('{loginfailed}'.format(loginfailed = login_failed_url))
access_token_uri = 'https://accounts.google.com/o/oauth2/token'
redirect_uri = "http://mysite/login/google/auth"
params = urllib.urlencode({
'code':request.GET['code'],
'redirect_uri':redirect_uri,
'client_id':XXXXX_your_google_key,
'client_secret':XXXXX_your_google_secret,
'grant_type':'authorization_code'
})
headers={'content-type':'application/x-www-form-urlencoded'}
resp, content = parser.request(access_token_uri, method = 'POST', body = params, headers = headers)
token_data = jsonDecode(content)
resp, content = parser.request("https://www.googleapis.com/oauth2/v1/userinfo?access_token={accessToken}".format(accessToken=token_data['access_token']))
#this gets the google profile!!
google_profile = jsonDecode(content)
#log the user in-->
#HERE YOU LOG THE USER IN, OR ANYTHING ELSE YOU WANT
#THEN REDIRECT TO PROTECTED PAGE
return HttpResponseRedirect('/dashboard')
我真的希望这可以帮助那里的人们,并为他们节省我浪费的时间.非常欢迎对代码的评论!
I really hope this helps people out there, and saves them the hours I wasted. Comments on the code are more than welcome!