Search code examples
spring-bootspring-mvcspring-security-oauth2

Accessing Oauth client and Principal inside the service class method


I am implementing a resource server using spring-boot-starter-oauth2-resource-server dependency. I was referring to the below code where inside the Controller method, we have injected the dependency and Spring will automatically inject the auth-client and the principal using reflection.

What if, I want to access these objects inside the method defined inside the service class? I do not want to pass these values as arguments when calling the method inside the service class. Please let me know, how to access these objects inside the service class.

@RequestMapping("/oauthinfo")  
    @ResponseBody  
    public String oauthUserInfo(@RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient,  
                              @AuthenticationPrincipal OAuth2User oauth2User) {  
        return  
            "User Name: " + oauth2User.getName() + "<br/>" +  
            "User Authorities: " + oauth2User.getAuthorities() + "<br/>" +  
            "Client Name: " + authorizedClient.getClientRegistration().getClientName() + "<br/>" +  
            this.prettyPrintAttributes(oauth2User.getAttributes());  
    }  

Solution

  • You could have the OAuth2AuthorizedClient injected (aka autowired) in the service class on construction.

    You can access the security principal inside a service class as follows:

     SecurityContextHolder.getContext().getAuthentication()