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

Itsdangerous replacement with PyJWT #144

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions .gitmodules

This file was deleted.

5 changes: 5 additions & 0 deletions docs/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
THEMESDIR = _themes

# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
Expand Down Expand Up @@ -52,6 +53,10 @@ help:
.PHONY: clean
clean:
rm -rf $(BUILDDIR)/*
rm -rf $(THEMESDIR)/*
git clone git://github.com/mitsuhiko/flask-sphinx-themes.git $(THEMESDIR)
@echo
@echo "Clones Sphinx themes into $(THEMESDIR)"

.PHONY: html
html:
Expand Down
1 change: 0 additions & 1 deletion docs/_themes
Submodule _themes deleted from 1cc446
34 changes: 18 additions & 16 deletions flask_oidc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,12 @@
from oauth2client.client import flow_from_clientsecrets, OAuth2WebServerFlow,\
AccessTokenRefreshError, OAuth2Credentials
import httplib2
from itsdangerous import JSONWebSignatureSerializer, BadSignature
import jwt

__all__ = ['OpenIDConnect', 'MemoryCredentials']

logger = logging.getLogger(__name__)


def _json_loads(content):
if not isinstance(content, str):
content = content.decode('utf-8')
Expand Down Expand Up @@ -176,11 +175,10 @@ def init_app(self, app):
cache=secrets_cache)
assert isinstance(self.flow, OAuth2WebServerFlow)

# create signers using the Flask secret key
self.extra_data_serializer = JSONWebSignatureSerializer(
app.config['SECRET_KEY'], salt='flask-oidc-extra-data')
self.cookie_serializer = JSONWebSignatureSerializer(
app.config['SECRET_KEY'], salt='flask-oidc-cookie')
self.extra_data_salt = 'flask-oidc-extra-data'
self.cookie_salt = 'flask-oidc-cookie'
self.extra_data_key = app.config['SECRET_KEY'] + self.extra_data_salt
self.cookie_key = app.config['SECRET_KEY'] + self.cookie_salt

try:
self.credentials_store = app.config['OIDC_CREDENTIALS_STORE']
Expand Down Expand Up @@ -353,13 +351,17 @@ def _get_cookie_id_token(self):
# Do not error if we were unable to get the cookie.
# The user can debug this themselves.
return None
return self.cookie_serializer.loads(id_token_cookie)
except SignatureExpired:
return jwt.decode(id_token_cookie, self.cookie_key, audience=self.client_secrets['client_id'],
algorithms=["HS512"])
except jwt.ExpiredSignatureError:
logger.debug("Invalid ID token cookie", exc_info=True)
return None
except BadSignature:
except jwt.InvalidSignatureError:
logger.info("Signature invalid for ID token cookie", exc_info=True)
return None
except:
logger.info("Token cookie JWT error", exc_info=True)
return None

def set_cookie_id_token(self, id_token):
"""
Expand Down Expand Up @@ -390,7 +392,7 @@ def _after_request(self, response):

if getattr(g, 'oidc_id_token_dirty', False):
if g.oidc_id_token:
signed_id_token = self.cookie_serializer.dumps(g.oidc_id_token)
signed_id_token = jwt.encode(g.oidc_id_token, self.cookie_key, algorithm="HS512")
response.set_cookie(
current_app.config['OIDC_ID_TOKEN_COOKIE_NAME'],
signed_id_token,
Expand Down Expand Up @@ -575,8 +577,7 @@ def redirect_to_auth_server(self, destination=None, customstate=None):
if customstate is not None:
statefield = 'custom'
statevalue = customstate
state[statefield] = self.extra_data_serializer.dumps(
statevalue).decode('utf-8')
state[statefield] = jwt.encode({'statevalue': statevalue}, self.extra_data_key, algorithm="HS512")

extra_params = {
'state': urlsafe_b64encode(json.dumps(state).encode('utf-8')),
Expand Down Expand Up @@ -684,6 +685,7 @@ def decorated(*args, **kwargs):

def _oidc_callback(self):
plainreturn, data = self._process_callback('destination')

if plainreturn:
return data
else:
Expand Down Expand Up @@ -731,10 +733,10 @@ def _process_callback(self, statefield):
# when Google is the IdP, the subject is their G+ account number
self.credentials_store[id_token['sub']] = credentials.to_json()

# Retrieve the extra statefield data
try:
response = self.extra_data_serializer.loads(state[statefield])
except BadSignature:
response = jwt.decode(state[statefield], self.extra_data_key, algorithms=["HS512"])
response = response['statevalue']
except:
logger.error('State field was invalid')
return True, self._oidc_error()

Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
Flask
itsdangerous
PyJWT
gerwout marked this conversation as resolved.
Show resolved Hide resolved
oauth2client
six
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from setuptools import setup

# This check is to make sure we checkout docs/_themes before running sdist
if not os.path.exists("./docs/_themes/README"):
if "sdist" in sys.argv and not os.path.exists("./docs/_themes/README"):
print('Please make sure you have docs/_themes checked out while running setup.py!')
if os.path.exists('.git'):
print('You seem to be using a git checkout, please execute the following commands to get the docs/_themes directory:')
Expand Down