You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
@cpacker What do you think of this implementation? Also, we can modify token storage from in-memory to persistent if desired.
Changes
server.py (SyncServer)
defauthenticate_user(self) ->str:
""" Generates a secure random bearer token, creates a new user if necessary, and stores the token associated with the user. """user_id=uuid.uuid4()
token=secrets.token_urlsafe()
user=User(id=user_id)
try:
self.ms.create_user(user)
exceptValueError:
# user already existspassself.active_tokens[token] =user_idreturntokendefverify_token(self, token: str) ->Optional[uuid.UUID]:
returnself.active_tokens.get(token, None)
auth/index.py
security=HTTPBearer()
classAuthResponse(BaseModel):
token: str=Field(..., description="Bearer token for the authenticated user")
defsetup_auth_router(server: SyncServer, interface: QueuingInterface):
@router.get("/auth", tags=["auth"], response_model=AuthResponse)defauthenticate_user():
""" Authenticates the user and sends response with User related data. Now returns a bearer token for the authenticated user. """interface.clear()
try:
token=server.authenticate_user()
exceptHTTPException:
raiseexceptExceptionase:
raiseHTTPException(status_code=500, detail=f"{e}")
returnAuthResponse(token=token)
defget_current_user(credentials: HTTPAuthorizationCredentials=Security(security)):
token=credentials.credentialsuser_id=server.verify_token(token)
ifnotuser_id:
raiseHTTPException(status_code=403, detail="Invalid authentication credentials")
user=server.ms.get_user(user_id)
ifnotuser:
raiseHTTPException(status_code=404, detail="User not found")
returnuser
Add optional authentication middleware to REST API, allowing clients to authenticate with bearer tokens
The text was updated successfully, but these errors were encountered: