Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save francbartoli/964fdd92f29cd6be20e2feb6eb5c9408 to your computer and use it in GitHub Desktop.

Select an option

Save francbartoli/964fdd92f29cd6be20e2feb6eb5c9408 to your computer and use it in GitHub Desktop.
@app.get("/login_basic")
async def login_basic(auth: BasicAuth = Depends(basic_auth)):
if not auth:
response = Response(headers={"WWW-Authenticate": "Basic"}, status_code=401)
return response
try:
decoded = base64.b64decode(auth).decode("ascii")
username, _, password = decoded.partition(":")
user = authenticate_user(fake_users_db, username, password)
if not user:
raise HTTPException(status_code=400, detail="Incorrect email or password")
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": username}, expires_delta=access_token_expires
)
token = jsonable_encoder(access_token)
response = RedirectResponse(url="/docs")
response.set_cookie(
"Authorization",
value=f"Bearer {token}",
domain="localtest.me",
httponly=True,
max_age=1800,
expires=1800,
)
return response
except:
response = Response(headers={"WWW-Authenticate": "Basic"}, status_code=401)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment