UserTokenGranter extends AbstractTokenGranter { protected Authentication validateRequest(TokenRequest request) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null || !authentication.isAuthenticated() || !(authentication instanceof UaaOauth2Authentication)) { throw new InsufficientAuthenticationException("Invalid authentication object:"+authentication); } UaaOauth2Authentication oauth2Authentication = (UaaOauth2Authentication)authentication; if (oauth2Authentication.getUserAuthentication() == null || !oauth2Authentication.getUserAuthentication().isAuthenticated()) { throw new InsufficientAuthenticationException("Authentication containing a user is required"); } if (request.getRequestParameters()==null || request.getRequestParameters().get(USER_TOKEN_REQUESTING_CLIENT_ID)==null) { throw new InvalidGrantException("Parameter "+USER_TOKEN_REQUESTING_CLIENT_ID+" is required."); } if (!TokenConstants.GRANT_TYPE_USER_TOKEN.equals(request.getGrantType())) { throw new InvalidGrantException("Invalid grant type"); } ClientDetails requesting = clientDetailsService.loadClientByClientId(request.getRequestParameters().get(USER_TOKEN_REQUESTING_CLIENT_ID), IdentityZoneHolder.get().getId()); super.validateGrantType(GRANT_TYPE_USER_TOKEN, requesting); ClientDetails receiving = clientDetailsService.loadClientByClientId(request.getRequestParameters().get(CLIENT_ID), IdentityZoneHolder.get().getId()); super.validateGrantType(GRANT_TYPE_REFRESH_TOKEN, receiving); return oauth2Authentication.getUserAuthentication(); } UserTokenGranter(AuthorizationServerTokenServices tokenServices,
                            MultitenantClientServices clientDetailsService,
                            OAuth2RequestFactory requestFactory,
                            RevocableTokenProvisioning tokenStore); @Override OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest);  }
@Test(expected = InsufficientAuthenticationException.class) public void test_no_authentication() { SecurityContextHolder.clearContext(); granter.validateRequest(tokenRequest); }
@Test(expected = InsufficientAuthenticationException.class) public void test_not_authenticated() { when(authentication.isAuthenticated()).thenReturn(false); granter.validateRequest(tokenRequest); }
@Test(expected = InsufficientAuthenticationException.class) public void test_not_a_user_authentication() { when(authentication.isAuthenticated()).thenReturn(true); when(authentication.getUserAuthentication()).thenReturn(null); granter.validateRequest(tokenRequest); }