update session
This commit is contained in:
@@ -3,8 +3,20 @@ import os
|
||||
ISSUER: str = os.getenv('ISSUER') # type: ignore
|
||||
|
||||
OAUTH2_TABLE: str = os.getenv('OAUTH2_TABLE') # type: ignore
|
||||
OAUTH2_SCOPES_SUPPORTED: str = os.getenv('OAUTH2_SCOPES_SUPPORTED', '')
|
||||
OAUTH2_REFRESH_TOKEN_EXPIRES_IN = 86_400 * 7 # 7 days
|
||||
OAUTH2_SCOPES_SUPPORTED: list[str] = [
|
||||
'openid',
|
||||
'profile',
|
||||
'email',
|
||||
'offline_access',
|
||||
'read:users',
|
||||
'write:users',
|
||||
'read:enrollments',
|
||||
'write:enrollments',
|
||||
'read:orders',
|
||||
'write:orders',
|
||||
'read:courses',
|
||||
'write:courses',
|
||||
]
|
||||
|
||||
SESSION_SECRET: str = os.environ.get('SESSION_SECRET') # type: ignore
|
||||
SESSION_EXPIRES_IN = 86400 * 30 # 30 days
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import os
|
||||
from dataclasses import asdict
|
||||
|
||||
import authlib.oauth2 as oauth2
|
||||
@@ -17,24 +16,19 @@ from config import OAUTH2_REFRESH_TOKEN_EXPIRES_IN
|
||||
from .client import OAuth2Client
|
||||
from .requests import APIGatewayJsonRequest, APIGatewayOAuth2Request
|
||||
|
||||
OAUTH2_SCOPES_SUPPORTED = os.getenv('OAUTH2_SCOPES_SUPPORTED')
|
||||
|
||||
logger = Logger(__name__)
|
||||
|
||||
|
||||
class AuthorizationServer(oauth2.AuthorizationServer):
|
||||
def __init__(
|
||||
self,
|
||||
scopes_supported: list[str],
|
||||
*,
|
||||
persistence_layer: DynamoDBPersistenceLayer,
|
||||
) -> None:
|
||||
super().__init__(scopes_supported=scopes_supported)
|
||||
self._persistence_layer = persistence_layer
|
||||
|
||||
if OAUTH2_SCOPES_SUPPORTED:
|
||||
super().__init__(
|
||||
scopes_supported=set(OAUTH2_SCOPES_SUPPORTED.split()),
|
||||
)
|
||||
|
||||
def save_token(
|
||||
self,
|
||||
token: dict,
|
||||
|
||||
@@ -49,7 +49,7 @@ class APIGatewayOAuth2Request(requests.OAuth2Request):
|
||||
super().__init__(
|
||||
request.request_context.http.method,
|
||||
uri,
|
||||
request.headers,
|
||||
headers=request.headers,
|
||||
)
|
||||
self._request = request
|
||||
self.payload = APIGatewayOAuth2Payload(request)
|
||||
|
||||
@@ -3,6 +3,7 @@ from authlib.common.urls import add_params_to_uri
|
||||
from authlib.jose import JsonWebKey
|
||||
from authlib.oauth2 import OAuth2Request, rfc7009, rfc9207
|
||||
from authlib.oauth2.rfc6749 import ClientMixin, TokenMixin, grants
|
||||
from authlib.oauth2.rfc6749.hooks import hooked
|
||||
from authlib.oauth2.rfc6750 import BearerTokenGenerator
|
||||
from authlib.oauth2.rfc7636 import CodeChallenge
|
||||
from authlib.oauth2.rfc9068 import JWTBearerTokenGenerator as JWTBearerTokenGenerator_
|
||||
@@ -21,7 +22,7 @@ from layercake.dynamodb import (
|
||||
from layercake.funcs import omit, pick
|
||||
|
||||
from boto3clients import dynamodb_client
|
||||
from config import ISSUER, OAUTH2_TABLE
|
||||
from config import ISSUER, OAUTH2_SCOPES_SUPPORTED, OAUTH2_TABLE
|
||||
from integrations.apigateway_oauth2.authorization_server import (
|
||||
AuthorizationServer,
|
||||
)
|
||||
@@ -64,6 +65,8 @@ class OpenIDCode(OpenIDCode_):
|
||||
}
|
||||
|
||||
def generate_user_info(self, user: User, scope: str) -> UserInfo:
|
||||
print(scope)
|
||||
print('--' * 100)
|
||||
return UserInfo(
|
||||
sub=user.id,
|
||||
name=user.name,
|
||||
@@ -173,6 +176,20 @@ class AuthorizationCodeGrant(grants.AuthorizationCodeGrant):
|
||||
return User(**pick(('id', 'name', 'email', 'email_verified'), user))
|
||||
|
||||
|
||||
class TokenExchangeGrant(grants.BaseGrant):
|
||||
GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange'
|
||||
|
||||
TOKEN_ENDPOINT_AUTH_METHODS = ['client_secret_basic', 'client_secret_post']
|
||||
|
||||
@hooked
|
||||
def validate_token_request(self):
|
||||
raise NotImplementedError()
|
||||
|
||||
@hooked
|
||||
def create_token_response(self):
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
class RefreshTokenNotFoundError(NotFoundError):
|
||||
def __init__(self, *_):
|
||||
super().__init__('Refresh token not found')
|
||||
@@ -337,7 +354,10 @@ class JWTBearerTokenGenerator(JWTBearerTokenGenerator_):
|
||||
}
|
||||
|
||||
|
||||
server = AuthorizationServer(persistence_layer=dyn)
|
||||
server = AuthorizationServer(
|
||||
persistence_layer=dyn,
|
||||
scopes_supported=OAUTH2_SCOPES_SUPPORTED,
|
||||
)
|
||||
server.register_grant(
|
||||
AuthorizationCodeGrant,
|
||||
[
|
||||
@@ -353,6 +373,7 @@ server.register_token_generator(
|
||||
expires_generator=expires_in,
|
||||
),
|
||||
)
|
||||
server.register_grant(TokenExchangeGrant)
|
||||
server.register_grant(RefreshTokenGrant)
|
||||
server.register_endpoint(RevocationEndpoint)
|
||||
server.register_extension(IssuerParameter())
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
from http.cookies import SimpleCookie
|
||||
|
||||
import jwt
|
||||
from authlib.oauth2.rfc6749 import errors
|
||||
from authlib.oauth2.rfc6749.util import scope_to_list
|
||||
from aws_lambda_powertools import Logger
|
||||
@@ -9,12 +8,12 @@ from aws_lambda_powertools.event_handler.exceptions import (
|
||||
BadRequestError,
|
||||
ForbiddenError,
|
||||
ServiceError,
|
||||
UnauthorizedError,
|
||||
)
|
||||
from joserfc.errors import JoseError
|
||||
from layercake.dynamodb import DynamoDBPersistenceLayer, KeyPair, SortKey
|
||||
|
||||
from boto3clients import dynamodb_client
|
||||
from config import ISSUER, OAUTH2_TABLE, SESSION_SECRET
|
||||
from config import OAUTH2_TABLE
|
||||
from oauth2 import server
|
||||
|
||||
router = Router()
|
||||
@@ -26,19 +25,24 @@ dyn = DynamoDBPersistenceLayer(OAUTH2_TABLE, dynamodb_client)
|
||||
def authorize():
|
||||
current_event = router.current_event
|
||||
cookies = _parse_cookies(current_event.get('cookies', []))
|
||||
session_id = cookies.get('session_id')
|
||||
session = cookies.get('__session')
|
||||
|
||||
if not session_id:
|
||||
raise BadRequestError('Missing session_id')
|
||||
if not session:
|
||||
raise BadRequestError('Missing session')
|
||||
|
||||
try:
|
||||
sub, session_scope = verify_session(session_id)
|
||||
sid, sub = session.split(':')
|
||||
# Raise if session is not found
|
||||
dyn.collection.get_item(
|
||||
KeyPair('SESSION', sid),
|
||||
exc_cls=InvalidSession,
|
||||
)
|
||||
grant = server.get_consent_grant(
|
||||
request=router.current_event,
|
||||
end_user=sub,
|
||||
)
|
||||
user_scopes = _user_scopes(sub)
|
||||
client_scopes = set(scope_to_list(grant.client.scope))
|
||||
user_scopes = set(scope_to_list(session_scope)) if session_scope else set()
|
||||
|
||||
# Deny authorization if user lacks scopes requested by client
|
||||
if not client_scopes.issubset(user_scopes):
|
||||
@@ -49,7 +53,7 @@ def authorize():
|
||||
grant_user=sub,
|
||||
grant=grant,
|
||||
)
|
||||
except jwt.exceptions.InvalidTokenError as err:
|
||||
except JoseError as err:
|
||||
logger.exception(err)
|
||||
raise BadRequestError(str(err))
|
||||
except errors.OAuth2Error as err:
|
||||
@@ -60,39 +64,19 @@ def authorize():
|
||||
)
|
||||
|
||||
|
||||
def verify_session(session_id: str) -> tuple[str, str | None]:
|
||||
payload = jwt.decode(
|
||||
session_id,
|
||||
SESSION_SECRET,
|
||||
algorithms=['HS256'],
|
||||
issuer=ISSUER,
|
||||
options={
|
||||
'require': ['exp', 'sub', 'iss', 'sid'],
|
||||
},
|
||||
)
|
||||
|
||||
user = dyn.collection.get_items(
|
||||
KeyPair(
|
||||
pk='SESSION',
|
||||
sk=payload['sid'],
|
||||
rename_key='session',
|
||||
def _user_scopes(sub: str) -> set:
|
||||
return set(
|
||||
scope_to_list(
|
||||
dyn.collection.get_item(
|
||||
KeyPair(
|
||||
pk=sub,
|
||||
sk=SortKey(sk='SCOPE', path_spec='scope'),
|
||||
),
|
||||
exc_cls=BadRequestError,
|
||||
)
|
||||
)
|
||||
+ KeyPair(
|
||||
pk=payload['sub'],
|
||||
sk=SortKey(
|
||||
sk='SCOPE',
|
||||
path_spec='scope',
|
||||
rename_key='scope',
|
||||
),
|
||||
),
|
||||
flatten_top=False,
|
||||
)
|
||||
|
||||
if 'session' not in user:
|
||||
raise SessionRevokedError('Session revoked')
|
||||
|
||||
return payload['sub'], user.get('scope')
|
||||
|
||||
|
||||
def _parse_cookies(cookies: list[str] | None) -> dict[str, str]:
|
||||
parsed_cookies = {}
|
||||
@@ -108,4 +92,4 @@ def _parse_cookies(cookies: list[str] | None) -> dict[str, str]:
|
||||
return parsed_cookies
|
||||
|
||||
|
||||
class SessionRevokedError(UnauthorizedError): ...
|
||||
class InvalidSession(BadRequestError): ...
|
||||
|
||||
@@ -3,7 +3,6 @@ from typing import Annotated
|
||||
from uuid import uuid4
|
||||
|
||||
import boto3
|
||||
import jwt
|
||||
from aws_lambda_powertools.event_handler import (
|
||||
Response,
|
||||
)
|
||||
@@ -17,10 +16,8 @@ from passlib.hash import pbkdf2_sha256
|
||||
|
||||
from boto3clients import dynamodb_client
|
||||
from config import (
|
||||
ISSUER,
|
||||
OAUTH2_TABLE,
|
||||
SESSION_EXPIRES_IN,
|
||||
SESSION_SECRET,
|
||||
)
|
||||
|
||||
router = Router()
|
||||
@@ -45,7 +42,7 @@ def session(
|
||||
status_code=HTTPStatus.OK,
|
||||
cookies=[
|
||||
Cookie(
|
||||
name='session_id',
|
||||
name='__session',
|
||||
value=new_session(user_id),
|
||||
http_only=True,
|
||||
secure=True,
|
||||
@@ -127,26 +124,15 @@ def _get_idp_user(
|
||||
|
||||
|
||||
def new_session(sub: str) -> str:
|
||||
session_id = str(uuid4())
|
||||
sid = str(uuid4())
|
||||
now_ = now()
|
||||
exp = ttl(start_dt=now_, seconds=SESSION_EXPIRES_IN)
|
||||
token = jwt.encode(
|
||||
{
|
||||
'sid': session_id,
|
||||
'sub': sub,
|
||||
'iss': ISSUER,
|
||||
'iat': int(now_.timestamp()),
|
||||
'exp': exp,
|
||||
},
|
||||
SESSION_SECRET,
|
||||
algorithm='HS256',
|
||||
)
|
||||
|
||||
with dyn.transact_writer() as transact:
|
||||
transact.put(
|
||||
item={
|
||||
'id': 'SESSION',
|
||||
'sk': session_id,
|
||||
'sk': sid,
|
||||
'user_id': sub,
|
||||
'ttl': exp,
|
||||
'created_at': now_,
|
||||
@@ -155,13 +141,13 @@ def new_session(sub: str) -> str:
|
||||
transact.put(
|
||||
item={
|
||||
'id': sub,
|
||||
'sk': f'SESSION#{session_id}',
|
||||
'sk': f'SESSION#{sid}',
|
||||
'ttl': exp,
|
||||
'created_at': now_,
|
||||
}
|
||||
)
|
||||
|
||||
return token
|
||||
return f'{sid}:{sub}'
|
||||
|
||||
|
||||
class UserNotFoundError(NotFoundError):
|
||||
|
||||
Reference in New Issue
Block a user