Google OAuth Implementation for ASP.
NET Core
1. Create a Project on Google Cloud Platform
1. Go to the Google Cloud Console (https://console.cloud.google.com/).
2. Create a new project or select an existing one.
3. Navigate to APIs & Services > Credentials.
4. Click Create Credentials and choose OAuth 2.0 Client IDs.
- Set the application type to Web application.
- Add the following:
- Authorized redirect URIs: http://127.0.0.1:8000/accounts/google/login/callback/
- Authorized JavaScript origins: http://127.0.0.1:8000
5. Note the Client ID and Client Secret.
2. Install Required Python Packages
Install Django and social-auth-app-django for integrating Google OAuth:
pip install django
pip install social-auth-app-django
3. Update Django Settings
In the settings.py file, configure the authentication backends and Google OAuth keys:
AUTHENTICATION_BACKENDS = [
'social_core.backends.google.GoogleOAuth2',
'django.contrib.auth.backends.ModelBackend',
]
Google OAuth Implementation for ASP.NET Core
INSTALLED_APPS += ['social_django']
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'YOUR_CLIENT_ID'
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'YOUR_CLIENT_SECRET'
LOGIN_URL = '/accounts/login/'
LOGIN_REDIRECT_URL = '/'
4. Update URL Patterns
In your urls.py file, include the URLs for the authentication process:
from django.urls import path, include
urlpatterns = [
path('accounts/', include('social_django.urls', namespace='social')),
path('admin/', admin.site.urls),
5. Add Middleware
Ensure the following middleware is included in settings.py:
MIDDLEWARE += [
'social_django.middleware.SocialAuthExceptionMiddleware',
]
Google OAuth Implementation for ASP.NET Core
6. Run Migrations
Run the necessary migrations to set up the database tables for social authentication:
python manage.py makemigrations
python manage.py migrate
7. Add Login and Logout Links
In your templates, add links to login and logout:
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}!</p>
<a href="{% url 'logout' %}">Logout</a>
{% else %}
<a href="{% url 'social:begin' 'google-oauth2' %}">Login with Google</a>
{% endif %}
8. Run and Test the Application
1. Start the Django development server:
python manage.py runserver
2. Open your browser and navigate to http://127.0.0.1:8000/accounts/login/.
3. Authenticate using Google and verify that you are redirected back to your application.