Skip to content

Commit

Permalink
add JWT token authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
jameshawkes committed Mar 15, 2024
1 parent 6f7dc4f commit d97947b
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 11 deletions.
2 changes: 1 addition & 1 deletion polytope_server/common/authentication/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def name(self) -> str:
"plain": "PlainAuthentication",
"keycloak": "KeycloakAuthentication",
"federation": "FederationAuthentication",
"jwt" : "JWTBearerAuthentication",
"jwt" : "JWTAuthentication",
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,10 @@
from ..auth import User
from ..caching import cache
from . import authentication
from ..exceptions import ForbiddenRequest


class JWTBearerAuthentication(authentication.Authentication):
class JWTAuthentication(authentication.Authentication):
def __init__(self, name, realm, config):
self.config = config

Expand All @@ -48,16 +49,21 @@ def get_certs(self):

@cache(lifetime=120)
def authenticate(self, credentials: str) -> User:
certs = self.get_certs()
decoded_token = jwt.decode(token=credentials,
algorithms=jwt.get_unverified_header(credentials).get('alg'),
key=certs
)

user = User(decoded_token["sub"], self.realm())
try:
certs = self.get_certs()
decoded_token = jwt.decode(token=credentials,
algorithms=jwt.get_unverified_header(credentials).get('alg'),
key=certs
)

logging.debug("Found user {} from decoded JWT".format(user))
user = User(decoded_token["sub"], self.realm())

logging.info("Found user {} from decoded JWT".format(user))
except Exception as e:
logging.info("Failed to authenticate user from JWT")
logging.info(e)
raise ForbiddenRequest("Credentials could not be unpacked")
return user


Expand Down
4 changes: 2 additions & 2 deletions polytope_server/common/datasource/mars.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,13 +182,13 @@ def make_env(self, request):
logging.info("Overriding MARS_USER_EMAIL with {}".format(self.override_mars_email))
mars_user = self.override_mars_email
else:
mars_user = request.user.attributes["ecmwf-email"]
mars_user = request.user.attributes.get("ecmwf-email", "no-email")

if self.override_mars_apikey:
logging.info("Overriding MARS_USER_TOKEN with {}".format(self.override_mars_apikey))
mars_token = self.override_mars_apikey
else:
mars_token = request.user.attributes["ecmwf-apikey"]
mars_token = request.user.attributes.get("ecmwf-apikey", "no-api-key")

env = {
**os.environ,
Expand Down

0 comments on commit d97947b

Please sign in to comment.