I still new with Spring especially spring security. This application is Restful application.
Following is snippet from @RestController
:
@RequestMapping(value = "/new", method = RequestMethod.POST)
@PreRegistration("new")
@ResponseBody
public ResponseEntity<Void> newUser(@RequestBody @Valid TempUser user, UriComponentsBuilder ucBuilder) {
registerService.addUser(user);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/register/{userName}").buildAndExpand(user.getUserName()).toUri());
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}
Following is the snippet from CustomAuthenticationProvider
:
@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
final String name = authentication.getName();
final String password = authentication.getCredentials().toString();
if (name.equals("admin") && password.equals("system")) {
final List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
final UserDetails principal = new User(name, password, grantedAuths);
final Authentication auth = new UsernamePasswordAuthenticationToken(principal, password, grantedAuths);
return auth;
}
else {
throw new BadCredentialsException("NOT_AUTHORIZED");
}
}
SecurityConfig :
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.requestCache()
.requestCache(new NullRequestCache())
.and()
.httpBasic()
.and()
.csrf().disable();
}
What I try to achieve is when the CustomAuthenticationProvider
thrown an exception (e.g "bad credential" or "Full authentication required...", I want to customize the response and return to the Response Body in JSON format.
What I have done is to create a new exception and invoke it using AOP. But it seems like not working. I also tried to use @ControllerAdvice
, but it seems like not working as well since the CustomAuthenticationProvider
is outside the controller (I guess).