user13034249
user13034249

Reputation:

spring security config for authenticated users

Good day. I would like to know how to block access to the registration page for users who have already been authenticated

Right now my configuration looks like this:

@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();
    }

Upvotes: 0

Views: 120

Answers (1)

Ajit Kumar Singh
Ajit Kumar Singh

Reputation: 378

You can directly write the if condition in your controller to access the login page as below code

@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:/";
    }

Upvotes: 3

Related Questions