OAuth2.0

 

API를 이용해서 다른 서비스에 있는 정보를 자신의 애플리케이션으로 가져와서 가공하고 무언가를 행하는 것은 중요한 기술입니다.

 

다른 서비스의 정보를 가져오고, 그 정보가 특정 사용자의 개인적인 정보일 때는 그 사용자의 허락과 가지고 오려는 서비스의 정해진 절차를 따라야 정보를 가져올 수 있습니다.
그때 사용할 수 있는 기술이 oauth입니다.

 

아주 옛날에는 Resource Owner에게 본인의 Resource Server의 id, password를 받아와서(이를테면 개인의 구글 아이디와 비밀번호), 직접 Resource Server에 접속하는 방법으로 사용하였으나 보안에 매우 취약해서 oauth 방식이 개발되었습니다.

 

 

동작 매커니즘


oauth를 이용한 애플리케이션을 운영하기 위해서 우리 애플리케이션을 구글에 먼저 사용등록을 합니다. 구글은 서비스를 식별할 수 있도록 client id와 client secret 두 개의 값을 발급해 줍니다. 우리는 이제 이것을 이용해서 애플리케이션을 운영해 나갑니다. 특히 client secret은 외부에 노출하면 안 됩니다.

이제 애플리케이션이 리소스를  사용하기 위해  사용자에게 허락을 받아야 합니다. 사용자는 애플리케이션을 이용해서 Resource server에 접속해 인증을 해줍니다.

 

사용자의 승인으로 resource server는 애플리케이션에서 code를 제공합니다. 여기서  한 번 더  code와, client id, client secret 3개의 정보를 담아 resource sever에 다시 보냅니다. resource sever는 자신이 보낸 code와 client id, client secret를 검증해서 access token를 보내줍니다. (*access token은 비밀번호처럼 사용되는 매우 중요한 정보입니다.)

애플리케이션은 access token을 이용해서 resource server에 접근하여 resoure를 획득하고  가공 후에  사용자에게 서비스를 제공합니다.

 

참고 강의

구글 API를 통해서 배우는 인증 (oauth 2.0)-생활코딩

https://opentutorials.org/course/2473/16571

 

구글 API를 통해서 배우는 인증 (oauth 2.0) - 생활코딩

수업소개 API를 사용하는데 큰 걸림돌은 인증입니다. 사용자에게 최적화된 서비스를 제공하기 위해서는 그 사용자의 정보에 접근할 수 있어야 합니다. 많은 서비스가 인증을 위한 방법으로 oauth

opentutorials.org

 

스프링애플리케이션에서 스프링 시큐리티를 사용할 때

 

“The type WebSecurityConfigurerAdapter is deprecated”

 

경고를 제거하는 방법✍🏻

 

 

 

많은 사람들은  아래 방법과 같은 WebSecurityConfigurerAdapter 추상 클래스를 확장하는 Spring 구성 클래스를 사용하는 데 익숙할 것입니다.

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
         
        // configure HTTP security...
         
    }
 
    @Override
    public void configure(WebSecurity web) throws Exception {
         
        // configure Web security...
         
    }      
}

해당 방법은

'Spring Security 버전 5.6.5' 또는 이전 버전'  

'Spring Boot 버전 2.6.8 또는 이전 버전'

에서는 문제가 없습니다.

 

그러나 프로젝트에서 Spring Security 5.7.1 이상 또는 Spring Boot 2.7.0 이상을 사용하는 경우 IDE

“The type WebSecurityConfigurerAdapter is deprecated” 경고가 표시됩니다.

 

그렇다면 Spring SecurityWebSecurityConfigurerAdapter 의 사용을 더 이상 사용하지 않는 이유 대안에 대해서 알아보겠습니다.

 

 


 

 

-이유🤷🏻‍♀️ 

스프링 프레임워크 개발자들은 사용자가 컴포넌트 기반 보안 구성으로 이동하기를 권하기 때문입니니다.

 


-대안🙆🏻‍♂️

WebSecurityConfigurerAdapterextends 하고 HttpSecurity WebSecurity 오버라이딩 하는 대신

아래 방법과 같이 SecurityFilterChain WebSecurityCustomizer 유형의 두 빈을 선언 합니다.

@Configuration
public class SecurityConfiguration {
         
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
     
    }
     
    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
         
    }
         
}

 


-예시💻

security configuration 의 컴포넌트 기반 접근방식으로 바꾸는 코드 예제입니다.

 

 

 

먼저 아래와 같이 WebSecurityConfigurerAdapter 를 사용하는 일반적인 security configuration class 를 살펴보겠습니다 .

 

기존)

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 
    @Bean
    public UserDetailsService userDetailsService() {
        return new ShopmeUserDetailsService();
    }
 
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
     
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/login").permitAll()
                .antMatchers("/users/**", "/settings/**").hasAuthority("Admin")
                .hasAnyAuthority("Admin", "Editor", "Salesperson")
                .hasAnyAuthority("Admin", "Editor", "Salesperson", "Shipper")
                .anyRequest().authenticated()
                .and().formLogin()
                .loginPage("/login")
                    .usernameParameter("email")
                    .permitAll()
                .and()
                .rememberMe().key("AbcdEfghIjklmNopQrsTuvXyz_0123456789")
                .and()
                .logout().permitAll();
 
        http.headers().frameOptions().sameOrigin();
    }
     
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/images/**", "/js/**", "/webjars/**"); 
    }
}

 

 

 

 

그리고 아래 대안법은 WebSecurityConfigurerAdapter를 사용하지 않은 예시입니다.

 

대안법)

package net.codejava;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
 
@Configuration
@EnableWebSecurity
public class SecurityConfiguration {
 
    @Bean
    public UserDetailsService userDetailsService() {
        return new ShopmeUserDetailsService();
    }
 
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
 
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
     
        http.authorizeRequests().antMatchers("/login").permitAll()
                .antMatchers("/users/**", "/settings/**").hasAuthority("Admin")
                .hasAnyAuthority("Admin", "Editor", "Salesperson")
                .hasAnyAuthority("Admin", "Editor", "Salesperson", "Shipper")
                .anyRequest().authenticated()
                .and().formLogin()
                .loginPage("/login")
                    .usernameParameter("email")
                    .permitAll()
                .and()
                .rememberMe().key("AbcdEfghIjklmNopQrsTuvXyz_0123456789")
                .and()
                .logout().permitAll();
 
        http.headers().frameOptions().sameOrigin();
 
        return http.build();
    }
 
    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring().antMatchers("/images/**", "/js/**", "/webjars/**");
    }
 
}

 

해당 방법은 스프링 기반 애플리케이션의 스프링 시큐리티 사용에 있어서

“The type WebSecurityConfigurerAdapter is deprecated”경고를 지우는 방법입니다.

 

, WebSecurityConfigurerAdapter의 메스드 오버라이딩 정의 방법 대신 SecurityFilterChainWebSecurityCustomizer 빈들을 선언해야 합니다.

 

만약 코드를 변경하지 않고 유지 보수하기 위해서는 Spring Boot 버전을 2.7.0 미만으로 유지하거나 Spring Security 버전을 5.7.1 이전으로 유지해야 합니다.

 

참고 
https://www.codejava.net/frameworks/spring-boot/fix-websecurityconfigureradapter-deprecated

Spring Security - How to Fix WebSecurityConfigurerAdapter Deprecated

Written by  Nam Ha Minh

 

Spring Security - How to Fix WebSecurityConfigurerAdapter Deprecated

DetailsWritten by  Nam Ha Minh Last Updated on 01 June 2022   |   Print  Email In this short article, I’d like to share how to get rid of the warning saying that “The type WebSecurityConfigurerAdapter is deprecated” in Spring-based application w

www.codejava.net

 

'개발 > Spring Security' 카테고리의 다른 글

OAuth2.0- OAuth2.0의 이해  (0) 2022.06.29

+ Recent posts