Notice
Recent Posts
Recent Comments
Link
«   2025/10   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

죽이죽이

JS : JWT 인증 방식 본문

Javascript

JS : JWT 인증 방식

죽이죽이 2024. 1. 31. 19:34
  • JSON Web Token
※ 사용하는 이유
- 사용자의 인증관련 정보를 전달하기 위해 사용한다.

- HTTP 헤더에 넣어 쉽게 전송할 수 있다.
- 서버가 클라이언트의 상태를 가지고 있지 않은 무상태성을 지향한다.
- 별도의 DB 공간이 필요하지 않다.


※ 사용 방법 (Python - FastAPI)
- 로그인 시 JWT 토큰 생성 및 발금

@app.post("/login")
def login(id:Annotated[str, Form()],
          password:Annotated[str, Form()]):
  user = user_info(id)
  
  if not user:
    raise InvalidCredentialsException
  elif password != user['password']:
    raise InvalidCredentialsException
  
  access_token = manager.create_access_token(data={
    'sub': {
      'id': user['id'],
      'name': user['name'],
      'email': user['email']
    }
  })
  
  return {'access_token': access_token}


- 발급 받은 토큰을 session에 저장

const handleSubmit = async (e) => {
  e.preventDefault();
  const formData = new FormData(form);
  const sha256Password = sha256(formData.get("password"));
  formData.set("password", sha256Password);

  const data = await fetch("/login", {
    method: "POST",
    body: formData,
  }).then((res) => res.json());

  accessToken = data.access_token;
  window.localStorage.setItem("token", accessToken);
  window.location.pathname = "/";
};


- 클라이언트단에서 요청 시 HTTP 헤더를 통해 전송

const fetchList = async () => {
  const accessToken = window.localStorage.getItem("token");
  const datas = await fetch("/items", {
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
  }).then((res) => res.json());
  renderData(datas);
};