keycloak.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. from fastapi import FastAPI, Form, Request, Depends, HTTPException, Body
  2. from pydantic import BaseModel
  3. from fastapi.responses import JSONResponse, RedirectResponse, HTMLResponse
  4. from fastapi.templating import Jinja2Templates
  5. from fastapi.staticfiles import StaticFiles
  6. from fastapi.middleware.cors import CORSMiddleware
  7. from starlette.middleware.sessions import SessionMiddleware
  8. import secrets
  9. import uvicorn
  10. import logging
  11. import requests # Import the requests library here
  12. from typing import Annotated, Dict, List #import typing
  13. # --- Keycloak Configuration ---
  14. KEYCLOAK_SERVER_URL = "http://165.22.75.145:8080" # Double-check this! Changed to http
  15. KEYCLOAK_REALM = "Generation"
  16. KEYCLOAK_CLIENT_ID = "web-app-pw"
  17. KEYCLOAK_CLIENT_SECRET = "fQGWt8HSPn65cCKTOzE5FigqZhf8QTYW"
  18. KEYCLOAK_SCOPE = "codicefiscale email openid ruolo"
  19. # --- App Initialization ---
  20. app = FastAPI()
  21. # --- Logging Configuration ---
  22. logging.basicConfig(level=logging.INFO)
  23. logger = logging.getLogger(__name__)
  24. # --- CORS ---
  25. origins = [
  26. "http://localhost:8000",
  27. "http://localhost:3000/*",
  28. ]
  29. app.add_middleware(
  30. CORSMiddleware,
  31. allow_origins=origins,
  32. allow_credentials=True,
  33. allow_methods=["*"],
  34. allow_headers=["*"],
  35. )
  36. # --- Session ---
  37. app.add_middleware(SessionMiddleware, secret_key=secrets.token_hex(32))
  38. # --- Helper Functions (modified to be part of the API) ---
  39. # Function to get tokens from keycloak
  40. def get_token_from_keycloak(username, password) -> Dict:
  41. """Retrieves access and refresh tokens from Keycloak."""
  42. url = f"{KEYCLOAK_SERVER_URL}/realms/{KEYCLOAK_REALM}/protocol/openid-connect/token"
  43. payload = f'grant_type=password&client_id={KEYCLOAK_CLIENT_ID}&scope={KEYCLOAK_SCOPE}&username={username}&password={password}&client_secret={KEYCLOAK_CLIENT_SECRET}'
  44. headers = {
  45. 'Content-Type': 'application/x-www-form-urlencoded'
  46. }
  47. try:
  48. response = requests.post(url, headers=headers, data=payload, timeout=10)
  49. response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
  50. return response.json()
  51. except requests.exceptions.RequestException as e:
  52. logger.error(f"Error getting token from Keycloak: {e}")
  53. raise HTTPException(status_code=500, detail=f"Failed to get token from Keycloak: {e}") from e
  54. def refresh_token_from_keycloak(refresh_token: str) -> Dict:
  55. """Refreshes the access token using the refresh token."""
  56. url = f"{KEYCLOAK_SERVER_URL}/realms/{KEYCLOAK_REALM}/protocol/openid-connect/token"
  57. payload = f'grant_type=refresh_token&client_id={KEYCLOAK_CLIENT_ID}&client_secret={KEYCLOAK_CLIENT_SECRET}&refresh_token={refresh_token}'
  58. headers = {
  59. 'Content-Type': 'application/x-www-form-urlencoded'
  60. }
  61. try:
  62. response = requests.post(url, headers=headers, data=payload, timeout=10)
  63. response.raise_for_status()
  64. return response.json()
  65. except requests.exceptions.RequestException as e:
  66. logger.error(f"Error refreshing token: {e}")
  67. raise HTTPException(status_code=500, detail=f"Failed to refresh token: {e}") from e
  68. def introspect_keycloak_token_request(access_token: str) -> Dict:
  69. """Introspects a Keycloak token to verify if it's active."""
  70. url = f"{KEYCLOAK_SERVER_URL}/realms/{KEYCLOAK_REALM}/protocol/openid-connect/token/introspect"
  71. payload = f'token={access_token}&client_id={KEYCLOAK_CLIENT_ID}&client_secret={KEYCLOAK_CLIENT_SECRET}'
  72. headers = {
  73. 'Content-Type': 'application/x-www-form-urlencoded'
  74. }
  75. try:
  76. response = requests.post(url, headers=headers, data=payload, verify=False, timeout=10)
  77. response.raise_for_status()
  78. return response.json()
  79. except requests.exceptions.RequestException as e:
  80. logger.error(f"Error introspecting token: {e}")
  81. raise HTTPException(status_code=500, detail=f"Failed to introspect token: {e}") from e
  82. def get_user_info_from_keycloak(access_token: str) -> Dict:
  83. """Gets user information from Keycloak using the access token."""
  84. url = f"{KEYCLOAK_SERVER_URL}/realms/{KEYCLOAK_REALM}/protocol/openid-connect/userinfo"
  85. headers = {
  86. 'Authorization': f'Bearer {access_token}'
  87. }
  88. try:
  89. response = requests.get(url, headers=headers, timeout=10)
  90. response.raise_for_status()
  91. return response.json()
  92. except requests.exceptions.RequestException as e:
  93. logger.error(f"Error getting user info: {e}")
  94. raise HTTPException(status_code=500, detail=f"Failed to get user info: {e}") from e
  95. def logout_keycloak(refresh_token:str):
  96. url = f"{KEYCLOAK_SERVER_URL}/realms/{KEYCLOAK_REALM}/protocol/openid-connect/logout"
  97. payload = f'refresh_token={refresh_token}&client_id={KEYCLOAK_CLIENT_ID}&client_secret={KEYCLOAK_CLIENT_SECRET}'
  98. headers = {
  99. 'Content-Type': 'application/x-www-form-urlencoded'
  100. }
  101. try:
  102. response = requests.request("POST", url, headers=headers, data=payload)
  103. response.raise_for_status()
  104. return response.json()
  105. except requests.exceptions.RequestException as e:
  106. logger.error(f"Error logging out user: {e}")
  107. raise HTTPException(status_code=500, detail=f"Failed to logout user: {e}") from e
  108. #print(get_token_from_keycloak("testuserperpaginaprivata", "user"))
  109. # --- Routes ---
  110. #@app.get("/login")
  111. #async def login(request: Request):
  112. # """
  113. # Logs in a user by retrieving tokens from Keycloak.
  114. # Stores the tokens and user info in the session.
  115. # """
  116. # try:
  117. # #tokens = get_token_from_keycloak()
  118. # ## Save tokens and information to the session
  119. # #request.session["access_token"] = tokens["access_token"]
  120. # #request.session["refresh_token"] = tokens["refresh_token"]
  121. ##
  122. # ## Get user info and save it to the session too
  123. # #user_info = get_user_info_from_keycloak(tokens["access_token"])
  124. # #request.session["user_info"] = user_info
  125. ##
  126. # #return {"message": "Login successful", "access_token": tokens["access_token"], "user_info": user_info}
  127. #
  128. # if request.session["access_token"]:
  129. # return RedirectResponse(url="localhost:3000/index")
  130. # else:
  131. # return RedirectResponse(url="localhost:3000/login")
  132. # except HTTPException as e:
  133. # return JSONResponse(content={"detail": e.detail}, status_code=e.status_code)
  134. # except Exception as e:
  135. # logger.error(f"An unexpected error occurred during login: {e}")
  136. # return JSONResponse(content={"detail": "An unexpected error occurred"}, status_code=500)
  137. class Credenziali(BaseModel):
  138. username: str
  139. password: str
  140. #@app.get("/login")
  141. app.mount("/static", StaticFiles(directory="static"), name="static")
  142. templates = Jinja2Templates(directory="templates")
  143. @app.get("/access")
  144. async def access(request: Request):
  145. return templates.TemplateResponse("login.html", context={"request": request, "title": "Accesso"})
  146. @app.post("/login")
  147. async def login(request: Request, credenziali: Credenziali = Body(...)):
  148. """
  149. Logs in a user by retrieving tokens from Keycloak.
  150. Stores the tokens and user info in the session.
  151. """
  152. try:
  153. tokens = get_token_from_keycloak(credenziali.username, credenziali.password)#request.body.json()["username"], request.json()["password"])
  154. RedirectResponse(url="localhost:8000/callback")
  155. # Save tokens and information to the session
  156. request.session["access_token"] = tokens["access_token"]
  157. request.session["refresh_token"] = tokens["refresh_token"]
  158. #print(tokens["access_token"])
  159. # Get user info and save it to the session too
  160. user_info = get_user_info_from_keycloak(tokens["access_token"])
  161. request.session["user_info"] = user_info
  162. return RedirectResponse(url="localhost:8000/callback")
  163. except HTTPException as e:
  164. return JSONResponse(content={"detail": e.detail}, status_code=e.status_code)
  165. except Exception as e:
  166. logger.error(f"An unexpected error occurred during login: {e}")
  167. return JSONResponse(content={"detail": "An unexpected error occurred"}, status_code=500)
  168. @app.get("/refresh")
  169. async def refresh(request: Request):
  170. """Refreshes the access token using the refresh token in the session."""
  171. refresh_token = request.session.get("refresh_token")
  172. if not refresh_token:
  173. raise HTTPException(status_code=401, detail="Refresh token not found in session")
  174. try:
  175. new_tokens = refresh_token_from_keycloak(refresh_token)
  176. request.session["access_token"] = new_tokens["access_token"]
  177. request.session["refresh_token"] = new_tokens["refresh_token"]
  178. new_user_info = get_user_info_from_keycloak(new_tokens["access_token"])
  179. request.session["user_info"] = new_user_info
  180. return {"message": "Token refreshed successfully", "access_token": new_tokens["access_token"], "user_info": new_user_info}
  181. except HTTPException as e:
  182. return JSONResponse(content={"detail": e.detail}, status_code=e.status_code)
  183. except Exception as e:
  184. logger.error(f"An unexpected error occurred during token refresh: {e}")
  185. return JSONResponse(content={"detail": "An unexpected error occurred"}, status_code=500)
  186. @app.get("/introspect")
  187. async def introspect(request: Request):
  188. """Introspects the access token in the session."""
  189. access_token = request.session.get("access_token")
  190. if not access_token:
  191. raise HTTPException(status_code=401, detail="Access token not found in session")
  192. try:
  193. introspect_data = introspect_keycloak_token_request(access_token)
  194. return {"message": "Token introspection successful", "introspect_data": introspect_data}
  195. except HTTPException as e:
  196. return JSONResponse(content={"detail": e.detail}, status_code=e.status_code)
  197. except Exception as e:
  198. logger.error(f"An unexpected error occurred during token introspection: {e}")
  199. return JSONResponse(content={"detail": "An unexpected error occurred"}, status_code=500)
  200. @app.get("/userinfo")
  201. async def user_info(request: Request):
  202. """Retrieves and returns user information stored in the session."""
  203. user_info = request.session.get("user_info")
  204. if not user_info:
  205. raise HTTPException(status_code=401, detail="User info not found in session")
  206. return {"message": "User information retrieved", "user_info": user_info}
  207. @app.get("/logout_keycloak")
  208. async def logout_user(request: Request):
  209. """Logs out a user by revoking the refresh token."""
  210. refresh_token = request.session.get("refresh_token")
  211. if not refresh_token:
  212. raise HTTPException(status_code=401, detail="Refresh token not found in session")
  213. try:
  214. logout_keycloak(refresh_token)
  215. request.session.clear()
  216. return {"message": "Logout successful"}
  217. except HTTPException as e:
  218. return JSONResponse(content={"detail": e.detail}, status_code=e.status_code)
  219. except Exception as e:
  220. logger.error(f"An unexpected error occurred during logout: {e}")
  221. return JSONResponse(content={"detail": "An unexpected error occurred"}, status_code=500)
  222. @app.get("/protected")
  223. async def protected_endpoint(request: Request):
  224. """A protected endpoint that requires a valid access token."""
  225. access_token = request.session.get("access_token")
  226. if not access_token:
  227. raise HTTPException(status_code=401, detail="Access token not found in session")
  228. try:
  229. introspect_data = introspect_keycloak_token_request(access_token)
  230. if not introspect_data.get("active"):
  231. raise HTTPException(status_code=401, detail="Access token is not active")
  232. return JSONResponse({"message": f"Hello, world! (Protected)", "introspect": introspect_data})
  233. except HTTPException as e:
  234. return JSONResponse(content={"detail": e.detail}, status_code=e.status_code)
  235. except Exception as e:
  236. logger.error(f"An unexpected error occurred during token introspection: {e}")
  237. return JSONResponse(content={"detail": "An unexpected error occurred"}, status_code=500)
  238. # --- Run the App ---
  239. if __name__ == "__main__":
  240. uvicorn.run(app, host="localhost", port=8000)