Kar Kar - 1 year ago 94
reST (reStructuredText) Question

How to get a handle to the User/Principal/Authentication in Spring REST Controller without passing them to the API method call?

I am using Spring 4.2.6.RELEASE and Spring Security 4.x. I would like to know whether it is possible to get a handle to the User(Principal) object inside the Spring REST Controller without having to pass the WebRequest or any other Spring object into the method of the REST API call, for example as in getBanks(WebRequest pWebRequest)

I am currently getting my user details in Spring by using the WebRequest passed into the method. This is affecting my REST document definitions especially while generating my YAML file using SWAGGER.

Would it be possible to inject or get a handle to the Principal or User without having to pass it to the REST API method call and still retain security of my APIs.

@RequestMapping(value = "/banks", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class BankResource extends Resource {

@RequestMapping(value = "/banks", method = RequestMethod.GET)
public ResponseEntity<List<Banks>> getBanks(WebRequest pWebRequest) {

Authentication authentication = (Authentication) pWebRequest.getUserPrincipal();
Object principal = pAuthentication != null ? pAuthentication.getPrincipal() : null;
User user = (User) principal;
BankCriteria criteria = new BankCriteria();
List<Bank> banks = _bankService.getBanks(user, criteria);
return ResponseEntity.ok(banks);

Answer Source

You can include an Authentication as a parameter:

public ResponseEntity<List<Banks>> getBanks(Authentication auth) {

Or you can get it by a static method call within the controller method:

Authentication auth = SecurityContextHolder.getContext().getAuthentication();