尝试发布到Spring API时禁止403吗?

时间:2018-09-21 18:44:28

标签: java spring spring-boot spring-security

使用邮递员,我可以通过以下请求获得用户列表: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')

编辑

enter image description here

enter image description here

EDit 2

添加了删除功能,但同时也提供了403吗?

@DeleteMapping("/users/{id}")

public void deleteUser(@PathVariable long id){     userRepository.deleteById(id); }

enter image description here

编辑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);
    }


}

5 个答案:

答案 0 :(得分:5)

@EnableWebSecurity启用spring安全性,并且默认情况下启用csrf支持,为了防止403错误,必须禁用它。

@Override
protected void configure(HttpSecurity http) throws Exception {
     http.csrf().disable();
}

或在每个请求中发送csrf令牌。

注意:禁用csrf会使应用程序的安全性降低,最好的做法是发送csrf令牌。

答案 1 :(得分:1)

403表示您没有授权。即使您注释掉了方法,您的代码仍将使用默认的安全访问权限进行预先配置。

您可以添加:

http.authorizeRequests()
   .antMatchers("/users/**").permitAll();

UPDATE:禁用csrf的配置:

http.csrf()
     .ignoringAntMatchers("/users/**")
     .and()
     .authorizeRequests()
        .antMatchers("/users/**").permitAll();

答案 2 :(得分:0)

请这样配置您的http;

JsonConvert.PopulateObject

请阅读更多CSRF

答案 3 :(得分:0)

当您将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();
        }
}

希望这对某人有帮助。

答案 4 :(得分:0)

SecurityConfig 类中的这个配置帮我解决了:

@Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
}
相关问题