Search code examples
javaspringspring-mvcspring-securityspring-annotations

How to unsecure a method with Spring security


I have implemented Spring Security for a RESTful web service project. It has Request Mappings with same url patterns but with different Request Method types.

@RequestMapping(value = "/charity/accounts", method = RequestMethod.POST)
public AccountResponseDto createAccount(HttpServletResponse response, @RequestBody AccountRequestDto requestDTO) {
    // some logics here
}

@RequestMapping(value = "/charity/accounts", method = RequestMethod.GET)
public AccountResponseDto getAccount(HttpServletResponse response) {
    // some logics here
}

@RequestMapping(value = "/charity/accounts", method = RequestMethod.PUT)
public void updateAccount(HttpServletResponse response, @RequestBody AccountRequestDto requestDTO){
    // some logics here
}

Currently all of these methods require Authorization to execute, but I need to remove authorization for createAccount(...) method. Are there annotation based solutions?

Note: I need a solution that will not effect to do changes for url patterns, as it will impact in many other modules.


Solution

  • Below is a sample configuration which would permit requests for signup and about:

    @EnableWebSecurity
    @Configuration
    public class CustomWebSecurityConfigurerAdapter extends
       WebSecurityConfigurerAdapter {
      @Autowired
      public void configureGlobal(AuthenticationManagerBuilder auth) {
        auth
          .inMemoryAuthentication()
            .withUser("user")  // #1
              .password("password")
              .roles("USER")
              .and()
            .withUser("admin") // #2
              .password("password")
              .roles("ADMIN","USER");
      }
    
      @Override
      protected void configure(HttpSecurity http) throws Exception {
        http
          .authorizeUrls()
            .antMatchers("/signup","/about").permitAll();
      }
    }
    

    You can refer Spring Security Java Config for detailed information.

    A suggestion on your Controller. If all requests prefixed with /charity to be handled by CharityController, you can map requests in the below way:

    @Controller
    @RequestMapping(value="/charity")
    class CharityController {
                @RequestMapping(value = "/accounts", method = RequestMethod.GET)
                public AccountResponseDto getAccount(HttpServletResponse response){
    
                }
    }
    

    Update

    The following should work for you.

    protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                .antMatchers(HttpMethod.POST, new String [] {"/charity/accounts", "/charity/people"}).permitAll();
    }