[Spring-boot] Spring Security 인증 인가

2023. 10. 14. 15:00·Backend/Spring
반응형
인증과 인가란?

인증이란?

  • 사용자가 시스템에 들어갈 수 있는지 확인하는 것이다.

인가란?

  • 사용자가 받은 권한으로 시스템에 접근할 수 있는지 확인하는 것이다.

 

Spring Security - SecurityFilterChain

  • Spring Security에서 보안 필터 체인을 구성하는데 사용되는 인터페이스입니다.
	@Bean
	public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
		http
			.cors()
			.and()
			.csrf().disable()
			.logout()
			.disable()

			.sessionManagement()
			.sessionCreationPolicy(SessionCreationPolicy.STATELESS)

			.and()
			.exceptionHandling()
			.authenticationEntryPoint(jwtAuthenticationEntryPoint) // 1번
			.accessDeniedHandler(jwtAccessDeniedHandler) // 2번

			.and()
			.addFilterBefore(new JwtAuthenticationFilter(tokenProvider, redisTemplate),
				UsernamePasswordAuthenticationFilter.class)
			.authorizeRequests()
			// permitAll -> 인증과 인가를 거치지 않고 모든 사용자에게 접근 권한을 부여한다.
			.antMatchers("/ai/summary/delete/**").permitAll()
			//permitAll로 적용된 URL 이외의 모든 요청은 인증된 사용자만이 접근할 수 있게 설정됩니다.
			.anyRequest().authenticated();
        /*
         perMitAll()은 인증을 거치지 않고, 이미 인증된 사용자로 처리 후, 이미 인증된 사용자로 처리했기 때문에 인증 필터를 거치지 않고 인가 처리를 해준다.
         인가 처리 -> 권한이 있다고 확인된 것.
         */
		return http.build();
	}

 

1. authenticationEntryPoint (jwtAuthenticationEntryPoint)

@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

	//인증되지 않은 사용자가 보호된 리소스에 접근하려고 할 때 호출되는 핸들러입니다.
	//주로 인증되지 않은 사용자의 접근이나 만료된 토큰 등의 상황에서 호출됩니다.
	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response,
		AuthenticationException authException) throws IOException {
		response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
	}
}

AuthenticationEntryPoint 란?

  • 인증 과정에서 예외가 생겼을 때 예외를 핸들링 하는 메서드입니다. (인증 전용)

이후, commence 메소드가 실행된 후, 인증 과정에서 문제가 생기면 401 에러가 반환이 됩니다.

 

2. accessDeniedHandler(jwtAccessDeniedHandler)

@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {

	//접근이 거부된 경우(인가 실패) 호출되는 핸들러
	//권한이 없을 때 호출된다.
	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response,
		AccessDeniedException accessDeniedException) throws IOException {
		response.sendError(HttpServletResponse.SC_FORBIDDEN);
	}
}

AccessDeniedHandler 란?

  • 인가 과정에서 예외가 생겼을 때 예외를 핸들링하는 메서드입니다. (인가 전용)

이후,  handle 메서드가 실행 된 후, 인과 과정에서 문제가 생기면 403에러가 반환됩니다.


출처 : https://yjna2316.github.io/spring/2021/01/03/SpringSecurity-%EC%9D%B8%EC%A6%9D/

그림에서 볼 수 있듯이 인증을 먼저 한 뒤 인가를 거치는 과정입니다.

반응형
저작자표시 동일조건 (새창열림)
'Backend/Spring' 카테고리의 다른 글
  • [Spring-boot] 당신의 비밀번호 안전한가요?
  • LazyInitializationException이란? [트러블슈팅]
  • [Spring-boot]JWT를 이용해 AccessToken 발급, 검사, 정보 추출
  • [Spring-boot] Redis를 활용한 RefreshToken 저장 및 조회
코딩하는_대학생
코딩하는_대학생
Java Developer, Open Source Enthusiast, Proud Son
  • 코딩하는_대학생
    코딩하는 대학생에서 개발자까지
    코딩하는_대학생
  • 전체
    오늘
    어제
    • 분류 전체보기 (216)
      • 코딩하는 대학생의 책 추천 (8)
        • 클린코드 (5)
        • 헤드퍼스트 디자인패턴 (3)
      • Backend (6)
        • Spring (14)
        • AWS (3)
        • 회고 (4)
        • Redis (5)
        • 다양한 시각에서 바라본 백엔드 (3)
      • Python (35)
        • 개념 및 정리 (15)
        • 백준 문제풀이 (20)
      • JAVA (17)
        • 개념 및 정리 (14)
        • 백준 문제풀이 (2)
      • 왜? (7)
      • C언어 (42)
        • 개념 및 정리 (9)
        • 백준 문제풀이 (32)
      • 개인 공부 (27)
        • 대학 수학 (5)
        • 대학 영어 (10)
        • 시계열데이터 처리 및 분석 (5)
        • 컴퓨터 네트워크 (6)
        • 운영체제 (1)
      • 솔직 리뷰 (23)
        • 꿀팁 (6)
        • IT기기 (1)
        • 국내 여행 (7)
        • 맛집 (2)
        • 알바 리뷰 (2)
      • 대외활동 (17)
        • 체리피우미 3기 (4)
        • 꿀잠이들 6기 (13)
      • 음식 평가 (1)
      • 일상 & 근황 (2)
  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
코딩하는_대학생
[Spring-boot] Spring Security 인증 인가
상단으로

티스토리툴바