Spring Security + JWT

Haechan Kim·2023년 5월 30일
0

Spring

목록 보기
42/68

Spring Security 인증과정

  1. http request가 서버로 넘어온다.
  2. 제일 먼저 AuthenticationFilter가 요청을 받게 된다.
  3. 필터에서 request의 Username, password로 UsernamePasswordAuthenticationToken 생성한다.
  4. AuthenticationManager가 토큰을 받는다.
  5. 매니저는 토큰을 AuthenticationProvider에게 넘겨준다.
  6. 프로바이더는 UserDetailsService에게 토큰의 Username 전달하고 DB에 있는지 확인한다. 이때 UserDetailsService는 DB의 회원정보를 UserDetails 객체로 반환한다.
  7. 프로바이더는 반환받은 객체를 실제 사용자의 입력정보와 비교한다.
  8. 비교 후 사용자 정보를 가진 Authentication 객체를 SecurityContextHolder에 담은 이후 AuthenticationSuccessHandle를 실행한다.(실패시 AuthenticationFailureHandler를 실행한다.)

Spring Security Filter

스프링 시큐리티는 필터 기반!

여러 필터가 존재하는데 원하는 필터를 커스텀하여 사용하면 됨.
새로운 필터를 생성할 때는 securityConfig에 Filter 체인을 추가 등록하면 됨.

필터 체인


필터들은 그림처럼 체인되어 있는데 필터 생성 후 원하는 필터 앞/뒤에 삽입하면 됨.

JWT

jwt는 3개의 구역으로 구성되어 있다.

  • header : 암호화 하는 방식, 타입 등등
  • payload : 내용. 서버에 보낼 데이터. user id, 유효기간 등
  • verify signature : 서명. Base64 방식으로 인코딩한 header, payload, secret key를 더한 값.

JWT 통한 인증절차

  1. 사용자 로그인
  2. 서버에서 계정 정보 읽고 사용자 확인 -> 사용자 고유 id 값 부여 -> 기타 정보와 함께 payload 에 넣는다.
  3. 토큰 유효기간 설정.
  4. 암호화 할 secret key 이용해 access token 발급 받음.
  5. 사용자는 액세스 토큰 저장 후 인증 필요할 때마다 토큰 헤더에 넣어 보냄.
  6. 서버는 받은 토큰의 verify signature를 secret key로 복호화 한 후, 검증(조작 여부, 유효기간 확인).
  7. 검증 후 payload 디코딩 후 사용자 id에 맞는 데이터 가져옴.

Spring Security + JWT

config

  1. 가장 먼저 security와 filter 관련 설정을 해줘야 함.

customer Filter

customer Provider

JWT의 암호화 알고리즘을 HS256, 즉 SHA-256 암호화를 사용하므로 키 값 또한 256비트가 넘어야 한다.
하지만 입력한 키의 값이 120비트라서 오류가 발생하는 것.
secret key의 길이는 늘리자!

The signing key's size is 120 bits which is not secure enough for the HS256 algorithm. The JWT JWA Specification (RFC 7518, Section 3.2) states that keys used with HS256 MUST have a size >= 256 bits (the key size must be greater than or equal to the hash output size). Consider using the io.jsonwebtoken.security.Keys class's 'secretKeyFor(SignatureAlgorithm.HS256)' method to create a key guaranteed to be secure enough for HS256. See https://tools.ietf.org/html/rfc7518#section-3.2 for more information.

0개의 댓글