Spring Security - 405 Request Method 'POST' Not Supported

前端 未结 6 1422
执笔经年
执笔经年 2021-01-13 10:31

I have implemented Spring Security to my project, but I am getting status 405 when I try to log in. I have already added csrf token in the form.

6条回答
  •  伪装坚强ぢ
    2021-01-13 11:04

    First of all csrf is enabled by default in Spring as of Spring 4.0 so there no need to explicitly enable it yourself.

    Secondly, there is no endpoint for you to authenticate your login. What you're doing is sending a request to /login which only takes a GET request. You could create another controller method to receive that POST request and authenticate or you could use a UserDetailsService.

    SecurityConfiguration

    protected void configure(HttpSecurity http) throws Exception {
            http
                    .authorizeRequests()
                        .antMatchers("/login-form")
                            .anonymous()
                        .and()
                    .formLogin()
                        .loginPage("/user-login") 
                        .defaultSuccessUrl("/admin", true) // the second parameter is for enforcing this url always
                        .loginProcessingUrl("/login")
                        .failureUrl("/user-login")
                        .permitAll();
    }
    
    @Autowired 
    private UserDetailsService userDetailsService;  
    
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        BCryptPasswordEncoder pe = new  BCryptPasswordEncoder();
        auth.userDetailsService(userDetailsService).passwordEncoder(pe);
    }
    

    Here our view page is /user-login and the processing url is /login this means in your controller you need remove the mapping for /login and add the following:

    Controller

    @RequestMapping(value="/user-login", method=RequestMethod.GET)
    public ModelAndView loginForm() {
        return new ModelAndView("login-form");
    }
    

    And change your view.

    View (login-form.jsp)

    
    
    Username:
    Password:

提交回复
热议问题