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

spring security 403 forbidden post
403 forbidden postman spring boot
post 403 (forbidden)
spring security 403 on post
spring-boot-admin 403 forbidden
403 forbidden error in spring mvc
spring boot 403 handler
spring boot status'': 403 error'': forbidden'', message forbidden

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


}

@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.

How to Solve 403 Error in Spring Boot Post Request, can describe that reason in the response payload (if any). The question is, does the java backend enable spring-boot security? This means you need to get the data with a token in your request header generated by your backend or can be recognized by your backend. If not, try to call the backend interface with the Postman. if it works, that means the backend does not support CORS.

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.

Put/Post 403 Forbidden in ElasticSearch with PostMan, due to misconfigured permissions. The top reasons for this error are permissions or . htaccess error. The curl command works completely fine, however when I try POST method with the same credentials and same datas on my code, it returns 403. You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.

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

403 Forbidden or No Permission to Access, feature by configuring in application. properties. There are work around to configure in application. properties file. The 403 Forbidden Error happens when the web page (or other resource) that you’re trying to open in your web browser is a resource that you’re not allowed to access.  It’s called a 403 error because that’s the HTTP status code that the web server uses to describe that kind of error. You usually get this error for one of two reasons.

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();

How to enable and disable CSRF in Spring Boot Security – Yawin , The POST method works absolutely fine on curl command. I too got the same error 403 forbidden error when trying to access rest-api using POST/PUT method​  A 403 Forbidden message could mean that you need additional access before you can view the page. Typically, a website produces a 401 Unauthorized error when special permission is required, but sometimes a 403 Forbidden is used instead.

Solved: 403 Forbidden on POST method of /rest/api/2/issue , keycloak rest api 403 forbidden spring boot 2.1 403 forbidden on post json api 403 forbidden xmlhttprequest post 403 forbidden web api return 403 forbidden. I'm having some troubles using your API. I've signed up for an API key, tested an API call in my browser and got a successful response. Then I've implemented it into my project which is a PHP project. But when I try to get the response via PHP it fails. It always throws a 403 error, forbidden. So, is there a restriction I don't know of?

403 forbidden when I try to post to my spring api?, Hi, I have been trying to connect my Sapui5 front-end with the java back-end(​springboot The post request is giving me 403: Forbidden error. The issue The question is, does the java backend enable spring-boot security? The account has a Power BI Pro license and is a member of the workspace I am trying to read from. I have also made the account the owner of the app registration for my app. I can get a token, but when I call the API to get a data set id from the workspace, I get 403 (Forbidden). The same program works if I use my personal credentials.

403: Forbidden for the REST API POST request on Java backend on , A quick and focused tutorial on customizing the 403 Forbidden error response page in a The canonical reference for building a production grade API with Spring. This can be achieved either through the Spring Security Whenever a user attempts to access a page that is restricted to roles they do not  Solved: Hello, to list the content of a users My Reports folder, we are using the following API call on an external web app, but some users receive

Comments
  • Postman does some tricky stuff to make itself work sometimes. Have you compared the headers in each request to see if there are any differences?
  • is there any stacktrace like Access is denied or something ?
  • @benjaminc i don't see any, and I've disabled authrozation, so don't know why there would be any?
  • @ab11 since @EnableWebSecurity is used, try disabling csrf support .csrf().disable()
  • @drowny you're right, it worked when I added .and().csrf().disable();
  • thanks, I've updated my SecruityConfig, but get the same 403 on delete and create. please see my latest edit with my new SecurityConfig. Could it relate to the Application class? I included it's source as well
  • add also http.csrf().disable(); also from your screenshots you are trying to post a list of users and in your method you have only one user.