django实现google第三方登录验证
时间: 2024-01-01 08:05:36 浏览: 35
要实现Google第三方登录验证,可以按照以下步骤:
1. 创建Google API项目并获取客户端ID和客户端密钥。
- 在 Google Cloud Console 中创建项目。
- 在“凭据”页面上创建OAuth 2.0客户端ID。
- 下载凭据并将其保存到项目中。
2. 安装必要的Python包:
```
pip install google-auth google-auth-oauthlib google-auth-httplib2
```
3. 在Django项目中,创建一个文件 `google_auth.py` 并添加以下代码:
```
from google.oauth2 import id_token
from google.auth.transport import requests
def validate_google_token(token):
try:
# Specify the CLIENT_ID of the app that accesses the backend:
idinfo = id_token.verify_oauth2_token(token, requests.Request(), 'CLIENT_ID')
# ID token is valid. Return the user's Google Account details.
return idinfo
except ValueError:
# Invalid token
return None
```
注意:在上述代码中,需要将字符串 `CLIENT_ID` 替换为你的Google客户端ID。
4. 创建视图函数,用于处理Google登录请求:
```
from django.shortcuts import redirect
from django.urls import reverse
def google_login(request):
# Create a state token to prevent request forgery.
# Store it in the session for later validation.
state = uuid.uuid4().hex
request.session['state'] = state
# Set the client ID, token state, and application name in the HTML while
# serving it.
google_auth_url = 'https://accounts.google.com/o/oauth2/auth?' \
'response_type=code&client_id={}&redirect_uri={}&' \
'scope=openid%20email%20profile&state={}'.format(
'CLIENT_ID',
request.build_absolute_uri(reverse('google_authenticate')),
state)
return redirect(google_auth_url)
```
注意:在上述代码中,需要将字符串 `CLIENT_ID` 替换为你的Google客户端ID。
5. 创建另一个视图函数,用于验证Google登录并返回用户信息:
```
def google_authenticate(request):
# Verify the state token
if request.GET.get('state') != request.session.get('state'):
return HttpResponseBadRequest('Invalid session state.')
# Exchange authorization code for access token
params = {
'code': request.GET.get('code'),
'client_id': 'CLIENT_ID',
'client_secret': 'CLIENT_SECRET',
'redirect_uri': request.build_absolute_uri(reverse('google_authenticate')),
'grant_type': 'authorization_code'
}
response = requests.post('https://oauth2.googleapis.com/token', data=params)
token_data = response.json()
# Validate and decode ID token
id_token = token_data.get('id_token')
idinfo = validate_google_token(id_token)
# Return user info
return JsonResponse({
'email': idinfo.get('email'),
'first_name': idinfo.get('given_name'),
'last_name': idinfo.get('family_name'),
'picture_url': idinfo.get('picture')
})
```
注意:在上述代码中,需要将字符串 `CLIENT_ID` 和 `CLIENT_SECRET` 替换为你的Google客户端ID和客户端密钥。
6. 在 `urls.py` 中添加以下路由:
```
from django.urls import path
from .views import google_login, google_authenticate
urlpatterns = [
path('google/login/', google_login, name='google_login'),
path('google/authenticate/', google_authenticate, name='google_authenticate'),
]
```
7. 在模板中添加登录按钮,点击该按钮将跳转到Google登录页面:
```
<a href="{% url 'google_login' %}">Log in with Google</a>
```
以上就是实现Django中Google第三方登录验证的步骤。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)