2023.02.18.TIL

김근호·2023년 2월 18일
1

Spring

목록 보기
5/9

Spring Security

'Spring Security' 프레임워크는 스프링 서버에 필요한 인증 및 인가를 위해 많은 기능을 제공해 줌으로써 개발의 수고를 덜어 줍니다. 마치 '스프링' 프레임워크가 웹 서버 구현에 편의를 제공해 주는 것과 같습니다.

Spring Security 프레임워크 추가 하는 법

build.gradle에 implementation 'org.springframework.boot:spring-boot-starter-security'추가 하기

Spring Security 프레임워크 활성화 하는 법

@EnableWebSecurity을 붙이면 Spring Security 지원을 가능하게 함

Spring Security 와 Filter

Spring Security는 요청이 들어오면 Servlet FilterChain을 자동으로 구성한 후 거치게 한다. FilterChain은 여러 Filter를 chain형태로 묶어놓은 것을 의미합니다.
여기서 Filter 란, 톰캣과 같은 웹 컨테이너에서 관리되는 서블릿의 기술이다. Filter는 Client 요청이 전달되기 전후의 URL 패턴에 맞는 모든 요청에 필터링을 해준다.
CSRF, XSS 등의 보안 검사를 통해 올바른 요청이 아닐 경우 이를 차단해 준다.
따라서 Spring Security는 이런한 기능을 활용하기위해 Filter를 사용하여 인증/인가를 구현하고 있다.


여기서 permitAll()은 앞의 url로 들어오는 url은 인증 없이 모두 허용하겠다는 의미이다.

SecurityFilterChain

Spring 의 보안 Filter를 결정하는데 사용되는 Filter
session, jwt 등의 인증방식들을 사용하는데에 필요한 설정을 완전히 분리할 수 있는 환경을 제공한다.

  • Filter는 chain이라는 여러번의 Filter를 거치는데 중간에 Exception이 발생 되면, 이전의 Filter로 돌아간다

AbstractAuthenticationProcessingFilter

사용자의 credential을 인증하기 위한 베이스 Filter

UsernamePasswordAuthenticationFilter

UsernamePasswordAuthenticationFilter 는 AbstractAuthenticationProcessingFilter를 상속한 Filter다.
기본적으로 아래와 같은 Form Login 기반을 사용할 때 username 과 password 확인하여 인증한다.
Form Login 기반은 인증이 필요한 URL 요청이 들어왔을 때 인증이 되지 않았다면 로그인페이지를 반환하는 형태이다.

SecurityContextHolder

  • SecurityContextHolder 에는 스프링 시큐리티로 인증을 한 사용자의 상세 정보를 저장한다.
  • SecurityContext 란? SecurityContextHolder 로 접근할 수 있으며 Authentication 객체를 가지고 있다.

// 예시코드

Authentication authentication = new UsernamePasswordAuthenticationToken(principal, credentials, authorities);
context.setAuthentication(authentication);
SecurityContextHolder.setContext(context);```

Authentication

  • 현재 인증된 사용자를 나타내며 SecurityContext 에서 가져올 수 있다.
  • principal : 사용자를 식별한다. Username/Password 방식으로 인증할 때 보통 UserDetails 인스턴스다.
  • credentials : 주로 비밀번호, 대부분 사용자 인증에 사용하고 다음 비운다.
  • authorities : 사용자에게 부여한 권한을 GrantedAuthority 로 추상화하여 사용한다.

비밀번호 암호화

회원 등록 시 '비밀번호'는 사용자가 입력한 문자 그대로 DB 에 등록하면 안 됩니다.
'정보통신망법, 개인정보보호법' 에 의해 비밀번호 암호화(Encryption)가 의무입니다.

단방향, 양방향

  • 양방향은 암호화(인코딩),복호화(디코딩) 둘 다 가능하다
  • 단방향은 암호화(인코딩)는 가능한데, 복호화(디코딩)는 불가능하다
    -> Spring Security가 제공하는 "적응형 단방향 함수 bCrypt"를 사용해서 암호화한다

Password Matching

Spring Security 에서는 비밀번호를 암호화하는 함수를 제공할 뿐만 아니라 사용자가 입력한 비밀번호를 저장된 비밀번호와 비교하여 일치여부를 확인해주는 함수도 제공합니다.

  • boolean matches(CharSequence rawPassword, String encodedPassword);
    - rawPassword : 사용자가 입력한 비밀번호
    - encodedPassword : 암호화되어 DB 에 저장된 비밀번호

@Secured

'일반 사용자'는 관리자 페이지에 접속이 인가되지 않아야 합니다!!

Spring Security를 이용한 API 별 권한 제어 방법

  • Controller 에 "@Secured" 어노테이션으로 권한 설정 가능
    - @Secured("권한 이름") 선언
    - 권한 1개 이상 설정 가능// (관리자용) 등록된 모든 상품 목록 조회
  • "@Secured" 어노테이션 활성화 방법
profile
앞만 보고 나아가자!

0개의 댓글