1. 개요

이 기사는 사용자가 XML을 사용하지 않고 Spring Security를 ​​쉽게 구성할 수 있도록 하는 Spring Security용 Java 구성에 대한 소개 입니다.

Java 구성은 Spring 3.1 의 Spring 프레임워크에 추가되었고 Spring 3.2 의 Spring Security로 확장되었으며 @Configuration 어노테이션이 달린 클래스에 정의됩니다 .

2. 메이븐 설정

Maven 프로젝트에서 Spring Security를 ​​사용하려면 먼저 pom.xml 프로젝트에 spring-security-core 의존성이 있어야 합니다 .

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>
    <version>5.3.3.RELEASE</version>
</dependency>

최신 버전은 항상 여기 에서 찾을 수 있습니다 .

3. Java 구성을 통한 웹 Security

Spring Security Java 구성의 기본 예제부터 시작하겠습니다.

@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) 
      throws Exception {
        auth.inMemoryAuthentication().withUser("user")
          .password(passwordEncoder().encode("password")).roles("USER");
    }
}

알다시피 구성은 기본 메모리 내 인증 구성을 설정합니다. 또한 Spring 5부터 PasswordEncoder 빈이 필요합니다.

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

4. HTTP Security

Spring에서 HTTP Security을 활성화하려면 SecurityFilterChain 빈을 생성해야 합니다.

@Bean 
 public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.authorizeRequests()
      .anyRequest().authenticated()
      .and().httpBasic();
    return http.build();
}

위의 구성은 응용 프로그램에 대한 모든 요청이 양식 기반 로그인 또는 HTTP 기본 인증으로 인증되도록 합니다.

또한 다음 XML 구성과 정확히 유사합니다.

<http>
    <intercept-url pattern="/**" access="isAuthenticated()"/>
    <form-login />
    <http-basic />
</http>

5. 양식 로그인

흥미롭게도 Spring Security는 활성화된 기능을 기반으로 제출된 로그인을 처리하는 URL에 대한 표준 값을 사용하여 로그인 페이지를 자동으로 생성합니다.

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.authorizeRequests()
      .anyRequest().authenticated()
      .and().formLogin()
      .loginPage("/login").permitAll();
    return http.build();
}

여기에서 자동으로 생성된 로그인 페이지는 빠르게 시작하고 실행하는 데 편리합니다.

6. 역할을 통한 권한 부여

이제 역할을 사용하여 각 URL에 대한 몇 가지 간단한 인증을 구성해 보겠습니다.

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.authorizeRequests()
      .antMatchers("/", "/home").access("hasRole('USER')")
      .antMatchers("/admin/**").hasRole("ADMIN")
      .and()
      // some more method calls
      .formLogin();
    return http.build();
}

type-safe API( hasRole )와 표현식 기반 API( 액세스 를 통해) 를 모두 사용하는 방법에 주목하십시오 .

7. 로그아웃

Spring Security의 다른 많은 측면과 마찬가지로 로그아웃에는 프레임워크에서 제공하는 몇 가지 훌륭한 기본값이 있습니다.

기본적으로 로그아웃 요청은 세션을 무효화하고 모든 인증 캐시를 지우고 SecurityContextHolder 를 지우고 로그인 페이지로 리디렉션합니다.

다음은 간단한 로그아웃 구성입니다.

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.logout();
    return http.build();
}

그러나 사용 가능한 핸들러를 더 많이 제어하려는 경우 다음과 같이 더 완전한 구현이 표시됩니다.

@Bean
 public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.logout().logoutUrl("/my/logout")
      .logoutSuccessUrl("/my/index")
      .logoutSuccessHandler(logoutSuccessHandler) 
      .invalidateHttpSession(true)
      .addLogoutHandler(logoutHandler)
      .deleteCookies(cookieNamesToClear)
      .and()
      // some other method calls
    return http.build();
}

8. 인증

Spring Security로 인증을 허용하는 또 다른 방법을 살펴보겠습니다.

8.1. 메모리 내 인증

간단한 메모리 내 구성부터 시작하겠습니다.

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) 
  throws Exception {
    auth.inMemoryAuthentication()
      .withUser("user").password(passwordEncoder().encode("password")).roles("USER")
      .and()
      .withUser("admin").password(passwordEncoder().encode("password")).roles("USER", "ADMIN");
}

8.2. JDBC 인증

이를 JDBC로 이동하려면 애플리케이션 내에서 데이터 소스를 정의하고 이를 직접 사용하기만 하면 됩니다.

@Autowired
private DataSource dataSource;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) 
  throws Exception {
    auth.jdbcAuthentication().dataSource(dataSource)
      .withDefaultSchema()
      .withUser("user").password(passwordEncoder().encode("password")).roles("USER")
      .and()
      .withUser("admin").password(passwordEncoder().encode("password")).roles("USER", "ADMIN");
}

물론 위의 두 예제 에서 섹션 3에 설명된 대로 PasswordEncoder 빈도 정의해야 합니다.

9. 결론

이 빠른 사용방법(예제)에서는 Spring Security용 Java 구성의 기본 사항을 살펴보고 가장 간단한 구성 시나리오를 보여주는 코드 샘플에 중점을 두었습니다.

Security footer banner