Spring

인증 된 사용자를위한 스프링 Security 구성

기록만이살길 2021. 3. 20. 15:03
반응형

인증 된 사용자를위한 스프링 Security 구성

1. 질문(문제점):

좋은 날. 이미 인증 된 사용자의 등록 페이지 접근을 차단하는 방법을 알고 싶습니다.

지금 내 구성은 다음과 같습니다.

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/registration").permitAll()
                .and()
                    .formLogin()
                    .loginPage("/login")
                    .defaultSuccessUrl("/hello")
                    .permitAll()
                .and()
                    .logout()
                    .logoutSuccessUrl("/hello")
                    .permitAll();
    }

2. 해결방안:

컨트롤러에 if 조건을 직접 작성하여 아래 코드와 같이 로그인 페이지에 액세스 할 수 있습니다.

@GetMapping("/login")
    public String loginPage(Model model) {
        User user = new User();
        model.addAttribute("user", user);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
            return "/login";
        }
        return "redirect:/";
    }
65638119
반응형