Spring Security

스프링부트 스프링시큐리티 연동하기(3) WebSecurityConfigurerAdapter/LoginController

dev.mk 2019. 6. 23. 20:52
반응형

1.SecurityConfig.java 작성

(SecurityConfig.java)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
 
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {  
    
    @Autowired 
    AuthProvider authProvider;
 
    @Autowired 
    AuthSuccessHandler authSuccessHandler;
    
    @Autowired 
    AuthFailureHandler authFailureHandler;
 
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authProvider);
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        
        //CROF 설정을 해제합니다
        //초기 개발시에만 설정합니다
        http.csrf().disable();
        
        http.authorizeRequests() 
            .antMatchers("/user/**").access("hasRole('ROLE_USER')")    // /user/** 경로의 경우 ROLE_USER의 권한을 가진 경우에 허용한다
            .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")     // /admin/** 경로의 경우 ROLE_ADMIN의 권한을 가진 경우에 허용한다
            
            // //누구나 접속할 수 있는 페이지이기 때문에 누구나 접근이 가능하다 (.permitAll())
            .antMatchers("/home"
                    ,"/login/login"
                    , "/login/login-error"
                    , "/join/join"
                    , "/join/idCheck"
                    , "/login/find"
                    , "/join/insert"
            ).permitAll()
            .antMatchers("/**").authenticated();  //기타 /** 의 경로는 인증을 필요로 한다
        
        http.formLogin() 
            .loginPage("/login/login")  //로그인 페이지는 /, /login (같은 페이지)두 페이지 에서 로그인을 실행할 것이다
            .loginProcessingUrl("/login/login-processing"//로그인 버튼을 누를시 /login-processing 경로로 
            .usernameParameter("id")  //input name 파라미터로 "id"를 받는다.
            .passwordParameter("password"//input name 파라미터로 "password"를 받는다.
            .failureHandler(authFailureHandler) //로그인 실패시 수행하는 클래스
            .successHandler(authSuccessHandler); // 로그인 성공시 수행하는 클래스
        
        http.logout() 
            .logoutRequestMatcher(new AntPathRequestMatcher("/login/logout")) //logout 경로로 요청이 들어올 경우 이 경로로 리다이렉트 하고 세션 초기화
            .logoutSuccessUrl("/login/login")  // 이 경로로 리다이렉트 하고
            .invalidateHttpSession(true); // 세션 초기화
        
    }
    
    //JSP의 리소스 파일이나 자바스크립트 파일이 저장된 경로는 무시를 한다
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
        .antMatchers("/api/**""/resources/**");
    }
    
}
 

각 기능 설명은 소스안에 주석으로 대체한다.

WebSecurityConfigurerAdapter를 상속받아 설정을 한다.

일반 스프링 프로젝트 security-contex.xml에 기능들을 태그로 정의하는 것처럼 자바로 정의 한다고 생각하면 된다.

이 컨피그 자바에서 앞서 작성했던 인증 구현체, 로그인 성공 핸들러,실패 핸들러들을 @Autowired로 의존성 주입해준 뒤 핸들러안에 설정한다.

위 소스에는 없지만 자동로그인(remember-me), 중복로그인 방지(maximumSessions) 등 부가적인 스프링시큐리티 기능들을 설정 할 수 있다.

이제 로그인페이지, 에러페이지, 회원가입페이지를 정의한 컨트롤러를 작성한다.

2.LoginController.java 작성

(LoginController.java)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
 
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
 
 
@Controller
public class LoginController {
    
    @Autowired
    SecurityService securityService;
    
    //회원가입 페이지 이동
    @GetMapping("/join/join")
    public String join() {
        return  "login/join";
    }
    
    //로그인 페이지 이동
    @RequestMapping("/login/login")
    public ModelAndView lgoin(@RequestParam(value="msg", required=falseString msg) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg",msg);
        mv.setViewName("/login/login");
        return mv;
    }
    
    //로그인 에러페이지 이동
    @GetMapping("/login/login-error")
    public String error() {
        return  "login/error";
    }
    
    //아이디 중복체크
    @PostMapping("/join/idCheck")
    @ResponseBody
    public String idCheck(@RequestParam String inputId) throws Exception{
        Member member = securityService.getSelectMeberInfo(inputId);
        String canUse = member != null ? "" : "Y";
        return canUse;
    }
    
    //회원가입 Insert 
    @PostMapping("/join/insert")
    public String setInsertMember(Member member) throws Exception{
        if(securityService.setInsertMember(member) > 0){
            return  "login/login";    
        }else {
            return  "join/join";
        }
    }
    
    //로그인 성공후 이동페이지
    @RequestMapping("/home")
    public String home() {
        return  "home/home";
    }
    
}
로그인컨틀롤러 내용의 대한 jsp 디렉토리구조이다.
다음 포스트에는 jsp 화면위주의 내용을 작성하겠다.
반응형