Skip to content

Instantly share code, notes, and snippets.

@jpic
Created July 23, 2026 13:28
Show Gist options
  • Select an option

  • Save jpic/fe21f1e38267f81eeafd0980bced6f4d to your computer and use it in GitHub Desktop.

Select an option

Save jpic/fe21f1e38267f81eeafd0980bced6f4d to your computer and use it in GitHub Desktop.
Oauth
# ton_app/oauth_jwt.py
import jwt
from datetime import datetime, timedelta, timezone
from django.conf import settings
from oauthlib.common import generate_token
def jwt_token_generator(request, refresh_token=False):
now = datetime.now(timezone.utc)
expires_in = settings.OAUTH2_PROVIDER.get("ACCESS_TOKEN_EXPIRE_SECONDS", 36000)
exp = now + timedelta(seconds=expires_in)
payload = {
"iss": getattr(settings, "JWT_ISSUER", "http://localhost:8000"),
"iat": int(now.timestamp()),
"exp": int(exp.timestamp()),
"jti": generate_token(),
"token_type": "refresh" if refresh_token else "access",
}
if getattr(request, "user", None) and request.user.is_authenticated:
payload["sub"] = str(request.user.pk)
if getattr(request, "client", None):
payload["client_id"] = request.client.client_id
payload["aud"] = request.client.client_id
if getattr(request, "scopes", None):
payload["scope"] = " ".join(request.scopes)
secret = getattr(settings, "JWT_SECRET_KEY", settings.SECRET_KEY)
algorithm = getattr(settings, "JWT_ALGORITHM", "HS256")
token = jwt.encode(payload, secret, algorithm=algorithm)
return token if isinstance(token, str) else token.decode("utf-8")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment