The before code shows a microservice directly validating user credentials, which duplicates authentication logic and is insecure. The after code shows the microservice validating an OAuth 2.0 JWT access token issued by an authorization server, checking scopes for authorization. This centralizes auth and improves security.
### Before: Microservice directly checks user credentials (bad practice)
class Microservice:
def handle_request(self, user_credentials):
if not self.validate_user(user_credentials):
return "Unauthorized"
return "Data for user"
def validate_user(self, creds):
# Naive check, duplicates auth logic
return creds == "valid_password"
### After: Microservice validates OAuth 2.0 access token
import jwt
class Microservice:
AUTH_SERVER_PUBLIC_KEY = "<public_key_here>"
def handle_request(self, access_token):
try:
payload = jwt.decode(access_token, self.AUTH_SERVER_PUBLIC_KEY, algorithms=["RS256"])
if "read:data" in payload.get("scopes", []):
return "Data for user"
else:
return "Forbidden: insufficient scope"
except jwt.ExpiredSignatureError:
return "Unauthorized: token expired"
except jwt.InvalidTokenError:
return "Unauthorized: invalid token"