Spring Boot

Spring Security를 이용한 로그인/로그아웃

dlwltn98 2023. 2. 4. 12:24

스프링 시큐리티

 - 사용자 정의가 가능한 인증 및 엑세스 제어 프레임워크 

 - Java 애플리케이션에 인증 및 권한 부여를 모두 제공하는데 중점을 둔 프레임워크

 

Maven 추가 

 - 스프링 시큐리티와 Thymeleaf 추가함

 

 

추가하고 실행하면 처음에 로그인 화면이 뜸 (기본 로그인 페이지 제공)

id : user / pw : 콘솔에 뜸

 

 

SecurityConfig.java

 - SecurityConfig 파일을 생성하여 스프링 시큐리티 관련 설정을 할 수 있음

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests().requestMatchers(
                new AntPathRequestMatcher("/**")).permitAll()
            .and()
                .formLogin()
                .loginPage("/user/login")
                //.loginProcessingUrl("/loginProc")
                .usernameParameter("userId")
                .passwordParameter("pwd")
                .defaultSuccessUrl("/")
            .and()
                .logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/user/logout"))
                .logoutSuccessUrl("/")
                .invalidateHttpSession(true)
            ;

        return http.build();

    }
    
    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    
    @Bean
    AuthenticationManager authenticationManager( AuthenticationConfiguration authenticationConfiguration
                                               ) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }
    
}

 - @Configuration : 스프링의 환경설정 파일임을 의미

 - @EnableWebSecurity : 모든 요청 URL이 스프링 시큐리티의 제어를 받도록 함

    + 내부적으로 SpringSecurityFilterChain이 동작하여 URL 필터가 적용된다고 함

 

- SecurityFilterChain이라는 Bean을 생성하여 스프링 시큐리티 세부 설정 가능

// 인증되지 않은 용청을 허락하는 코드, 수정 예정
http.authorizeHttpRequests().requestMatchers(
                new AntPathRequestMatcher("/**")).permitAll()

.antMatchers("/", "/user/login") : 로그인 과정 없이 누구나 접근 가능

.antMatchers("/private").hasRole("ADMIN") : 로그인된 계정이 Admin 권한을 가져야 접근 가능

// http 객체의 설정을 이어서 할 수 있게 해주는 메서드
.and() 

// 보안 검증은 formLogin방식 사용
.formLogin()

// 사용자 정의 로그인 페이지 경로
.loginPage("/user/login")

// 아이디 파라미터명 설정 (default : username)
.usernameParameter("userId")

// 패스워드 파라미터명 설정 (default : password)
.passwordParameter("pwd")

// 로그인 성공 후 이동 페이지
.defaultSuccessUrl("/")

.loginProcessingUrl("/user/login") : 로그인 Form Action Url

 - 실제 로그인을 진행하는 @PostMapping 방식의 메서드는 스프링 시큐리티가 대신처리함 → 구현할 필요 없음

 

// http 객체의 설정을 이어서 할 수 있게 해주는 메서드
.and()

// 로그아웃 처리
.logout()

// 로그아웃 처리 URL
.logoutRequestMatcher(new AntPathRequestMatcher("/user/logout"))

// 로그아웃 성공 후 이동할 페이지
.logoutSuccessUrl("/")

// 로그아웃시 생성된 사용자 세션 삭제
.invalidateHttpSession(true)

.deleteCookies() : 쿠키 삭제 

 

회원가입시 비밀번호를 암호화 해서 저장하기 위해 사용

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

 - 사용자 비밀번호는 보안을 위해 반드시 암호화해서 저장해야 함

 - 함호화를 위해 BCryptPasswordEncoder 클래스를 사용

 - BCryptPasswordEncoder : BCrypt 해싱 함수(BCrypt hashing function)를 사용해서 비밀번호를 암호화

 

스프링 시큐리티의 인증 담당

@Bean
AuthenticationManager authenticationManager( AuthenticationConfiguration authenticationConfiguration
                                               ) throws Exception {
    return authenticationConfiguration.getAuthenticationManager();
}

스프링 시큐리티에 등록해서 사용할 UserSecurityService는 UserDetailsService 인터페이스를 구현해야 함

 - UserDetailsService 인터페이스는 loadUserByUsername() 라는 메소드를 선언하고 있음

public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException {
    ...
}

 - 사용자가 로그인을 할 때 아이디를 입력하면 해당 아이디를 loadUserByUsername()메소드의 인자로 전달

 - 전달 받은 아이디의 정보가 없으면 UsernameNotFoundException 발생

 - 정보가 있을 경우엔 UserDetails인터페이스를 구현한 객체를 리턴 

 

 

 

출처 : 

https://spring.io/projects/spring-security

https://wikidocs.net/162150

 

'Spring Boot' 카테고리의 다른 글

Spring boot 프로젝트 생성, 설정  (0) 2023.01.20