728x90
예외 처리를 함수로 만들어서 코드를 가독성이 좋게 만드는 것이 목표
1. 라이브러리 import
#status 삽입
from fastapi import FastAPI, Depends, HTTPException, status
2. user 인증 에러 함수
def get_user_exception():
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate":"Bearer"},
)
return credentials_exception
3. token 인증 에러 함수
def token_exception():
token_exception_response = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate":"Bearer"},
)
return token_exception_response
4. token 인증 API 수정
@app.post("/token")
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(),
db: Session = Depends(get_db)):
user = authenticate_user(form_data.username, form_data.password, db)
if not user:
return token_exception()
token_expires = timedelta(minutes=20)
token = create_access_token(user.username,
user.id,
expires_delta=token_expires)
return {"token": token}
5. 사용자 인증 함수 수정
async def get_current_user(token: str = Depends(oauth2_bearer)):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
user_id: int = payload.get("id")
if username is None or user_id is None:
raise get_user_exception()
return {"username": username, "id": user_id}
except JWTError:
return get_user_exception()
728x90
SMALL
'Develop > FastAPI' 카테고리의 다른 글
FastAPI 데이터베이스 내 User와 Todo의 관계 설정 - 52 (0) | 2023.01.10 |
---|---|
FastAPI Postman 설치 / 사용법(GET kakao 검색) - 51 (2) | 2023.01.09 |
FastAPI JSON Web Token(JWT) 디코딩 함수 구현 - 49 (0) | 2023.01.08 |
FastAPI JSON Web Token(JWT) 생성 - 48 (0) | 2023.01.08 |
FastAPI 사용자 인증 - 47 (0) | 2023.01.07 |