1

This is a typical Spring controller method.

public ResponseEntity<RestApiResponse<OTPResponse>> sendOtp(HttpServletRequest request) {
        UserDetails userDetails = (UserDetails) request.getSession().getAttribute(SessionKey.USER_DETAILS);
        // Do some work
        //...
}

To get the username I have to copy the bellow line over and over again in every other controller method.

UserDetails userDetails = (UserDetails) request.getSession().getAttribute(SessionKey.USER_DETAILS);

Can I do this as follows ?

// @UserDetails is some kind of imaginary annotation 
public ResponseEntity<RestApiResponse<OTPResponse>> sendOtp(@UserDetails UserDetails userDetails) {
        userDetails.getUsername();
        // Do some work
        //....
}

Can I intercept the request, get the userDetails from request and inject that as controller method argument?

2 Answers 2

2

you can use below code as util method

public UserDetails getUser(){
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (!(auth instanceof AnonymousAuthenticationToken)) {
        return (UserDetails) auth.getPrincipal();
    }
    return null;
}

Another way of doing same.

@RequestMapping(method = RequestMethod.GET)   
 public ModelAndView anyMethodNameGoesHere(Principal principal) {
        final String loggedInUserName = principal.getName();

 }
Sign up to request clarification or add additional context in comments.

1 Comment

Nice one! The only drawback that this works only with Principal.
1

You can intercept requests and do it yourself, however spring-security already have such feature. It is called @AuthenticationPrincipal.

You can use it as follow:

@GetMapping
String hello(@AuthenticationPrincipal java.security.Principal principal) {
    return principal.getName();
}

If having a Principal isn't enough for your usecase, User also works:

@GetMapping
String hello(@AuthenticationPrincipal org.springframework.security.core.userdetails.User user) {
    return user.getUsername();
}

You can even inject your custom user details this way if you want.

Please have a look at documentation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.