Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Security Configuration for POST request

I have configured spring security in my Rest API.I have three controller methods. One uses GET and other two use POST. Now, I have used basic authentication. The problem is that the security is working fine for GET request but not for the POST requests.

I am always getting 403 Forbidden response for the requests when POST method is used.

Controller class:

package com.base.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import com.base.model.User;
import com.base.service.UserService;

@RestController

public class CountryController {




  @Autowired
  UserService userService;  //Service which will do all data retrieval/manipulation work


    //-------------------Retrieve All Users--------------------------------------------------------

    @RequestMapping(value = "/user/", method = RequestMethod.POST)
    public ResponseEntity<List<User>> listAllUsers() {
        List<User> users = userService.findAllUsers();
        if(users.isEmpty()){
            return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
        }
        return new ResponseEntity<List<User>>(users, HttpStatus.OK);
    }


    //-------------------Retrieve Single User--------------------------------------------------------

    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    public ResponseEntity<User> getUser(@PathVariable("id") long id) {
        System.out.println("Fetching User with id " + id);
        User user = userService.findById(id);
        if (user == null) {
            System.out.println("User with id " + id + " not found");
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<User>(user, HttpStatus.OK);
    }

    @RequestMapping(value = "/user123", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.ALREADY_REPORTED)
    public User postUser(@RequestBody @Valid User user) {
        System.out.println("Fetching User with id " + user.getId());
        user.setName("Tou added");
        return user;
    }
}

Security Config:

@Configuration
@EnableWebSecurity
@ComponentScan("com.base.security")
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
MyUSerService userService;

@Autowired
public void configureGlobalAuth(final AuthenticationManagerBuilder auth)throws Exception{
    auth.userDetailsService(userService);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    // TODO Auto-generated method stub
    http.authorizeRequests().anyRequest().authenticated().and().httpBasic().and()
    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}

MyUserService (to provide the usename and password)

 @Service
public class MyUSerService implements UserDetailsService{



    @Override
    public UserDetails loadUserByUsername(String arg0) throws UsernameNotFoundException {
        // TODO Auto-generated method stub
        List<SimpleGrantedAuthority> authoriities = new ArrayList<SimpleGrantedAuthority>();
        authoriities.add(new SimpleGrantedAuthority("WRITE"));
        return new User("ayush","ayush123",authoriities);
    }
    }

Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
    <display-name>Archetype Created Web Application</display-name>



    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>springrest</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
        <init-param>
            <param-name>contextClass</param-name>
            <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext
            </param-value>
        </init-param>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>com.base.config</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springrest</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>  

I am using 'Google Advanced Rest Client'.

like image 298
Ayush Avatar asked Apr 27 '26 12:04

Ayush


1 Answers

You need to disable CRSF. CRSF is enabled by default in spring security 4.

http.csrf().disable()

or send the request with CRSF token.

like image 180
chaoluo Avatar answered Apr 30 '26 03:04

chaoluo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!