냐냐한 IT/냐냐한 Spring Boot

Spring Boot - Security 사용하기 (인메모리)

소소하냐 2019. 10. 12. 16:51

아래 소스들은 이전 포스팅 중 Spring Boot + MyBatis 프로젝트 연습의 MyBatis - Join 매핑하기 소스 기준으로 추가된 내용입니다. 참고하세요. 

 

이번 포스팅에서는 Spring 공식 가이드 내용 기준으로 Security를 설정해보기로 했습니다. 실제 개발 시에는 인메모리로 사용하지 않겠지만 DB로 접근하여 로그인하는 부분은 차후 진행하기로 하고 우선은 인메모리를 사용하는 Spring 공식 가이드를 따라 해 보았습니다.

 

Spring Boot - Security 사용 및 인메모리 설정

 

1. pom.xml에 추가 

<dependencies>
    ...
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
    ...
</dependencies>

2. Spring Security가 classpath에 있는 경우 Spring Boot는 "기본" 인증으로 모든 HTTP endpoint를 자동으로 보호한다. 즉, pom.xml에 위 내용을 추가하기만 해도 HTTP 요청 시 "기본" 인증으로 로그인 페이지로 이동하게 된다. (http://localhost:8080/ 을 요청하면 http://localhost:8080/login로 이동)

따로 생성하지 않은 로그인 페이지로 자동으로 redirect 

3. 보안 처리할 경로와 보안 처리하지 않을 경로, 로그인 페이지 설정 등 보안 설정을 추가로 사용자 정의
: WebSecurityConfigurerAdapter을 상속받아 일부 웹 보안 구성을 설정하기 위해 특정 몇 가지 메서드를 override 하는 WebSecurityConfig 클래스 생성 

package com.sosohanya.leveldiary;

//...import 생략...

@Configuration
@EnableWebSecurity  //@EnableWebSecurity : Spring Security의 웹 보안 지원을 활성화하고 Spring MVC 통합을 제공
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	//configure(HttpSecurity http) : 보안 처리할 경로와 처리하지 않을 경로 정의 
	@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .permitAll()
                .and()
            .logout()
                .permitAll()
                .and();
    }

    @Bean //<-- 이 부분을 빼먹어서 '자격 증명에 실패하였습니다' 메세지를 찾는다고 고생. 주의!!!
    @Override
    public UserDetailsService userDetailsService() {
        //인메모리에 username, password, role 설정 
        UserDetails user =
             User.withDefaultPasswordEncoder()
                .username("user") 
                .password("pwd")
                .roles("USER")
                .build();
        
        System.out.println("password : " + user.getPassword());

        return new InMemoryUserDetailsManager(user);
    }
	
}

     - 로그인 시도 시, 맞는 username / password 입력하여도 '자격 증명에 실패하였습니다.'라는 오류 문구로 로그인 실패 
        :
UserDetailsService를 반환하는 userDetailsService() 메서드에 @Bean 추가로 해결

 

    - userDetailsService() 메서드를 정의하지 않은 경우, 기본 개발 구성이 username:user, password:임의의 UUID로 UserDetailService 인터페이스의 in-memory 구현을 생성 

userDetailsService() 메서드를 정의하지 않은 경우, username은 user로 password는 위 security password 사용하여 로그인이 가능

4. 이 내용 git : add spring-security 변경 내용 보기 [새창] 

 

참고 사이트 : GETTING STARTED - Securing a Web Application [새창]

 

h2-console 접속 문제 해결

 

1. 설정 후 http://localhost:8080/h2-console 접근 시 로그인 페이지로 redirect 하는 문제 해결 
   : 아래 소스의 주석 1, 2, 3번 순서대로 차례로 추가하면서 확인해보면 변화를 알 수 있다. 

	@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/h2-console/**").permitAll() //1. h2-console 에서 접근할 수 있도록 설정 
                .anyRequest().authenticated()
                .and()
            .csrf() 
            	.ignoringAntMatchers("/h2-console/**") //2. csrf 설정으로 h2-console 콘솔에서 접속 시도하면 인증화면으로 변경되는 문제 해결 
            	.and()
        	.headers()
        		.frameOptions().sameOrigin() //3. h2-console 콘솔 접속 후 화면 표시 이상 해결 
        		.and()
            .formLogin()
                .permitAll()
                .and()
            .logout()
                .permitAll()
                .and();
    }

 

2. 이 내용 git : spring security and h2-console connect 변경 내용 보기 [새창]