у меня проблема с csrf и SpringSecurity. Когда я посылаю форму я получаю статус 302
я сделал так
auth.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
другими словами
@Override
protected void configure(HttpSecurity auth) throws Exception {
auth.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
auth
.authorizeRequests()
.antMatchers("/static/**","/webjars/**","/registration").permitAll()
.antMatchers("/user").access("hasAuthority('USER')")
.antMatchers("/admin","/add").access("hasAuthority('ADMIN')")
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").permitAll()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.permitAll();
}
мапинг
@RequestMapping(value = "/registration",method = RequestMethod.POST)
public ResponseEntity<User> update(@RequestBody User user){
userMapper.findByName(user.getUsername());
if (userMapper.findByName(user.getUsername())!=null){
user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
userMapper.addUser(user);
return new ResponseEntity<User>(user, HttpStatus.OK);
}else
return new ResponseEntity<User>(user, HttpStatus.CONFLICT);
}
и форма
<form id="registration">
<input type="hidden" name="_csrf" value="{{_csrf.token}}" />
<input type="text" id="username" name="username" placeholder="password">
<input type="password" id="password" name="password" placeholder="password">
<button type="submit">submit</button>
как реализовать Security csrf и ajax (json). если есть туториал или пример, буду благодарен
Для ajax запросов можно убрать csrf на сервере.
auth.csrf().disabled().authorizeRequests()
.antMatchers("/static/**","/webjars/**","/registration").permitAll()
.antMatchers("/user").access("hasAuthority('USER')")
.antMatchers("/admin","/add").access("hasAuthority('ADMIN')")
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").permitAll()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.permitAll();
Нужно добавить мета теги
<html>
<head>
<meta name="_csrf" content="${_csrf.token}"/>
<!-- default header name is X-CSRF-TOKEN -->
<meta name="_csrf_header" content="${_csrf.headerName}"/>
<!-- ... -->
</head>
<!-- ... -->
и так же в сам файл javascripta
$(function () {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function(e, xhr, options) {
xhr.setRequestHeader(header, token);
});
});
и вставить токен в отправные данные. Есть еще пару способов, но помог мне этот.
Нашел ответ, по этой ссылке если кому либо понадобится
Основные этапы разработки сайта для стоматологической клиники
Продвижение своими сайтами как стратегия роста и независимости