-
Notifications
You must be signed in to change notification settings - Fork 53
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement oauth2 authentication for SSO login from talk component (#310)
* implement sso login feature * format code
- Loading branch information
Showing
10 changed files
with
276 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
===================================================== | ||
Single Sign-On (SSO) Implementation with JWT and OAuth2 | ||
===================================================== | ||
|
||
Overview | ||
======== | ||
This document provides a step-by-step guide to implementing Single Sign-On (SSO) between the `ticket` and `talk` applications using JWT tokens and Django OAuth Toolkit. The configuration involves customizing the OAuth2 `AuthorizationView`, handling login processes to set JWT cookies, and ensuring a seamless SSO experience across applications. | ||
|
||
Pre-requisites | ||
============== | ||
- Django >= 3.11 | ||
- Django OAuth Toolkit | ||
- PyJWT | ||
- HTTPS configuration for secure cookie handling | ||
|
||
Step 1: Customize Authorization View | ||
==================================== | ||
To bypass the OAuth2 consent screen for trusted applications and automatically set a JWT cookie upon successful authorization, we override the `AuthorizationView`. | ||
|
||
src/pretix/control/views/auth.py | ||
|
||
|
||
Step 2: Update URL Configuration | ||
================================ | ||
Update the URL configuration to use the `CustomAuthorizationView`: | ||
|
||
src/pretix/control/urls.py | ||
|
||
Step 3: Modify Login View to Set JWT Cookie | ||
=========================================== | ||
In the `ticket` application, modify the `login` view to set a JWT cookie after successful authentication. | ||
|
||
Update `login` view in `src/pretix/control/views/auth.py`: | ||
|
||
|
||
Step 4: Security and Configuration | ||
================================== | ||
Ensure that all configurations are secure and appropriate for your environment: | ||
|
||
- Use `SECRET_KEY` in `settings.py` for JWT signing. | ||
|
||
Conclusion | ||
========== | ||
By following these steps, you can implement SSO using JWT and Django OAuth Toolkit between the `ticket` and `talk` applications. This configuration allows for seamless user authentication while maintaining a secure environment. Ensure to review and follow security best practices to protect user data and session integrity. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
55 changes: 55 additions & 0 deletions
55
src/pretix/api/migrations/0004_oauthapplication_allowed_origins_and_more.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
# Generated by Django 4.2.15 on 2024-08-30 08:15 | ||
|
||
from django.db import migrations, models | ||
import oauth2_provider.generators | ||
import oauth2_provider.models | ||
|
||
|
||
class Migration(migrations.Migration): | ||
|
||
dependencies = [ | ||
('pretixapi', '0003_oauthapplication_post_logout_redirect_uris_and_more'), | ||
] | ||
|
||
operations = [ | ||
migrations.AddField( | ||
model_name='oauthapplication', | ||
name='allowed_origins', | ||
field=models.TextField(default=''), | ||
), | ||
migrations.AddField( | ||
model_name='oauthapplication', | ||
name='hash_client_secret', | ||
field=models.BooleanField(default=True), | ||
), | ||
migrations.AlterField( | ||
model_name='apicall', | ||
name='id', | ||
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False), | ||
), | ||
migrations.AlterField( | ||
model_name='oauthaccesstoken', | ||
name='token', | ||
field=models.CharField(db_index=True, max_length=255, unique=True), | ||
), | ||
migrations.AlterField( | ||
model_name='oauthapplication', | ||
name='client_secret', | ||
field=oauth2_provider.models.ClientSecretField(db_index=True, default=oauth2_provider.generators.generate_client_secret, max_length=255), | ||
), | ||
migrations.AlterField( | ||
model_name='webhook', | ||
name='id', | ||
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False), | ||
), | ||
migrations.AlterField( | ||
model_name='webhookcall', | ||
name='id', | ||
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False), | ||
), | ||
migrations.AlterField( | ||
model_name='webhookeventlistener', | ||
name='id', | ||
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False), | ||
), | ||
] |
35 changes: 35 additions & 0 deletions
35
src/pretix/base/management/commands/create_oauth_application.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
import secrets | ||
|
||
from django.core.management.base import BaseCommand | ||
|
||
from pretix.api.models import OAuthApplication | ||
|
||
|
||
class Command(BaseCommand): | ||
help = "Create an OAuth2 Application for the Talk SSO Client" | ||
|
||
def handle(self, *args, **options): | ||
redirect_uris = input('Enter the redirect URI: ') # Get redirect URI from user input | ||
|
||
# Check if the application already exists based on redirect_uri | ||
if OAuthApplication.objects.filter(redirect_uris=redirect_uris).exists(): | ||
self.stdout.write(self.style.WARNING('OAuth2 Application with this redirect URI already exists.')) | ||
return | ||
|
||
# Create the OAuth2 Application | ||
application = OAuthApplication( | ||
name="Talk SSO Client", | ||
client_type=OAuthApplication.CLIENT_CONFIDENTIAL, | ||
authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE, | ||
redirect_uris=redirect_uris, | ||
user=None, # Set a specific user if you want this to be user-specific, else keep it None | ||
client_id=secrets.token_urlsafe(32), | ||
client_secret=secrets.token_urlsafe(64), | ||
hash_client_secret=False, | ||
skip_authorization=True, | ||
) | ||
application.save() | ||
|
||
self.stdout.write(self.style.SUCCESS('Successfully created OAuth2 Application')) | ||
self.stdout.write(f'Client ID: {application.client_id}') | ||
self.stdout.write(f'Client Secret: {application.client_secret}') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
from datetime import datetime, timedelta | ||
|
||
import jwt | ||
from django.conf import settings | ||
|
||
|
||
def generate_sso_token(user): | ||
""" | ||
Generate a JWT token for the user. | ||
@param user: User obj | ||
@return: jwt token | ||
""" | ||
if user and user.is_authenticated: | ||
jwt_payload = { | ||
'email': user.email, | ||
'name': user.get_full_name(), | ||
'is_active': user.is_active, | ||
'is_staff': user.is_staff, | ||
'locale': user.locale, | ||
'timezone': user.timezone, | ||
'exp': datetime.utcnow() + timedelta(hours=1), # Token expiration | ||
'iat': datetime.utcnow(), | ||
} | ||
jwt_token = jwt.encode(jwt_payload, settings.SECRET_KEY, algorithm='HS256') | ||
return jwt_token | ||
return None |
Oops, something went wrong.