Denis Deniben
Denis Deniben

Reputation: 93

405 - Request method 'POST' not supported Spring MVC + Spring Security

Sorry for duplicate i have seen so many questions for this topic but no one couldn't help me. When i put correct login data in login form all works. When i put incorrect login data in login form redirect to 'loginProcessingUrl()' is '/sign-in-handler' but i don't have in controller POST-endpoind for /sign-in-handler mapping because this endpoind must handle by spring security. But i have 405. Here is my code:

SecurityConfig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private DataSource dataSource;

    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl persistentTokenRepository = new JdbcTokenRepositoryImpl();
        persistentTokenRepository.setDataSource(dataSource);
        return persistentTokenRepository;
    }

    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(getPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/my-profile", "/edit", "/edit/**", "/remove").hasAnyAuthority(Constants.USER)
                .anyRequest().permitAll()
                .and()
                .formLogin()
                .loginPage("/sign-in")
                .loginProcessingUrl("/sign-in-handler")
                .usernameParameter("uid")
                .passwordParameter("password")
                .defaultSuccessUrl("/my-profile")
                .failureForwardUrl("/sign-in-failed")
                .and()
                .logout()
                .logoutUrl("/sign-out")
                .logoutSuccessUrl("/welcome")
                .invalidateHttpSession(true)
                .deleteCookies("JSESSIONID")
                .and()
                .rememberMe()
                .rememberMeParameter("remember-me")
                .key("resume-online-key")
                .tokenRepository(persistentTokenRepository());
    }
}

sign-in.jsp

        <form action='<spring:url value="/sign-in-handler"/>' method="post">
            <c:if test="${sessionScope.SPRING_SECURITY_LAST_EXCEPTION != null}">
                <div class="alert alert-danger" role="alert">
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                        ${sessionScope.SPRING_SECURITY_LAST_EXCEPTION.message }
                    <c:remove var="SPRING_SECURITY_LAST_EXCEPTION" scope="session" />
                </div>
            </c:if>
            <div class="help-block">Вы можете использовать Ваши UID или Email или Phone в качестве логина</div>
            <div class="form-group">
                <label for="uid">Логин</label> <input id="uid" name="uid" class="form-control" placeholder="UID или Email или Phone" required autofocus>
            </div>
            <div class="form-group">
                <label for="password">Пароль</label> <input id="password" type="password" name="password" class="form-control" placeholder="Password" required>
            </div>
            <div class="form-group">
                <label><input type="checkbox" name="remember-me" value="true"> Запомнить меня</label>
            </div>
                <button type="submit" class="btn btn-success">Войти</button>
   </form>

ViewLoginController.java

@Controller
public class ViewLoginController {

    @GetMapping("sign-in")
    public String signIn() {
        return "sign-in";
    }

    @GetMapping("/sign-in-failed")
    public String signInFailed(HttpSession httpSession){
        if(httpSession.getAttribute("SPRING_SECURITY_LAST_EXCEPTION") == null){
            return "redirect:/sign-in";
        }
        return "sign-in";
    }
}

But i have - https://prnt.sc/s79zwz I tried: change url on jsp spring:url, c:url, ${pageContext.request.contextPath}, just '/', daoAuthenticationProvider... Thanks for help

Upvotes: 1

Views: 448

Answers (1)

Lachezar Balev
Lachezar Balev

Reputation: 12021

I think that you may use failureUrl, instead of failureForwardUrl, for example:

and()
      .formLogin()
      .loginPage("/login")
      .loginProcessingUrl("/login/authenticate")
      .failureUrl("/login?param.error=bad_credentials")

The difference between the two is that failureForwardUrl may perform a server side forwarding (e.g. the POST that you observe to your endpoint) while failureUrl uses the default redirecting strategy of the platform and will cause a browser redirect (HTTP 302). The documentation is really vague and causes lots of confusion at least to me.

Upvotes: 2

Related Questions