Получение информации о данных пользователя после аутентификации с помощью OAuth 2.0
Как получить информацию о данных пользователя после аутентификации с помощью Django и Google OAuth2?
HTML
<button>
<a href="{% provider_login_url "google" %}">
<div class="connexion-type">
<div class="connexion-type-svg">
<svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="100" height="100" viewBox="0 0 48 48">
<!-- SVG paths -->
</svg>
</div>
<div class="connexion-type-content">Login via Gmail</div>
</div>
</a>
</button>
</div>
** Django View:**
@login_required
def redirect_google_provider(request):
print("Access to redirect_google_provider")
if 'code' in request.GET:
# Extract the authorization code
code = request.GET['code']
# Debug
print(f"Code is: {code}")
# Exchange the authorization code for an access token
token_url = 'https://oauth2.googleapis.com/token'
client_id = 'YOUR_GOOGLE_CLIENT_ID'
client_secret = 'YOUR_GOOGLE_CLIENT_SECRET'
redirect_uri = 'YOUR_REDIRECT_URI'
data = {
'code': code,
'client_id': client_id,
'client_secret': client_secret,
'redirect_uri': redirect_uri,
'grant_type': 'authorization_code',
}
response = requests.post(token_url, data=data)
token_data = response.json()
access_token = token_data.get('access_token')
# Retrieve user information from Google API
if access_token:
user_info_url = 'https://www.googleapis.com/oauth2/v3/userinfo'
headers = {'Authorization': f'Bearer {access_token}'}
user_info_response = requests.get(user_info_url, headers=headers)
user_info = user_info_response.json()
email = user_info.get('email')
# Check if the user exists in the system
if email:
user, created = User.objects.get_or_create(username=email, email=email)
if created:
# New user, save additional information if needed
user.save()
# Log the user in
login(request, user)
return HttpResponseRedirect('/home/') # Redirect to home page after successful login
# If code is not present or user could not be logged in, redirect to login page
return render(request, '../templates/users/login.html')
Settings.py
LOGIN_REDIRECT_URL = 'redirect_google_provider' # Redirect after authentication
Журналы
[13/May/2024 05:00:17] "GET /accounts/google/login/ HTTP/1.1" 302 0 [13/May/2024 05:00:21] "GET /accounts/google/login/callback/? state=oirQ0xHHGNoRNQ33&code=234%2F0AdLIrYfk7gpUs678HJOjkhshdjjsJVTFpqjpAxZ4iMWttcjBzG8XhCPnijh_e_R8ntZ8jYIEsshY8ng-w&scope=profile+https%3A%2ddF%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile HTTP/1.1" 302 0 [13/May/2024 05:00:21] "GET /users/redirect_google_provider HTTP/1.1" 200 15063
Как захватить
"GET /accounts/google/login/callback/?state=oirQ0xHHGNoRNQ33&code=234%2F0AdLIrYfk7gpUs678HJOjkhshdjjsJVTFpqjpAxZ4iMWttcjBzG8XhCPnijh_e_R8ntZ8jYIEsshY8ng-w&scope=profile+https%3A%2ddF%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile HTTP/1.1" 302 0
перед тем, как передать его моему представлению