0

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.

@RestController
@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);
}
serah
  • 2,057
  • 7
  • 36
  • 56
  • 1
    Possible duplicate of [How to find out the currently logged-in user in Spring Boot?](http://stackoverflow.com/questions/31159075/how-to-find-out-the-currently-logged-in-user-in-spring-boot) – Roman Vottner Sep 01 '16 at 17:14

1 Answers1

0

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();
David Miller
  • 507
  • 3
  • 5