I’m trying to make an endpoint accessible while not logged in with spring-security. But when I try to open the url, I always get redirected to the spring login page.
My config-class:
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig
{
@Bean
@Order(SecurityProperties.BASIC_AUTH_ORDER)
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception
{
log.debug("securityFilterChain() bean called");
http.authorizeHttpRequests(auth -> {
// auth.requestMatchers("/register").permitAll();
auth.requestMatchers("/register").anonymous();
// auth.requestMatchers("/register").authenticated();
auth.anyRequest().authenticated();
});
http.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.ALWAYS));
http.formLogin(Customizer.withDefaults());
http.httpBasic(Customizer.withDefaults());
http.csrf(AbstractHttpConfigurer::disable);
http.headers(headers -> headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable));
return http.build();
}
}
The controller:
@Controller
@AllArgsConstructor
@SessionAttributes({"registerError", "redirect"})
public class UserController
{
private AuthenticationService authenticationService;
// @PreAuthorize("permitAll()")
@Transactional
@GetMapping("/register")
public String createUser(ModelMap model, HttpServletRequest request)
{
log.info("createUser() called");
model.put("userDto", new UserDto());
request.getSession().setAttribute("redirect", "redirect:register");
return "signup";
}
// @PreAuthorize("permitAll()")
@Transactional
@PostMapping("/register")
public String registerUser(ModelMap model, HttpServletRequest request, @Valid UserDto userDto)
{
log.info("registerUser() called with userDto={}", userDto);
try {
authenticationService.registerUser(userDto);
} catch (DuplicateKeyException e)
{
model.put("userDto", userDto);
model.put("registerError", "A user with this name already exists.");
return "redirect:register";
}
model.remove("registerError");
request.getSession().removeAttribute("redirect");
return "redirect:/";
}
}
I’ve configured my application.properties like this:
server.port=2345
spring.mvc.servlet.path=/
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
When I’m logged in and try to access the /register endpoint, I get a 403 as expected, but when logged out, I can’t access /register. Does anyone know what I’m doing wrong?
I also tried some combinations with the commented-out code, but nothing enabled the /register endpoint for non-logged-in users.