파워노트

[ skeleton ] spring boot security ( web login ) 본문

spring boot

[ skeleton ] spring boot security ( web login )

파워킴 2021. 11. 26. 01:00
반응형

spring boot security 

 

   이전글에서 api 기반의 security를 설정하였다. 그러나 이번에는 AdminLte 등을 통한 web 기반의 사이트를 설정하는것이다. 

 

security 설정.

  • spring boot security config 
    @Slf4j
    @Configuration
    @EnableGlobalMethodSecurity(securedEnabled = true)
    // @EnableGlobalMethodSecurity(    // Method 단위 시큐리티 처리.
    //        prePostEnabled = true,  // Spring Security의 @PreAuthorize, @PreFilter /@PostAuthorize, @PostFilter어노테이션 활성화 여부
    //        securedEnabled = true,  // @Secured어노테이션 활성화 여부
    //        jsr250Enabled = true)   // @RoleAllowed 어노테이션 사용 활성화 여부
    @EnableWebSecurity  // EnableWebSecurity 를 입력하는 순간 기존 Spring의 설정을 무시하고 내가 설정하겠다고 지정하는 것임.
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Bean
        public PasswordEncoder passwordEncoder(){
            return new BCryptPasswordEncoder();
        }
    
        /**
         * 추가적인 provider가 구현이 필요한경우 포함 가능함.
         * @param auth
         * @throws Exception
         */
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                    .withUser("aaaa@gmail.com")
                    .password(passwordEncoder().encode("aaaa1234")).roles("USER")
                    .and()
                    .withUser("superuser")
                    .password(passwordEncoder().encode("superuser"))
                    .roles("USER").roles("ADMIN");
        }
    
        @Override // ignore check swagger resource 해당 url은 시큐리티 처리 안함.
        public void configure(WebSecurity web)  throws Exception  {
            //        super.configure(web);
    //        web.ignoring().antMatchers("/swagger-ui/**","/swagger-resources/**","/v2/api-docs/**", "/sample/**");
            web.ignoring().antMatchers("/", "/index","/vendor/**", "/css/**", "/images/**", "/js/**", "/error/**" );
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
    //        super.configure(http);
    
            http
                .csrf().disable()
                .authorizeRequests()  // 요청을 어떻게 보안을 걸것이냐에 대한 설정.
                    .antMatchers("/", "/main","/regist").permitAll()
                    .antMatchers("/hello").hasRole("MASTER")
                    .anyRequest().authenticated() // 이외에는 인증이 필요하다.
                    .and()
                .formLogin()          // 로그인 페이지 관련. 이항목이 없다면 403 페이지 오류가 발생.
                    .loginPage("/login").permitAll()  // 사용자 페이지 구성을 위해서는 해당 항목을 설정.
                    .loginProcessingUrl("/j_spring_security_check").permitAll()
                    .usernameParameter("userid")
                    .passwordParameter("password")
                    .successHandler( new CustomLoginSuccessHandler("/main") )
                    .failureHandler( new CustomLoginFailureHandler("/login") )
                    .and()
                .logout()             // 로그아웃시 어떻게 처리 할것이냐.
                    .logoutSuccessUrl("/login").permitAll()   // logout 이 되고 나서 가는 페이지 설정.
                    .invalidateHttpSession(true)  // session 정보를 지우고 무효화.
    //                .and()
    //            .exceptionHandling()  // Exception Handle 의 경우  필요한경우에만 설정
    //                // 로그인은 됐으나 Role 접근이 안되는 경우. '권한 없음 페이지. 403 Status 처리.'
    //                .accessDeniedHandler(new CustomAccessDeniedHandler())
    //                // 비로그인 상태. 인증 하지 않은 상황에서 호출됨으로 401.html 페이지 호출 이후  로그인 할수 있는 페이지 이동 가이드가 필요함.
    
    //                // authenticationEntryPoint를 설정시 로그인 페이지를 호출하지 않을 수 있다.
    //                .authenticationEntryPoint(new CustomAuthenticationEntryPoint())
                ;
        }
    }​

 

PasswordEncoder

 

  • 비밀번호 암호화 처리시 내부적으로 난수화 시켜주어 비밀번호를 안전하게 보관할수 있다. 
  • 단방향 암호로 처리 되어  난수화된 암호를 풀수는 없다. 비밀번호를 까먹으면 찾을수 없는것이다. 

 

 Configure Method 

  •  Spring boot Security에는 여러가지를 설정할수 있는 config method를 제공한다.
  • AuthenticationManagerBuilder​
    • 인증 처리 방식에 대한 설정. 메모리, DB, 및 사용자 지정 , provider 지정
  •  configure(WebSecurity web)
     
    •  web.ignore등을 통해 security 를 적용에서 제외 하는 설정등을 할 수있다.
  • configure(HttpSecurity http)​
    • security의 핵심 설정. 
    • .csrf().disable() :   csrf 비활성   활성화시에는  webpage에서  csrf 토큰을 함께 서버쪽으로 전달되어야 오류가 나지 않는다. 
    • authorizeRequests() :  각 유입 경로에 대한 권한 설정
    • formLogin()  :  로그인페이지 및 로그인 프로세서에 대한 설정.
    • logout()    :   logout 시 경로 설정 및 처리. 
    • exceptionHandling() : 현재는 주석으로 막고 동작하지 않도록 설정을 하였으나,
      • accessDeniedHandler : ( 403error custom 가능 ) 경우에 따라서는  인증은 (일반유저 )되었으나 권한(마스터 유저)이 부족하여 진입하지 못하는 경우 custom하게  webpage를 구성할때 사용할 수 있다.]
      •  authenticationEntryPoint :  ( 401error custom 가능  ) 권한없이 페이지 접근을 했을때.. 접근할수 없습니다라는 페이지로 이동하거나 하여 custom 하게 webpage를 구성할 수 있다.   이설정이 없다면  접근할 수 없는 페이지 접근시 로그인 페이지로 자동 이동 된다. 

 

마무리 

  • spring security 는 기본적이면서도 항상 해깔리고 복잡한듯 하다.
  • 잘 숙지하고 정리해 두자. 

 

반응형
Comments