Как исправить ошибку Forbidden 403, вызванную SpringSecurity? - PullRequest
0 голосов
/ 03 мая 2019

У меня запущено весеннее загрузочное приложение, и я не могу RequestParam из формы HTML. Всякий раз, когда я пытаюсь отправить параметр через форму, используя метод POST, выдается ошибка Forbidden 403. Даже когда я изменил настройки безопасности Spring на anyRequest.permit, все равно выдает 403. Есть идеи, как решить эту проблему?

mastermind_home.jsp:

<form action="/mastermind/home" method="POST">
            <label>
                <input type="radio" name="difficulty" value="easy">
            </label>Easy<br>
            <label>
                <input type="radio" name="difficulty" value="medium" checked>
            </label>Medium<br>
            <label>
                <input type="radio" name="difficulty" value="hard">
            </label>Hard<br>
            <input type="submit" value="Start game">
        </form>`

Контроллер:

@AllArgsConstructor
@Controller
@RequestMapping("mastermind")
public class MastermindController {

private MastermindServiceImpl mastermindService;
private UserService userService;

@GetMapping("/home")
public String prepareMmHomePage() {
    return "mastermind_home";
}
@PostMapping("/home")
public String formRequest( @RequestParam String difficulty) {
    return "mastermind_home";
}

Настройки безопасности Spring:

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

private DataSource dataSource;

public SecurityConfiguration(DataSource dataSource) {
    this.dataSource = dataSource;
}

@Bean
public PasswordEncoder passwordEncoder() {
    return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}

@Bean
public Authentication authentication() {
    return SecurityContextHolder.getContext().getAuthentication();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws   Exception {
    auth.jdbcAuthentication()
            .dataSource(dataSource)
            .passwordEncoder(passwordEncoder())
            .usersByUsernameQuery("SELECT user_name, password, true FROM users WHERE user_name = ?")
            .authoritiesByUsernameQuery("SELECT user_name, 'ROLE_USER' FROM users WHERE user_name = ?");
}

@Override
public void configure(WebSecurity web) throws Exception {
    super.configure(web);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/main_menu","/mastermind/**").authenticated()
            .antMatchers("/admin", "/admin/**").hasRole("ADMIN")
            .antMatchers("/home", "/register", "/registered_successfully").anonymous()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .defaultSuccessUrl("/main_menu")
            .and()
            .logout()
            .logoutSuccessUrl("/home");
}

}

Ответы [ 3 ]

0 голосов
/ 03 мая 2019

Добавьте это к безопасности весны, чтобы игнорировать шаблон URL

@Override
public void configure(WebSecurity webSecurity) throws Exception {
    webSecurity.ignoring()
            // All of Spring Security will ignore the requests.
            .antMatchers("/mastermind/home");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
 ..........
}
0 голосов
/ 04 мая 2019

Отключение csrf в весеннем конфиге безопасности исправило мою проблему.

and()
.csrf().disable();

Другое и лучшее решение моей проблемы:
В весенней безопасности я добавил:

.antMatchers(HttpMethod.POST, "/mastermind/home").authenticated()

и в форме jsp токен, проверяющий csrf:

<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
0 голосов
/ 03 мая 2019

В настройках безопасности Spring вы указываете, что все запросы к URL, начинающимся с /mastermind, должны проходить аутентификацию (.antMatchers("/main_menu","/mastermind/**").authenticated()).

Если вы хотите сделать исключение для POST /mastermind/home, вам нужно изменить конфигурацию, чтобы она выглядела примерно так:

http.authorizeRequests()
        .antMatchers(HttpMethod.POST, "/mastermind/home").permitAll()
        .antMatchers("/main_menu","/mastermind/**").authenticated()
        ....

Обратите внимание, что порядок этих двух строк важен, поскольку Spring соответствует URL-адресу запроса в той же последовательности.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...