Java 403当我试图发布到我的spring api时被禁止?
通过使用postman,我可以获得一个用户列表,请求:Java 403当我试图发布到我的spring api时被禁止?,java,spring,spring-boot,spring-security,Java,Spring,Spring Boot,Spring Security,通过使用postman,我可以获得一个用户列表,请求:http://localhost:8080/users 但是当我向同一个地址发送post请求时,我得到一个403错误 @RestController public class UserResource { @Autowired private UserRepository userRepository; @GetMapping("/users") public List<User> retrie
http://localhost:8080/users
但是当我向同一个地址发送post请求时,我得到一个403错误
@RestController
public class UserResource {
@Autowired
private UserRepository userRepository;
@GetMapping("/users")
public List<User> retrievaAllUsers() {
return userRepository.findAll();
}
@PostMapping("/users")
public ResponseEntity<Object> createUser(@RequestBody User user) {
User savedUser = userRepository.save(user);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(savedUser.getId())
.toUri();
return ResponseEntity.created(location).build();
}
}
@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
/*@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}*/
/*@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().and().authorizeRequests()
.antMatchers("/users/**").hasRole("ADMIN")
.and().csrf().disable().headers().frameOptions().disable();
}*/
}
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue
private Long id;
private String name;
private String password;
@Enumerated(EnumType.STRING)
private Role role;
// TODO which cna be removed
public User() {
super();
}
public User(Long id, String name, String password, Role role) {
this.id = id;
this.name = name;
this.password = password;
this.role = role;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
}
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
INSERT INTO user VALUES (1, 'user1', 'pass1', 'ADMIN');
INSERT INTO user VALUES (2, 'user2', 'pass2', 'USER');
INSERT INTO user VALUES (3,'user3', 'pass3', 'ADMIN')
public void deleteUser(@PathVariable long id){
userRepository.deleteById(id);
}
编辑4
@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/users/**").permitAll();
}
}
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
403表示您没有授权。即使您注释掉了您的方法,您的代码仍将预先配置默认的安全访问权限 您可以添加:
http.authorizeRequests()
.antMatchers("/users/**").permitAll();
更新:禁用csrf的配置:
http.csrf()
.ignoringAntMatchers("/users/**")
.and()
.authorizeRequests()
.antMatchers("/users/**").permitAll();
@EnableWebSecurity
启用spring安全性,默认情况下它启用csrf
支持,您必须禁用它才能防止403错误
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
或随每个请求发送csrf
令牌
注意:禁用
csrf
会降低应用程序的安全性,最好的做法是发送csrf
令牌。请像这样配置您的http
@Override
protected void configure(HttpSecurity http) throws Exception {
http
//configureothers if u wants.
.csrf().disable();
}
请阅读更多信息当您将spring引导与spring security一起使用时,如果您从Postman或其他地方访问API(POST、PUT、DELETE),它们将无法访问,并且错误与授权相关,如禁止403 因此,在这种情况下,您必须禁用csrf功能才能从Postman运行和测试API @benjamin c提供的答案是正确的。您必须添加具有此配置的类才能工作 在生产环境中添加代码时,请确保正在删除此项。CSRF保护是必须的,您必须将其保持在安全功能中 我只是通过提供完整的课堂细节来扩展他的答案,了解更多细节。我的要求是只测试Postman的API,所以我添加了这个类,并且能够测试Postman的API 但是在那之后,我添加了SpringJUnit类来测试我的功能,并删除了这个类
@Configuration
@EnableWebSecurity
public class AppWebSecurityConfigurer extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.anyRequest().permitAll();
}
}
希望这对某人有所帮助。SecurityConfig类中的此配置帮助我解决了此问题:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
邮递员有时会做一些棘手的事情来让自己工作。您是否比较了每个请求中的标题以查看是否有任何差异?是否有任何stacktrace,如
访问被拒绝
或其他什么?@benjaminc我没有看到任何,并且我已禁用了身份验证,所以不知道为什么会有任何差异?@ab11由于使用了@EnableWebSecurity
,请尝试禁用csrf支持.csrf().disable()
@crowey你说得对,当我添加和().csrf().disable()时它起作用了代码>谢谢,我已经更新了我的SecruityConfig,但是在删除和创建时得到了相同的403。请使用我的新SecurityConfig查看我的最新编辑。它是否与应用程序类相关?我也包括了它的源代码,还添加了http.csrf().disable();另外,从你的截图中,你试图发布一个用户列表,在你的方法中,你只有一个用户。
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}