add revoke
This commit is contained in:
@@ -6,8 +6,12 @@ from authlib.oauth2.rfc6749 import errors
|
||||
from authlib.oauth2.rfc6749.util import scope_to_list
|
||||
from aws_lambda_powertools import Logger
|
||||
from aws_lambda_powertools.event_handler.api_gateway import Router
|
||||
from aws_lambda_powertools.event_handler.exceptions import BadRequestError, ServiceError
|
||||
from layercake.dynamodb import DynamoDBPersistenceLayer, KeyPair
|
||||
from aws_lambda_powertools.event_handler.exceptions import (
|
||||
BadRequestError,
|
||||
ServiceError,
|
||||
UnauthorizedError,
|
||||
)
|
||||
from layercake.dynamodb import DynamoDBPersistenceLayer, KeyPair, SortKey
|
||||
|
||||
from boto3clients import dynamodb_client
|
||||
from config import ISSUER, JWT_ALGORITHM, JWT_SECRET, OAUTH2_TABLE
|
||||
@@ -15,7 +19,7 @@ from oauth2 import server
|
||||
|
||||
router = Router()
|
||||
logger = Logger(__name__)
|
||||
oauth2_layer = DynamoDBPersistenceLayer(OAUTH2_TABLE, dynamodb_client)
|
||||
dyn = DynamoDBPersistenceLayer(OAUTH2_TABLE, dynamodb_client)
|
||||
|
||||
|
||||
@router.get('/authorize')
|
||||
@@ -36,9 +40,8 @@ def authorize():
|
||||
client_scopes = set(scope_to_list(grant.client.scope))
|
||||
user_scopes = set(scope_to_list(session_scope)) if session_scope else set()
|
||||
|
||||
if not client_scopes.issubset(
|
||||
user_scopes | {'openid', 'email', 'profile', 'offline_access'}
|
||||
):
|
||||
# Deny authorization if user has no scopes matching the client request
|
||||
if not user_scopes & client_scopes:
|
||||
raise errors.InvalidScopeError(status_code=HTTPStatus.UNAUTHORIZED)
|
||||
|
||||
return server.create_authorization_response(
|
||||
@@ -69,15 +72,27 @@ def verify_session(session_id: str) -> tuple[str, str | None]:
|
||||
},
|
||||
)
|
||||
|
||||
oauth2_layer.collection.get_item(
|
||||
user = dyn.collection.get_items(
|
||||
KeyPair(
|
||||
pk='SESSION',
|
||||
sk=payload['sid'],
|
||||
rename_key='session',
|
||||
)
|
||||
+ KeyPair(
|
||||
pk=payload['sub'],
|
||||
sk=SortKey(
|
||||
sk='SCOPE',
|
||||
path_spec='scope',
|
||||
rename_key='scope',
|
||||
),
|
||||
),
|
||||
exc_cls=SessionRevokedError,
|
||||
flatten_top=False,
|
||||
)
|
||||
|
||||
return payload['sub'], payload.get('scope')
|
||||
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]:
|
||||
@@ -94,6 +109,4 @@ def _parse_cookies(cookies: list[str] | None) -> dict[str, str]:
|
||||
return parsed_cookies
|
||||
|
||||
|
||||
class SessionRevokedError(BadRequestError):
|
||||
def __init__(self, *_):
|
||||
super().__init__('Session revoked')
|
||||
class SessionRevokedError(UnauthorizedError): ...
|
||||
|
||||
@@ -11,6 +11,7 @@ def openid_configuration():
|
||||
'issuer': ISSUER,
|
||||
'authorization_endpoint': f'{ISSUER}/authorize',
|
||||
'token_endpoint': f'{ISSUER}/token',
|
||||
'revocation_endpoint': f'{ISSUER}/revoke',
|
||||
'userinfo_endpoint': f'{ISSUER}/userinfo',
|
||||
'jwks_uri': f'{ISSUER}/jwks.json',
|
||||
'scopes_supported': OAUTH2_SCOPES_SUPPORTED.split(),
|
||||
|
||||
13
id.saladeaula.digital/app/routes/revoke.py
Normal file
13
id.saladeaula.digital/app/routes/revoke.py
Normal file
@@ -0,0 +1,13 @@
|
||||
from aws_lambda_powertools.event_handler.api_gateway import Router
|
||||
|
||||
from oauth2 import RevocationEndpoint, server
|
||||
|
||||
router = Router()
|
||||
|
||||
|
||||
@router.post('/revoke')
|
||||
def revoke():
|
||||
return server.create_endpoint_response(
|
||||
RevocationEndpoint.ENDPOINT_NAME,
|
||||
router.current_event,
|
||||
)
|
||||
@@ -15,10 +15,16 @@ from layercake.dynamodb import DynamoDBPersistenceLayer, KeyPair, SortKey
|
||||
from passlib.hash import pbkdf2_sha256
|
||||
|
||||
from boto3clients import dynamodb_client
|
||||
from config import ISSUER, JWT_ALGORITHM, JWT_EXP_SECONDS, JWT_SECRET, OAUTH2_TABLE
|
||||
from config import (
|
||||
ISSUER,
|
||||
JWT_ALGORITHM,
|
||||
JWT_SECRET,
|
||||
OAUTH2_REFRESH_TOKEN_EXPIRES_IN,
|
||||
OAUTH2_TABLE,
|
||||
)
|
||||
|
||||
router = Router()
|
||||
oauth2_layer = DynamoDBPersistenceLayer(OAUTH2_TABLE, dynamodb_client)
|
||||
dyn = DynamoDBPersistenceLayer(OAUTH2_TABLE, dynamodb_client)
|
||||
|
||||
|
||||
@router.post('/session')
|
||||
@@ -26,11 +32,7 @@ def session(
|
||||
username: Annotated[str, Body()],
|
||||
password: Annotated[str, Body()],
|
||||
):
|
||||
(
|
||||
user_id,
|
||||
password_hash,
|
||||
scope,
|
||||
) = _get_user(username)
|
||||
user_id, password_hash = _get_user(username)
|
||||
|
||||
if not pbkdf2_sha256.verify(password, password_hash):
|
||||
raise ForbiddenError('Invalid credentials')
|
||||
@@ -40,28 +42,27 @@ def session(
|
||||
cookies=[
|
||||
Cookie(
|
||||
name='session_id',
|
||||
value=new_session(user_id, scope),
|
||||
value=new_session(user_id),
|
||||
http_only=True,
|
||||
secure=True,
|
||||
same_site=None,
|
||||
max_age=JWT_EXP_SECONDS,
|
||||
max_age=OAUTH2_REFRESH_TOKEN_EXPIRES_IN,
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def _get_user(username: str) -> tuple[str, str, str | None]:
|
||||
def _get_user(username: str) -> tuple[str, str]:
|
||||
sk = SortKey(username, path_spec='user_id')
|
||||
user = oauth2_layer.collection.get_items(
|
||||
user = dyn.collection.get_items(
|
||||
KeyPair(pk='email', sk=sk, rename_key=sk.path_spec)
|
||||
+ KeyPair(pk='cpf', sk=sk, rename_key=sk.path_spec),
|
||||
flatten_top=False,
|
||||
)
|
||||
|
||||
if not user:
|
||||
raise UserNotFoundError()
|
||||
|
||||
userdata = oauth2_layer.collection.get_items(
|
||||
password = dyn.collection.get_item(
|
||||
KeyPair(
|
||||
pk=user['user_id'],
|
||||
sk=SortKey(
|
||||
@@ -69,46 +70,34 @@ def _get_user(username: str) -> tuple[str, str, str | None]:
|
||||
path_spec='hash',
|
||||
rename_key='password',
|
||||
),
|
||||
)
|
||||
+ KeyPair(
|
||||
pk=user['user_id'],
|
||||
sk=SortKey(
|
||||
sk='SCOPE',
|
||||
path_spec='scope',
|
||||
rename_key='scope',
|
||||
),
|
||||
),
|
||||
flatten_top=False,
|
||||
exc_cls=UserNotFoundError,
|
||||
)
|
||||
|
||||
if not userdata:
|
||||
raise UserNotFoundError()
|
||||
|
||||
return user['user_id'], userdata['password'], userdata.get('scope')
|
||||
return user['user_id'], password
|
||||
|
||||
|
||||
def new_session(sub: str, scope: str | None) -> str:
|
||||
def new_session(sub: str) -> str:
|
||||
session_id = str(uuid4())
|
||||
now_ = now()
|
||||
sid = str(uuid4())
|
||||
exp = ttl(start_dt=now_, seconds=JWT_EXP_SECONDS)
|
||||
exp = ttl(start_dt=now_, seconds=OAUTH2_REFRESH_TOKEN_EXPIRES_IN)
|
||||
token = jwt.encode(
|
||||
{
|
||||
'sid': sid,
|
||||
'sid': session_id,
|
||||
'sub': sub,
|
||||
'iss': ISSUER,
|
||||
'iat': int(now_.timestamp()),
|
||||
'exp': exp,
|
||||
'scope': scope,
|
||||
},
|
||||
JWT_SECRET,
|
||||
algorithm=JWT_ALGORITHM,
|
||||
)
|
||||
|
||||
with oauth2_layer.transact_writer() as transact:
|
||||
with dyn.transact_writer() as transact:
|
||||
transact.put(
|
||||
item={
|
||||
'id': 'SESSION',
|
||||
'sk': sid,
|
||||
'sk': session_id,
|
||||
'user_id': sub,
|
||||
'ttl': exp,
|
||||
'created_at': now_,
|
||||
@@ -117,7 +106,7 @@ def new_session(sub: str, scope: str | None) -> str:
|
||||
transact.put(
|
||||
item={
|
||||
'id': sub,
|
||||
'sk': f'SESSION#{sid}',
|
||||
'sk': f'SESSION#{session_id}',
|
||||
'ttl': exp,
|
||||
'created_at': now_,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user