Spring Security 초기설정

Sunset·2023년 6월 22일
0

SpringSecurity

목록 보기
1/1

pom.xml 에 스프링 시큐리티 추가

<!-- Spring Security -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-security</artifactId>
</dependency>

혹시 몰라 그래들도

implementation 'org.springframework.boot:spring-boot-starter-security'

실행 시 로그에 password가 나타나며,
디펜던시 추가만 해줘도 localhost:8080/으로 접속하면 아래와 같이 로그인 화면을 알아서 띄어줍니다.

시큐리티 설정할 클래스를 만들어 줍니다.

@Configuration
@EnableWebSecurity					//deprecated로 경고 뜹니다. 
public class SecurityCofing extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    
        http.
        		authorizeRequests()
                .anyRequest().authenticated();           
        http.
        		formLogin()
                .loginPage("/loginPage")                 //사용자 정의 로그인 페이지
                .defaultSuccessUrl("/")                  //로그인 성공 후 이동 페이지
                .failureUrl("/login")                    //로그인 실패 후 이동 페이지
                .usernameParameter("userId")             //아이디 파라미터명 설정
                .passwordParameter("passwd")             //패스워드 파라미터명 설정
                .loginProcessingUrl("/login_proc")       //로그인 form action url
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override                            //로그인 성공 후 핸들러
                    public void onAuthenticationSuccess(HttpServletRequest request,
                                                        HttpServletResponse response,
                                                        Authentication authentication)
                            throws IOException, ServletException {
                        System.out.println("authentication == " + authentication.getName());
                        response.sendRedirect("/");
                    }
                })
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override                           //로그인 실패 후 핸들러
                    public void onAuthenticationFailure(HttpServletRequest request,
                                                        HttpServletResponse response,
                                                        AuthenticationException exception)
                            throws IOException, ServletException {
                        System.out.println("exception == " + exception);
                        response.sendRedirect("/login");
                    }
                });
    }
}

@EnableWebSecurity

@Documented
@Import({WebSecurityConfiguration.class, SpringWebMvcImportSelector.class, OAuth2ImportSelector.class, HttpSecurityConfiguration.class})
@EnableGlobalAuthentication
@Configuration
public @interface EnableWebSecurity {
    boolean debug() default false;
}

@EnableWebSecurity 어노테이션 안에는 시큐리티 설정관련 4가지의 클래스들이 임포트 되어있습니다.

WebSecurityConfigurerAdapter 클래스를 상속받아 configure메서드를 오버라이딩하여 작성합니다.

메서드기능
formLogin()form을 지정하는 메서드
loginPage()사용자가 지정한 로그인 페이지 설정
defaultSuccessUrl()로그인 성공 시 이동할 페이지 설정
failureUrl()로그인 실패 시 이동할 페이지 설정
usernameParameter()화면 form에서 username에 사용할 파라미터명 설정
passwordParameter()화면 form에서 password에 사용할 파라미터명 설정
loginProcessingUrl()form에 action 속성에 해당하는 설정
successHandler()성공 시 핸들러
failureHandler()실패 시 핸들러

application.properties에 프로퍼티 설정도 가능합니다.
spring.security.user.name=user
spring.security.user.password=1234

0개의 댓글

Powered by GraphCDN, the GraphQL CDN