Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring security login error "Request method 'POST' not supported"

I've looked at every related question I could find, but haven't been able to find an answer that works in my scenario. I'm using a Spring WebSecurityConfigurerAdapter, and I was able to authenticate a single user type, but after configuring my SecurityConfig class to handle multiple user types, I'm getting a "Request method 'POST' not supported" error even though I still the same URL for formLogin().loginPage(URL...).

I have 4 static classes of orders 1, 2, 3 and 4, although the first 2 are simply for permitting unauthenticated users to URLs with patterns / for home and /account/* for other things. All of these static classes are working appropriately, and when a URL is visited with patterns /company/* and /candidate/* the user is directed to the appropriate login pages to log in.

This is where the problem now occurs. I am using "/account/candidateLogin" and "/account/companyLogin" as the args in formLogin().loginPage(arg), but the same controller method I used before is no longer working properly. I am getting a 405 error and the console displays o.s.web.servlet.PageNotFound : Request method 'POST' not supported.

Here is the relevant code, and thank you in advance:

SecurityConfig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers( "/images/**",
            "/vendor/**",
            "/app.css",
            "/app.js",
            "/favicon.png");
    }

    @Configuration
    @Order(1)
    public static class HomePageSecurityConfigurationAdapter extends 
    WebSecurityConfigurerAdapter {
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
                .antMatcher("/")
                .authorizeRequests().anyRequest().permitAll();

       }
    }

    @Configuration
    @Order(2)
    public static class AccountSecurityConfigurationAdapter extends 
    WebSecurityConfigurerAdapter {
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
                .antMatcher("/account/*")
                .authorizeRequests().anyRequest().permitAll();

        }
    }


    @Configuration
    @Order(3)
    public static class CompanySecurityConfigurationAdapter extends 
    WebSecurityConfigurerAdapter {

        @Autowired
        private CompanyService companyService;

        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(companyService);
        }

        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
                .antMatcher("/company/*")
                .authorizeRequests()
                .anyRequest()
                .hasRole("COMPANY")
                .and()
                .formLogin()
                .loginPage("/account/companyLogin")
                .successHandler(companyLoginSuccessHandler())
                .failureHandler(companyLoginFailureHandler())
                .and()
                .logout()
                .logoutSuccessUrl("/");
        }

        public AuthenticationSuccessHandler companyLoginSuccessHandler() {
            return (request, response, authentication) -> response.sendRedirect("/company/companyProfile");
        }

        public AuthenticationFailureHandler companyLoginFailureHandler() {
            return (request, response, exception) -> {
                request.getSession().setAttribute("flash", new FlashMessage("Incorrect username and/or password. Please try again.", FlashMessage.Status.FAILURE));
                response.sendRedirect("/account/companyLogin");
            };
        }
    }

    @Configuration
    @Order(4)
    public static class CandidateSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {

        @Autowired
        private CandidateService candidateService;

        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(candidateService);
        }

        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
                .antMatcher("/candidate/*")
                .authorizeRequests()
                .anyRequest()
                .hasRole("CANDIDATE")
                .and()
                .formLogin()
                .loginPage("/account/candidateLogin")
                .successHandler(candidateLoginSuccessHandler())
                .failureHandler(candidateLoginFailureHandler())
                .and()
                .logout()
                .logoutSuccessUrl("/");
        }

        public AuthenticationSuccessHandler candidateLoginSuccessHandler() {
            return (request, response, authentication) -> response.sendRedirect("/candidate/candidateProfile");
        }

        public AuthenticationFailureHandler candidateLoginFailureHandler() {
            return (request, response, exception) -> {
                request.getSession().setAttribute("flash", new FlashMessage("Incorrect username and/or password. Please try again.", FlashMessage.Status.FAILURE));
                response.sendRedirect("/account/candidateLogin");
            };
        }
    }
}

Controller for login URIs. These are the same, just one for the candidate login and one for the company

@Controller()
public class AccountController {

    @Autowired
    private CandidateService candidateService;

    @Autowired
    private CompanyService companyService;

    @RequestMapping(value = "/account/candidateLogin", method = RequestMethod.GET)
    public String candidateLoginForm(Model model, HttpServletRequest request) {
        model.addAttribute("candidate", new Candidate());
        try {
            Object flash = request.getSession().getAttribute("flash");
            model.addAttribute("flash", flash);
            model.addAttribute("action", "/account/candidateLogin");
            model.addAttribute("submit","Login");

            request.getSession().removeAttribute("flash");
        } catch (Exception e) {
            //Flash session attribute must not exist. Do nothing and proceed.
        }
        return "account/candidateLogin";
    }

    @RequestMapping(value = "/account/companyLogin", method = RequestMethod.GET)
    public String loginCompanyForm(Model model, HttpServletRequest request) {
        model.addAttribute("company", new Company());
        try {
            Object flash = request.getSession().getAttribute("flash");
            model.addAttribute("flash", flash);
            model.addAttribute("action", "/account/companyLogin");
            model.addAttribute("submit","Login");

            request.getSession().removeAttribute("flash");
        }  catch (Exception e) {
            //Flash session attribute must not exist. Do nothing and proceed.
        }
        return "account/companyLogin";
    }

Login HTML file. I'm just including one since the only difference is variable names.

<!DOCTYPE html>
<html lang="en">
<head th:replace="layout :: head('explore')"></head>
<body>
<div th:replace="layout :: nav"></div>
<div th:replace="layout :: login"></div>


<h1 style="margin-left: 25%">Company Login</h1>
<div class="grayContainer">
    <div th:fragment="login">
        <div class="row">
            <div class="col s12">
                <div th:replace="layout :: flash"></div>
                <form th:action="@{${action}}" th:object="${company}" method="post">
                    <div class="input-field" style="width: 70%; margin: 0 auto;">
                        <input type="text" th:field="*{username}" placeholder="Username/Email"/>
                    </div>
                    <div class="input-field" style="width: 70%; margin: 0 auto;">
                        <input type="password" th:field="*{password}" placeholder="Password"/>
                    </div>
                    <button class="button" type="${submit}" style="text-align: center;">Login</button>Forgot password?
                </form>
            </div>
        </div>
    </div>
</div>

<div th:replace="layout :: scripts"></div>

</body>

EDIT

As a few people suggested, I changed the method in the request mapping for the login form to POST instead of GET and enabled security logging. Now I can't access the login page at all, it gives me a 405 error and this is the security debugger log:

************************************************************


2018-03-06 14:27:48.820  INFO 4495 --- [nio-8080-exec-4] Spring Security Debugger                 : 

************************************************************

Request received for GET '/account/candidateLogin':

org.apache.catalina.connector.RequestFacade@4cf3f981

servletPath:/account/candidateLogin
pathInfo:null
headers: 
host: localhost:8080
connection: keep-alive
upgrade-insecure-requests: 1
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
referer: http://localhost:8080/account/selectType
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
cookie: JSESSIONID=58FD34AB4F9796EC523C355C0A51ED49


Security filter chain: [
  WebAsyncManagerIntegrationFilter
  SecurityContextPersistenceFilter
  HeaderWriterFilter
  CsrfFilter
  LogoutFilter
  RequestCacheAwareFilter
  SecurityContextHolderAwareRequestFilter
  AnonymousAuthenticationFilter
  SessionManagementFilter
  ExceptionTranslationFilter
  FilterSecurityInterceptor
]


************************************************************


2018-03-06 14:27:48.829  WARN 4495 --- [nio-8080-exec-4] o.s.web.servlet.PageNotFound             : Request method 'GET' not supported
like image 740
CBruenger Avatar asked May 10 '26 02:05

CBruenger


1 Answers

for the request mapping

@RequestMapping(value = "/account/candidateLogin", method = RequestMethod.GET)

and

@RequestMapping(value = "/account/companyLogin", method = RequestMethod.GET)

They are mapped with GET method of the request while in ur form

<form th:action="@{${action}}" th:object="${company}" method="post">

its POST.

like image 152
Amit Kumar Lal Avatar answered May 12 '26 16:05

Amit Kumar Lal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!