[Project] 6일차 진행 - Spring Security 적용(토큰 생성)

박상혁·2023년 5월 29일

Project

목록 보기
13/14

구현 방식

  • 인터셉터 이용
  • 서블릿 필터 이용
    이중에서 서블릿 필터를 이용하여 구현

deprecated WebSecurityConfigurerAdapter

Spring Security without the WebSecurityConfigurerAdapter
Springboot 2.7 버전부터(Spring Security 5.7.0-M2) 시큐리티 설정파일을 등록하는 방법이 달라짐

기존에 Adapter를 상속하는 방법에서
SecurityFilterChain Bean을 등록하는 방법으로 변경
자세한 방법은 위 공식 블로그 참조

  • 기본적으로 Security는 ServletFilter를 사용하여 구현된 라이브러리

요구사항 분석

회원가입, 로그인 2가지 기능과, 이외에 로그인 이후 어떤 책임을 추가해야 되는지 분석

회원 가입

회원가입은 Token을 발급할 필요가 없기 때문에 유효성 검사 및 중복 여부만 조사한 후 DB에 저장

로그인

id, pw를 체크한 후 서버의 비밀키를 사용하여 JWT를 생성하고 클라이언트에게 발급

이외 기능

내정보 조회, 게시판 수정 등 User의 인증을 필요로 하는 기능들에 Header 체크하는 기능을 추가. 이는 Filter 혹은 Intercepter를 사용

JWT 구현 순서

[Java] Spring Boot Security 이해하기 -1 : 5.7.x 버전 구조 및 파일 이해
멋사 SpringSecurity 인증인가 - 01 Spring Security적용
Spring Security
Spring Security Architecture

  1. 의존성 주입
  2. User Entity 생성 및 회원가입, 로그인 Controller 생성
  3. WebSecurityConfig 클래스 생성
    Spring Security를 사용하기 위한 설정 클래스스
  4. Spring Security 기본 설정
    기본적인 FilterChain 등록이나 세션 정책 등록 등

의존성 주입

implementation 'org.springframework.boot:spring-boot-starter-security'  
implementation 'o.jsonwebtoken:jjwt:0.9.1'

기본적인 User API 처리 로직 구현

CRUD 구현
특별히 인증 절차 없이, DB로 확인만 하는 기본적인 CRUD를 먼저 구현하자
이후에 인증 로직을 거치면 된다.

WebSecurityConfig 클래스 생성

@Bean  
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{  
	return http  
			.httpBasic().disable()  
			.csrf().disable()  
			.cors().and()  
			.authorizeRequests()  
			.antMatchers("/user/login").permitAll()  
			.antMatchers(HttpMethod.GET, "/boards/**").authenticated()  
			.and()  
			.sessionManagement()  
			.sessionCreationPolicy(SessionCreationPolicy.STATELESS)  
			.and()  
			// .addFilterBefore(new JwtAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class)  
			.build();  
}
  • authorizeRequests()
    요청에 대해서 인증을 거침을 선언
    antMatchers를 이용해 어떤 URL을 허가하고 허가하지 않을 것인지 설정
  • sessionManagement()
    세션 정책을 무상태로 만듬

TokenUtils 생성

토큰 생성 및 기타 기능들을 한 곳에 모은 Utils 클래스
이 친구는 static 메서드만 구현하기 때문에 따로 Bean 등록 안해도 됨
여기서 jjwt 라이브러리를 활용하여 생성 로직을 구성할 것

토큰 생성 메서드

public static String createToken(String username, String secretKey, Long expiredMilliSecond) {  
	Claims claims = Jwts.claims();  
	claims.put("username", username);  
  
	return Jwts.builder()  
			.setClaims(claims)  
			.setIssuedAt(new Date(System.currentTimeMillis()))  
			.setExpiration(new Date(System.currentTimeMillis() + expiredMilliSecond))  
			.signWith(SignatureAlgorithm.HS256, secretKey)  
			.compact();  
}
  • Claim : 내가 원하는 정보를 담을 수 있는 공간. Map으로 구현되어 있음
    만든 claims 넣고, 언제 생성되었고 만료 기간은 언제인지
    그리고 서명 알고리즘과 비밀키를 넣어 서명을 만들 수 있게 함

토큰 생성 성공


토큰이 생성되는 것 까지 구현 완료

profile
개발 노트

0개의 댓글