Request method 'POST' is not supported - spring

I'm trying to upgrade Spring Boot from 2.7.6 to 3.0.1. I have a problem during the login action. The following is my new WebSecurityConfig:
#Configuration
#EnableWebSecurity
public class WebSecurityConfig {
private final CustomUserDetailsService customUserDetailsService;
private final CustomizeAuthenticationSuccessHandler customizeAuthenticationSuccessHandler;
public WebSecurityConfig(CustomUserDetailsService customUserDetailsService, CustomizeAuthenticationSuccessHandler customizeAuthenticationSuccessHandler) {
this.customUserDetailsService = customUserDetailsService;
this.customizeAuthenticationSuccessHandler = customizeAuthenticationSuccessHandler;
}
#Bean
public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(customUserDetailsService);
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}
#Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
public AccessDeniedHandler accessDeniedHandler(){
return new CustomAccessDeniedHandler();
}
#Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests()
.requestMatchers("/").permitAll()
.requestMatchers("/login").permitAll()
.authenticated()
.and()
.csrf().disable()
.formLogin()
.successHandler(customizeAuthenticationSuccessHandler)
.loginPage("/login")
.failureUrl("/login?error=true")
.usernameParameter("email")
.passwordParameter("password")
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.invalidateHttpSession(true)
.logoutSuccessUrl("/login?logout=true")
.and()
.exceptionHandling()
.accessDeniedHandler(accessDeniedHandler())
.and()
.authenticationProvider(authenticationProvider());
http
.sessionManagement()
.maximumSessions(1)
.expiredUrl("/login?expired=true");
return http.build();
}
// This second filter chain will secure the static resources without reading the SecurityContext from the session.
#Bean
#Order(0)
SecurityFilterChain resources(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**").permitAll()
.anyRequest().permitAll())
.requestCache().disable()
.securityContext().disable()
.sessionManagement().disable();
return http.build();
}
}
Follow my CustomUserDetailService:
#Service
public class CustomUserDetailsService implements UserDetailsService {
private final UserRepository userRepository;
public CustomUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User findUserByEmail(String email) {
System.out.println(email);
User user = userRepository.findByEmail(email.toLowerCase());
System.out.println(user.getEmail());
return userRepository.findByEmail(email.toLowerCase());
}
#Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
User user = userRepository.findByEmail(email.toLowerCase());
if (user != null) {
List<GrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority( user.getRole()));;
return buildUserForAuthentication(user, authorities);
} else {
throw new UsernameNotFoundException("username not found");
}
}
private UserDetails buildUserForAuthentication(User user, List<GrantedAuthority> authorities) {
return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), authorities);
}
}
When I run the application I see the login page, but when I enter the credential and press submit I receive the error:
Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' is not supported]
and Tomcat shows:
HTTP Status 405 – Method Not Allowed Type Status Report
Message Method 'POST' is not supported.
I searched for a solution but really I don't understand where is the problem.

To use multiple HttpSecurity instances, you must specify a security matcher, otherwise the first SecurityFilterChain will process all requests, and no requests will reach the second chain.
See this section of the Spring Security reference documentation.
In your case the SecurityFilterChain called resources is matching all requests, because you don't have a security matcher.
Since the resources chain does not configure formLogin then Spring Security does not create the default /login POST endpoint.
You can fix this by changing requests to:
#Bean
#Order(0)
SecurityFilterChain resources(HttpSecurity http) throws Exception {
http
.securityMatchers((matchers) -> matchers
.requestMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**") // the requests that this SecurityFilterChain will process
)
.authorizeHttpRequests((authorize) -> authorize
.anyRequest().permitAll())
.requestCache().disable()
.securityContext().disable()
.sessionManagement().disable();
return http.build();
}
If you want more details on the difference between authorizeHttpRequests and requestMatchers you can check out this question.

This error typically occurs when the method in the controller is not mapped to a post request. Should be something like:
#RequestMapping(value = "/login", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView login(...

Related

Keycloak return 401 instead of 302 when token expire keyclaok

When the token expires Keycloak normally return 302(redirect to logout) ; however , I want to return 401 instead of 302 in the api response .
I am using spring boot framework , here the keyloack configuration
#KeycloakConfiguration
#EnableGlobalMethodSecurity(jsr250Enabled = true)
public class GlobalSecurityConfiguration extends KeycloakWebSecurityConfigurerAdapter {
#Autowired
public KeycloakClientRequestFactory keycloakClientRequestFactory;
#Bean
#Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public KeycloakRestTemplate keycloakRestTemplate() {
return new KeycloakRestTemplate(keycloakClientRequestFactory);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests()
.and()
.cors()
.and()
.csrf()
.disable()
.headers()
.frameOptions()
.disable()
.and()
.authorizeRequests()
.antMatchers("test/login").permitAll()
.anyRequest()
.authenticated();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
auth.authenticationProvider(keycloakAuthenticationProvider);
}
#Bean
#Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new NullAuthenticatedSessionStrategy();
}
// Starting from Keycloak Spring Boot Adapter 7.0.0,
// due to some issues, the automatic discovery of the Keycloak configuration
// from the application.properties (or application.yml) file will not work.
// To overcome this problem, we need to define a KeycloakSpringBootConfigResolver bean explicitly in a #Configuration class.
#Bean
public KeycloakConfigResolver KeycloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
}
but I can not reach in which place It sends 302 when token expire to change the response to 401
According to the documentation, you could use the exceptionHandling() method:
https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/config/web/server/ServerHttpSecurity.html#exceptionHandling(org.springframework.security.config.Customizer)
exceptionHandling
public ServerHttpSecurity
exceptionHandling​(Customizer<ServerHttpSecurity.ExceptionHandlingSpec>
exceptionHandlingCustomizer)
Configures exception handling (i.e. handles when authentication is
requested). An example configuration can be found below:
#Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
// ...
.exceptionHandling((exceptionHandling) ->
exceptionHandling
// customize how to request for authentication
.authenticationEntryPoint(entryPoint)
);
return http.build();
}
Parameters:
exceptionHandlingCustomizer - the Customizer to provide more options for the ServerHttpSecurity.ExceptionHandlingSpec
Returns:
the ServerHttpSecurity to customize
and according to this page, https://github.com/spring-projects/spring-boot/issues/10715
You could simply do:
http.exceptionHandling().authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));
However I think this will always return 401 UNAUTHORIZED on any (Authentication Exceptions) and not specifically Token Expired.
If you look at the documentation further, you can implement a custom ServerAuthenticationEntryPoint
https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/server/ServerAuthenticationEntryPoint.html
Example:
#Component
#Slf4j
public class GatewayAuthenticationEntryPoint implements ServerAuthenticationEntryPoint {
#Override
public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException e) {
exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
// resolve response status
if (ex instanceof AccessDeniedException) {
exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
} else exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
// compose error response
final ErrorResponse error = new ErrorResponse(ex, exchange.getRequest().getURI().getPath(),
exchange.getRequest().getMethod(), HttpStatus.UNAUTHORIZED);
exchange.getResponse()
.writeWith(getEncoder().encode(Mono.just(error), exchange.getResponse().bufferFactory(),
ResolvableType.forInstance(error), MediaType.APPLICATION_JSON,
Hints.from(Hints.LOG_PREFIX_HINT, exchange.getLogPrefix())));
return Mono.error(ex);
}
}

Spring Boot autologin after registration not working

I have a login and a registration page. I wanted to achieve the feature of autologin after the registration. I have gone through various docs and finally came up with this. Can someone figure out what went wrong here?
Web Security Configuration
#Configuration
#EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
public BCryptPasswordEncoder bCryptPasswordEncoder()
{
return new BCryptPasswordEncoder();
}
#Autowired
public UserDetailsService userDetailsService;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/register/**","/css/**","/js/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/welcome",true)
.permitAll()
.and()
.rememberMe()
.rememberMeParameter("rememberme")
.rememberMeCookieName("myLogin")
.tokenValiditySeconds(360*60*60)
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login?logout")
.invalidateHttpSession(true)
.clearAuthentication(true)
.deleteCookies("myLogin");
}
}
Controller
#Autowired
protected AuthenticationManager authenticationManager;
#Autowired
UserRepo repo;
#Autowired
BCryptPasswordEncoder bCryptPasswordEncoder;
#RequestMapping("/login")
public String loginpage()
{
return "index";
}
#RequestMapping("/welcome")
public String welcomePage()
{
return "welcome";
}
#RequestMapping(value = "/register", method = RequestMethod.GET)
public String register(Model model)
{
model.addAttribute("user", new User());
return "register";
}
#RequestMapping(value = "/register",method = RequestMethod.POST)
public String registerIt(#Valid #ModelAttribute("user")User user, BindingResult result, Model model, HttpServletRequest request)
{
if(result.hasErrors())
{
return "register";
}
Roles roles1=new Roles();
Roles roles2=new Roles();
roles1.setRoles("ADMIN");
roles2.setRoles("USER");
ArrayList<Roles> roleList=new ArrayList<>();
roleList.add(roles1);
roleList.add(roles2);
user.setRoles(roleList);
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
repo.save(user);
UsernamePasswordAuthenticationToken token=new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());
request.getSession();
token.setDetails(new WebAuthenticationDetails(request));
Authentication auth=authenticationManager.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(auth);
return "welcome";
}
Still, after the registration, the page redirects to the Login page itself. I am not able to figure out what went wrong.... Please help...
Try this to init the Auth:
Ref: org.springframework.security.web.authentication.AuthenticationFilter#successfulAuthentication
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
org.springframework.security.core.userdetails.UserDetails userDetails =
new YOURUserDetail( PARAMS );
//create instance of your AUTH object
Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, other params )
securityContext.setAuthentication(authentication);
SecurityContextHolder.setContext(securityContext);

Spring Security basic auth for REST Api single login needed?

I am using Spring Security basic auth for my REST API.
Initially I get unauthorized HTTP response status for unauthenticated secured routes.
If I provide the right credentials, I get a Ok HTTP response status, but after a single successful login, I can access all the secured routes without providing user credentials.
Here are my questions:
Is it the correct behaviour for basic authentication?
Why it happens?
My security config:
#Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserService userService;
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userService);
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
//J-
http.csrf().disable()
.authorizeRequests()
.antMatchers("/save")
.permitAll()
.and()
.authorizeRequests()
.antMatchers("/h2-console/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic();
//J+
//adding support for h2 console, otherwise crashes
http.headers().frameOptions().disable();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(authenticationProvider());
}
}
and here is the UserDetailsService's loadByUsername() method:
#Override
public UserDetails loadUserByUsername(String username) {
User user = userRepository.findByUsername(username);
if (user == null) {
throw new UserNotFoundException(username);
} else if (UserStatus.Deactivated.equals(user.getStatus())) {
throw new UserDeactivatedException(username);
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), Collections.singleton(new SimpleGrantedAuthority("USER")));
}
https://www.baeldung.com/spring-security-session
Refer mentioned link. For Restful API’s use stateless session policy

Wrong redirection in Spring MVC app

Im going to be quick. I have a Spring MVC project, and Im using Spring Security, so after I successfully log in the server redirects me to the application context instead of the index page. Any idea why this is happening, I suspect it may be a security problem, but so far I haven´t figure it out, so please I need help on this one.
My login form action is this: ${loginUrl}
And the redirection problem only happens the first time i try to log in, if I log out and log in again the server redirects me correctly.
Here is my code:
Web Security Config class:
#EnableWebSecurity
#Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
ServicioInicioSesion inicioSesion;
#Autowired
MessageSource messageSource;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/addUsuarios").permitAll()
.antMatchers("/roles/**", "/usuarios/**").hasAuthority("Administrador")
.antMatchers("/editarPerfil").authenticated()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login").defaultSuccessUrl("/index")
.permitAll()
.and()
.logout()
.invalidateHttpSession(true)
.clearAuthentication(true)
.logoutSuccessUrl("/login")
.and()
.exceptionHandling().accessDeniedPage("/403");
}
#Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/static/**");
}
#Bean(name = "authenticationManager")
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider auth = new DaoAuthenticationProvider();
auth.setUserDetailsService(inicioSesion);
auth.setMessageSource(messageSource);
auth.setPasswordEncoder(passwordEncoder());
return auth;
}
#Bean
public PasswordEncoder p`enter code here`asswordEncoder() {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
return passwordEncoder;
}
}
Index Controller class
#Controller
public class IndexController {
#RequestMapping(value = "/index", method = RequestMethod.GET)
public String showIndex() {
return "index";
}
}
Alberto. Try this one:
1 - replace value = "/index" by value = {"/","/index"}
2 - remove method parameter
#RequestMapping(value = {"/","/index"})
When you submit authentication form in the request you have POST data, but in your case you have RequestMethod.GET

Spring Security custom AuthenticationProvider authenticate method called twice

I am developing a Spring Boot that uses an API Key to authenticate. I have created a custom Authentication provider and the authenticate method is called twice. Can anyone tell me why it's being called twice?
This is my authenticate method:
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
ApiAuthenticationToken authenticationToken = (ApiAuthenticationToken) authentication;
/**
* Authenticate the token
*/
ValidateApiKeyRequest request = new ValidateApiKeyRequest(authenticationToken.getApiKey());
ValidateApiKeyResp resp = getValidateApiKeyCommand().execute(request);
/**
* Populate and return a new authenticaiton token
*/
return createSuccessAuthentication(resp);
}
and this is the createSuccessAuthentication method:
protected Authentication createSuccessAuthentication(final ValidateApiKeyResp resp) {
List<GrantedAuthority> authorities = Lists.newArrayList();
authorities.add(new SimpleGrantedAuthority("API_KEY"));
return new ApiAuthenticationToken(resp.getApiKey(), authorities, true);
}
this is the ApiAuthenticationToken constructor:
public ApiAuthenticationToken(final ApiKey apiKey, Collection<? extends GrantedAuthority> authorities, boolean authenticated) {
super(authorities);
setAuthenticated(true);
this.apiKey = apiKey;
}
This is my security configuration:
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher(CONFIGURATION_MATCHER)
.exceptionHandling().authenticationEntryPoint(restAuthenticationEntryPoint())
.and()
.addFilterBefore(apiKeyAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.csrf().disable()
.authorizeRequests().antMatchers(CONFIGURATION_MATCHER).authenticated()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authenticationProvider(apiKeyAuthenticationProvider());
Just in case anyone else has this issue:
The problem was related to my spring security configuration. I had several methods annotated with #Bean - see below
#Bean
public ApiKeyAuthenticationProvider apiKeyAuthenticationProvider() {
return new ApiKeyAuthenticationProvider(getValidateApiKeyCommand());
}
#Bean
public RestAuthenticationEntryPoint restAuthenticationEntryPoint() {
return new RestAuthenticationEntryPoint();
}
#Bean
public ApiKeyAuthenticationFilter apiKeyAuthenticationFilter() throws Exception {
ApiKeyAuthenticationFilter apiKeyAuthenticationFilter = new ApiKeyAuthenticationFilter();
apiKeyAuthenticationFilter.setAuthenticationManager(authenticationManagerBean());
apiKeyAuthenticationFilter.setAuthenticationSuccessHandler(new ApiKeyAuthenticationSuccessHandler());
apiKeyAuthenticationFilter.setAuthenticationFailureHandler(new ApiKeyAuthenticationFailureHandler());
return apiKeyAuthenticationFilter;
}
But theses beans were getting registered again in the configure(HttpSecurity http) method.
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher(CONFIGURATION_MATCHER)
.exceptionHandling().authenticationEntryPoint(restAuthenticationEntryPoint())
.and()
.addFilterBefore(apiKeyAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.csrf().disable()
.authorizeRequests().antMatchers(CONFIGURATION_MATCHER).authenticated()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authenticationProvider(apiKeyAuthenticationProvider());
}
The fix was to remove the #Bean annotation. Seems obvious now :)

Resources