403 forbidden when I try to post to my spring api?

孤者浪人 提交于 2021-01-20 18:17:48

问题


Using postman, I can get a list of users with a get request to: http://localhost:8080/users.

But when I send a post request to the same address, I get a 403 error.

@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')

EDIT

EDit 2

added delete, but it also gives a 403?

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

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

edit 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);
    }


}

回答1:


@EnableWebSecurity enables spring security and it by default enables csrf support, you must disable it in order to prevent 403 errors.

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

Or send csrf token with each request.

Note: disabling csrf makes application less secure, best thing to do is send csrf token.




回答2:


When you use spring boot with spring security and if you are accessing your API's(POST, PUT, DELETE) from Postman or something, they wont be accessible and error is related to authorization like forbidden 403.

So in that case, you have to disabled to csrf functionality to run and test the API from Postman.

The answer provided by @benjamin c is right. You have to add the class with the this configuration will work.

Make sure you are removing this when you add your code in production. CSRF protection is must and you have to keep it in security functionality.

I am just extending his answer for more details by providing complete class details. My requirement was to just test the API from Postman, so I added this class, and able to test the API from Postman.

But after that I have added Spring Junit classes to test my functionalities and removed this class.

@Configuration
@EnableWebSecurity
public class AppWebSecurityConfigurer extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {    
        http
            .csrf().disable()
            .authorizeRequests()
                .anyRequest().permitAll();
        }
}

Hope this helps to someone.




回答3:


403 means you don't have authorization. Even though you commented out your method, your code will still be preconfigured with default security access.

You can add:

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

UPDATE : The configuration with csrf disabled:

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



回答4:


Please configure your http like this ;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        //configureothers if u wants.
        .csrf().disable();
}

Please read for more CSRF



来源:https://stackoverflow.com/questions/52449496/403-forbidden-when-i-try-to-post-to-my-spring-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!