Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added JWT authentication. #537

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 5 additions & 5 deletions examples/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,18 +84,18 @@ def token_gen_call(username, password):
return 'Invalid username and/or password for user: {0}'.format(username)

# JWT AUTH EXAMPLE #
replace_this = False
replace_this = False # Replace this placeholder in your implementation.
config = {
'jwt_secret': 'super-secret-key-please-change',
# token will expire in 3600 seconds if it is not refreshed and the user will be required to log in again
# Token will expire in 3600 seconds if it is not refreshed and the user will be required to log in again.
'token_expiration_seconds': 3600,
# if a request is made at a time less than 1000 seconds before expiry, a new jwt is sent in the response header
# If a request is made at a time less than 1000 seconds before expiry, a new jwt is sent in the response header.
'token_refresh_seconds': 1000
}
# enable authenticated endpoints, example @authenticated.get('/users/me')
# Enable authenticated endpoints, example @authenticated.get('/users/me').
authenticated = hug.http(requires=hug.authentication.json_web_token(hug.authentication.verify_jwt, config['jwt_secret']))

# check the token and issue a new one if it is about to expire (within token_refresh_seconds from expiry)
# Check the token and issue a new one if it is about to expire (within token_refresh_seconds from expiry).
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Normally there will be 2 new lines between function and classes and one new line between class methods. Please add a new line.

@hug.response_middleware()
def refresh_jwt(request, response, resource):
authorization = request.get_header('Authorization')
Expand Down
14 changes: 3 additions & 11 deletions hug/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ def jwt_authenticator_name():
def json_web_token(request, response, verify_token, jwt_secret):
"""JWT verification

Checks for the Authorization header and verifies it using the verify_token function
Checks for the Authorization header and verifies it using the verify_token function.
"""
authorization = request.get_header('Authorization')
if authorization:
Expand All @@ -197,13 +197,9 @@ def verify_jwt(authorization, response, jwt_secret):
try:
token = authorization.split(' ')[1]
decoding = jwt.decode(token, jwt_secret, algorithm='HS256')
print(decoding)
return decoding['user_id']
except Exception as ex:
template = "An exception of type {0} occurred. Arguments:\n{1!r}"
print(template.format(type(ex).__name__, ex.args))
except:
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you catching all exceptions ? 😮 Wouldn't this make things hard to debug ?

Isn't there a specific exception that can be caught ?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes it would, I'll go figure out which one/s I'm expecting to catch when the token is no longer valid. Thanks.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@OGKevin If an exception is thrown that isn't caught here what happens to the server? Does it continue running and print and error message, or does it break? Where is the code that handles the exceptions that get bubbled up?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dsmurrell The individual request will die, but the server itself will keep running, if you have an @hug.exception handler you can manage how that exception is handled

return False
return None

def new_jwt(user_id, token_expiration_seconds, jwt_secret):
return jwt.encode({'user_id': user_id,
Expand All @@ -220,10 +216,6 @@ def refresh_jwt(authorization, token_refresh_seconds, token_expiration_seconds,
return jwt.encode({'user_id': decoding['user_id'],
'exp': datetime.utcnow() + timedelta(seconds=token_expiration_seconds)},
jwt_secret, algorithm='HS256').decode("utf-8")
else:
return None
except Exception as ex:
template = "An exception of type {0} occurred. Arguments:\n{1!r}"
print(template.format(type(ex).__name__, ex.args))
except:
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same as above ☝️

return None
# END - JWT AUTH #