ab1*_*b11 4 java spring spring-security spring-boot
使用邮递员,我可以得到用户的列表与GET请求: http://localhost:8080/users。
但是,当我向同一地址发送邮寄请求时,出现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')
Run Code Online (Sandbox Code Playgroud)
编辑
EDit 2
添加删除,但它也给出了403?
@DeleteMapping("/users/{id}")
Run Code Online (Sandbox Code Playgroud)
公共无效deleteUser(@PathVariable长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);
}
}
Run Code Online (Sandbox Code Playgroud)
ben*_*n c 11
@EnableWebSecurity启用spring安全性,并且默认情况下启用csrf支持,您必须禁用它以防止403错误。
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
Run Code Online (Sandbox Code Playgroud)
或csrf随每个请求发送令牌。
注意:禁用csrf会使应用程序不安全,最好的办法是发送csrf令牌。
小智 6
当您使用 spring boot 和 spring security 并且如果您从 Postman 或其他东西访问您的 API(POST、PUT、DELETE)时,它们将无法访问,并且错误与禁止 403 等授权有关。
因此,在这种情况下,您必须禁用 csrf 功能才能从 Postman 运行和测试 API。
@benjamin c 提供的答案是正确的。您必须添加具有此配置的类才能工作。
在生产中添加代码时,请确保将其删除。CSRF 保护是必须的,您必须将其保留在安全功能中。
我只是通过提供完整的课程详细信息来扩展他的答案以获取更多详细信息。我的需求是只测试来自 Postman 的 API,所以我添加了这个类,并且能够测试来自 Postman 的 API。
但在那之后,我添加了 Spring Junit 类来测试我的功能并删除了这个类。
@Configuration
@EnableWebSecurity
public class AppWebSecurityConfigurer extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.anyRequest().permitAll();
}
}
Run Code Online (Sandbox Code Playgroud)
希望这对某人有帮助。
| 归档时间: |
|
| 查看次数: |
3987 次 |
| 最近记录: |