Reputation: 2405
I'm configuring HttpSecurity for a Spring Boot rest server, and I need to make the create user end point not require authentication.
The mapping for the controller method is POST /users/{username}?action=create
I produced the following regex which I tested with online tools to make sure it matched correctly:
(\/users\/)([^\/]+)(\?action=create)
My only rule for usernames was that they cannot contain /, and so I believe that regex fufills that.
However, despite adding the following to the httpsecurity config:
.authorizeRequests()
.regexMatchers(HttpMethod.POST,"(\\/users\\/)([^\\/]+)(\\?action=create)")
.permitAll()
I am still unable to hit my endpoint and am unsure why.
Thanks!
UPDATE:
Apparently my custom filters would be applied unless I configured the WebSecurity object to ignore it completely, like so:
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/**", "/swagger-ui.html", "/webjars/**")
.and().ignoring().regexMatchers(HttpMethod.POST, "(\\/users\\/)([^\\/]+)(\\?action=create)");
}
But now spring is complaining about not being able to find an authentication object...
Upvotes: 0
Views: 4462
Reputation: 2405
My original solution was authorizing requests that had been authenticated, the following makes it so ALL requests (anonymous or not) are good to go!
Add this to your custom WebSecurityConfigurerAdapter
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/**", "/swagger-ui.html", "/webjars/**")
.and().ignoring().regexMatchers(HttpMethod.POST, "(\\/users\\/)([^\\/]+)(\\?action=create)");
}
And just for clarity, this is the controller method it is applied to:
@RequestMapping(value = "/users/{username}",params = {"action="+Action.CREATE}, method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public UserModel createUser(@PathVariable(value="username") String username, @RequestBody UserModel user) {
user.setUsername(username);
return userService.createUser(user);
}
Upvotes: 1