405 - Метод запроса 'POST' не поддерживается Spring MVC + Spring Security - PullRequest
1 голос
/ 28 апреля 2020

Извините за дубликат Я видел так много вопросов по этой теме c, но никто не мог мне помочь. Когда я введу правильные данные для входа в форму входа, все работает. Когда я помещаю неверные данные для входа в форму входа, перенаправление в 'loginProcessingUrl ()' равно '/ sign-in-handler', но у меня нет в контроллере POST-endpoind для отображения / sign-in-handler, потому что эта конечная точка должна обрабатываться весенняя охрана. Но у меня есть 405. Вот мой код:

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());
    }
}

вход. 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";
    }
}

Но у меня есть - https://prnt.sc/s79zwz Я пытался: изменить URL на jsp spring: url, c: url, $ {pageContext.request.contextPath}, просто '/', daoAuthenticationProvider ... Спасибо за помощь

1 Ответ

1 голос
/ 28 апреля 2020

Я думаю, что вы можете использовать failureUrl вместо failureForwardUrl, например:

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

Разница между ними заключается в том, что failureForwardUrl может выполнить переадресация на стороне сервера (например, POST, который вы наблюдаете на своей конечной точке), в то время как failureUrl использует стратегию перенаправления по умолчанию платформы и вызовет перенаправление браузера (HTTP 302). Документация действительно расплывчата и вызывает путаницу, по крайней мере, у меня.

...