Spring Security 적용해보기

정미·2021년 11월 17일
0

Spring Security

목록 보기
1/2

Spring Security 설정

  • Security Config
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) {
        web.ignoring()
            .antMatchers("/assets/**"); // 이 요청들에 대해서는 spring security 필터 체인을 적용하지 않겠다
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/my-page").hasAnyRole("USER", "ADMINS")    // 인증 영역 설정
                .anyRequest().permitAll()   // 익명 영역
                .and()
            .formLogin()
                .defaultSuccessUrl("/")
                .permitAll()
                .and()
        ;
    }
}
  • 이 상태에서 어플리케이션을 띄우면 console 창에 비밀번호를 출력해준다.
    Using generated security password: (임시 비밀번호)
  • localhost:8080/my-page로 접속

    • Security Config 파일에서 설정한
      .antMatchers("/my-page").hasAnyRole("USER", "ADMINS")중 USER나 ADMINS 권한을 가지고 있지 않기 때문에 Spring Security가 자동으로 login 페이지로 redirect 시켜주었다.
    • default Username은 user, Password는 스프링 시큐리티가 console 창에 띄어준 임시 비밀번호
  • 로그인 후

    역시나 권한이 없기 때문에 403 Forbidden 에러 페이지가 보인다.

    • console
    DEBUG 10612 --- [  XNIO-1 task-2] s.s.w.c.SecurityContextPersistenceFilter:107 : Set SecurityContextHolder to SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=org.springframework.security.core.userdetails.User [Username=user, Password=[PROTECTED], Enabled=true, AccountNonExpired=true, credentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[]], Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=wTtczobIl39mmrSL5DuBoWVbSnv9X_b6H2ACCmyd], Granted Authorities=[]]]
    DEBUG 10612 --- [  XNIO-1 task-2] o.s.s.w.s.HttpSessionRequestCache       :114 : Loaded matching saved request http://localhost:8080/my-page
    DEBUG 10612 --- [  XNIO-1 task-2] o.s.s.w.a.i.FilterSecurityInterceptor   :246 : Failed to authorize filter invocation [GET /my-page] with attributes [hasAnyRole('ROLE_USER','ROLE_ADMINS')]
    DEBUG 10612 --- [  XNIO-1 task-2] o.s.s.w.access.AccessDeniedHandlerImpl  :61 : Responding with 403 status code

    첫번째 줄에서 Granted Authorities=[]로 권한이 null이다.
    마지막 줄에서 403 Forbidden으로 응답했음을 알 수 있다.

권한 설정

매번 바뀌는 사용자 비밀번호를 콘솔 창에서 띄어주고 복사해서 사용하는 것은 불편하다.
바뀌지 않는 기본 계정을 하나 만들어보자

  • UserDetailsServiceAutoConfiguration 클래스 확인
    User user = properties.getUser();
    String password = user.getPassword();
    우리가 설정해주고자 하는 유저 계정 정보를 property에 넣어주어야한다는 것을 알 수 있다.
  • application.yml
    security:
      user:
        name: user
        password: (비밀번호)
        roles: USER
    우리가 원하는 비밀번호를 가지고 있는 User를 만들어줄 수 있다. (추후 개선)
  • 다시 localhost:8080/my-page로 접속
    로그인창에서 위의 user 정보로 로그인하면

    my-page.html이 뜬다!
  • console
    DEBUG 17904 --- [  XNIO-1 task-1] w.a.UsernamePasswordAuthenticationFilter:315 : Set SecurityContextHolder to UsernamePasswordAuthenticationToken [Principal=org.springframework.security.core.userdetails.User [Username=user, Password=[PROTECTED], Enabled=true, AccountNonExpired=true, credentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[ROLE_USER]], Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=9XjXtSGtv9iF5_OHVSVlDMxbgsO8UK8KSWHUazEQ], Granted Authorities=[ROLE_USER]]
    DEBUG 17904 --- [  XNIO-1 task-1] o.s.s.web.DefaultRedirectStrategy       :57 : Redirecting to http://localhost:8080/my-page
    첫번째 줄에서 Granted Authorities=[ROLE_USER]] 로그인한 유저가 ROLE_USER라는 권한을 가지고 있음
    또한 콘솔창에 password 관련 log를 출력하지 않는다.

0개의 댓글