[Spring Security] 인증 및 권한 부여

Jeongyeon Park·2023년 2월 3일

Spring 개념 정리

목록 보기
3/4

인증 및 권한 부여 (Authentication and Authorization)


1. 인증(Authentication)과 인가(Authorization)

1) 인증(Authentication)

보호된 리소스에 접근한 대상에 대해 해당 유저가 누구이며 애플리케이션의 작업을 수행할 수 있는 주체인지 확인하는 과정

2) 인가(Authorization)

보호된 리소스에 접근한 유저가 해당 리소스에 접근 권한을 가지고 있는지 확인하는 과정(Authentication 이후 수행)

3) 접근 주체(Principal)

보호된 리소스에 접근하는 대상


2. Spring Security의 인증 아키텍쳐(Authentication Architecture)

Spring Security

  • Spring에서 제공하는 하위 프레임워크로, 유저의 리소스 접근 및 사용을 컨트롤
  • 인증, 권한 부여 등 보안 관련 기능을 쉽게 구현할 수 있도록 다양한 함수 제공
  • Spring의 DispatcherServlet 앞단에 Filter 형태로 위치 -> 요청이 Dispatcher로 넘어가기 전에 클라이언트의 리소스 접근 권한 확인 (권한이 없는 클라이언트의 경우, 인증 요청 화면으로 redirection)

1) Spring Security Authentication Architecture



2) Spring Security Filter

예제 코드

@Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{

        http.sessionManagement()
                // 인증에 JWT 토큰을 사용하므로 Session을 생성하지 않음
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .exceptionHandling()
                // 잘못된/만료된/지원되지 않는 JWT 토큰을 사용했을 때의 예외처리
                .authenticationEntryPoint(new RestAuthenticationEntryPoint())
                // 사용자가 허가받지 않은 API에 접근한 경우
                .accessDeniedHandler(customAccessDeniedHandler).and()
                .authorizeRequests()  // 인증된 유저만 접근 가능
                // CORS Preflight Request에 대해서는 spring security를 적용하지 않음
                .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                .antMatchers("/", "/login/oauth2/**").permitAll()
                // 로그인 URL과 Home URL에는 모든 사용자가 접근 가능
                .antMatchers(HttpMethod.POST, "/api/**")
                .hasAnyRole("USER", "ADMIN")
                .antMatchers("/admin/**").hasRole("ADMIN")
                // Home과 로그인 URL을 제외한 페이지는 관리자 혹은 가입된 유저만 접근 가능
                .anyRequest().authenticated().and() // 이외에는 인증된 사용자만 접근 가능
                .oauth2Login() // oauth2Login 설정
                .authorizationEndpoint().baseUri("/login/oauth2").and()
                .redirectionEndpoint().baseUri("/*/oauth2/code/*").and()
                .userInfoEndpoint() // oauth2Login 성공 이후의 설정
                .userService(customOAuth2UserService).and() // 로그인 성공 이후의 task는 customOAuth2UserService에서 처리
                .successHandler(oAuth2AuthenticationSuccessHandler)
                .failureHandler(oAuth2AuthenticationFailureHandler).and()
                // JWT 토큰 인증을 위한 Filter 등록
                .addFilterBefore(new JwtFilter(), UsernamePasswordAuthenticationFilter.class)
                .csrf().disable()
                .formLogin().disable()
                .httpBasic().disable()
                .cors().and()
                .logout().logoutSuccessUrl("/");

3) AuthenticationManager

유저의 요청을 AuthenticationFilter에서 Authentication 객체로 변환 -> AuthenticationManager로 전달 -> AuthenticationProvider에서 인증 수행 -> 인증 성공 시 Authentication 객체의 authenticated 필드가 true로 세팅 -> Authentication 객체 리턴 -> SecurityContext에 저장


References

0개의 댓글