@RestController
public class UserController {
@Autowired
UserService userService;
@PostMapping("/adduser")
public String addUser(@RequestBody Users user){
return userService.addUser(user);
}
@PutMapping("/updateuser/{id}")
public Users update(@PathVariable Long id,@RequestBody Users
user){
return userService.update(id,user);
}
//GET-USER
@GetMapping("/user/{id}")
public Users findUser(@PathVariable Long id){
return userService.findUserById(id);
}
@DeleteMapping("/deleteuser/{id}")
public String delete(@PathVariable Long id){
return userService.delete(id);
}
@GetMapping("/getuser")
public List<Users> findUser(){
List<Users> usersList = userService.findAll();
Collections.sort(usersList);
return usersList;
}
}
spring.datasource.url=jdbc:h2:mem:userandroles
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
我的帖子和获取映射工作得很好,但是当我添加安全性(基本身份验证)时,getMpping 工作但 postMaping 显示
enter code here
403 Forbidden
我的 get 和 post 映射在添加 spring-security 后工作正常
要解决此问题,您有几种选择: 1:在您的请求中包含 CSRF 令牌您可以在您的 POST、PUT 和 DELETE 请求中包含 CSRF 令牌作为请求参数或标头。以下是如何将其作为标题包含的示例:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/adduser").permitAll() // Allow unauthenticated access to POST /adduser
.anyRequest().authenticated()
.and()
.httpBasic();
}
}
2:禁用CSRF保护(不推荐) 如果您正在使用无状态 RESTful API,或者如果您有其他方法来防止 CSRF 攻击,您可以选择完全禁用 CSRF 保护。但是,除非您有替代的安全措施,否则不推荐使用这种方法。以下是如何禁用 CSRF 保护的示例:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/adduser").permitAll() // Allow unauthenticated access to POST /adduser
.anyRequest().authenticated()
.and()
.httpBasic();
}
}