def generate_token(data:dict):
to_encode=data.copy();
expire=datetime.utcnow() +timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES);
to_encode.update({"exp":expire})
encode_jwt=jwt.encode(to_encode,SECRET_KEY,algorithm=ALGORITHM);
return encode_jwt
데이터를 받고 랜덤으로 생성한 SECRET_KEY를 이용해 인코딩해 토큰을 생성하였다.
@router.post('/login')
def login(request:OAuth2PasswordRequestForm=Depends(),db:Session=Depends(get_db)):
seller=db.query(models.Seller).filter(models.Seller.username==request.username).first()
if not seller:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,detail='Seller not found')
access_token= generate_token(
data={"sub":seller.username}
)
return {"access_token":access_token,"token_type":"bearer"}
맨 위 그림의 오른쪽처럼 원하는 기능을 잠금하여 2번째 그림처럼 로그인을 통해 인증을 해야만 원하는 기능을 이용할 수 있다.