Implemented oidc with hydra
This commit is contained in:
parent
26ffb28a41
commit
2160f634d1
9 changed files with 87 additions and 16 deletions
|
|
@ -1,2 +1,3 @@
|
|||
from .kratos_api import *
|
||||
from .error_handler import *
|
||||
from .hydra_oauth import *
|
||||
|
|
|
|||
|
|
@ -6,6 +6,10 @@ class KratosError(Exception):
|
|||
pass
|
||||
|
||||
|
||||
class HydraError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class BadRequest(Exception):
|
||||
pass
|
||||
|
||||
|
|
@ -24,11 +28,17 @@ def validation_error(e):
|
|||
|
||||
|
||||
def kratos_error(e):
|
||||
message = e.args[0] if e.args else "Failed to contact Kratos."
|
||||
message = "[KratosError] " + e.args[0] if e.args else "Failed to contact Kratos."
|
||||
status_code = e.args[1] if e.args else 500
|
||||
return jsonify({"errorMessage": message}), status_code
|
||||
|
||||
|
||||
def hydra_error(e):
|
||||
message = "[HydraError] " + e.args[0] if e.args else "Failed to contact Hydra."
|
||||
status_code = e.args[1] if e.args else 500
|
||||
return jsonify({"errorMessage": message}), status_code
|
||||
|
||||
|
||||
def global_error(e):
|
||||
message = str(e)
|
||||
return jsonify({"errorMessage": message})
|
||||
return jsonify({"errorMessage": message}), 500
|
||||
|
|
|
|||
41
helpers/hydra_oauth.py
Normal file
41
helpers/hydra_oauth.py
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
from flask import request, session
|
||||
from requests_oauthlib import OAuth2Session
|
||||
|
||||
from config import *
|
||||
from helpers import HydraError
|
||||
|
||||
|
||||
class HydraOauth:
|
||||
SESSION_KEY = "oauth_state"
|
||||
|
||||
@staticmethod
|
||||
def authorize():
|
||||
try:
|
||||
hydra = OAuth2Session(HYDRA_CLIENT_ID)
|
||||
authorization_url, state = hydra.authorization_url(
|
||||
HYDRA_AUTHORIZATION_BASE_URL
|
||||
)
|
||||
|
||||
# State is used to prevent CSRF, keep this for later.
|
||||
session[HydraOauth.SESSION_KEY] = state
|
||||
|
||||
return authorization_url
|
||||
except Exception as err:
|
||||
raise HydraError(str(err), 500)
|
||||
|
||||
@staticmethod
|
||||
def get_token():
|
||||
try:
|
||||
hydra = OAuth2Session(
|
||||
HYDRA_CLIENT_ID, state=session[HydraOauth.SESSION_KEY]
|
||||
)
|
||||
token = hydra.fetch_token(
|
||||
TOKEN_URL,
|
||||
client_secret=HYDRA_CLIENT_SECRET,
|
||||
authorization_response=request.url,
|
||||
)
|
||||
|
||||
session["hydra_token"] = token
|
||||
return token
|
||||
except Exception as err:
|
||||
raise HydraError(str(err), 500)
|
||||
|
|
@ -18,6 +18,8 @@ class KratosApi:
|
|||
res = requests.get("{}{}".format(KRATOS_URL, url))
|
||||
KratosApi.__handleError(res)
|
||||
return res
|
||||
except KratosError as err:
|
||||
raise err
|
||||
except:
|
||||
raise KratosError()
|
||||
|
||||
|
|
|
|||
Reference in a new issue