AccessTokenUtils { public static Optional<String> getAccessTokenFromSecurityContext() { SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = securityContext.getAuthentication(); if (authentication instanceof OAuth2Authentication) { Object userDetails = ((OAuth2Authentication) authentication).getUserAuthentication().getDetails(); if (userDetails != null) { try { final Map details = (Map) userDetails; return Optional.fromNullable((String) details.get(ACCESS_TOKEN)); } catch (ClassCastException e) { return Optional.absent(); } } else { return Optional.absent(); } } return Optional.absent(); } private  AccessTokenUtils(); static Optional<String> getAccessTokenFromSecurityContext();  }
@Test public void testNonOAuth2Authentication() { SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("foo", "bar")); assertThat(getAccessTokenFromSecurityContext().isPresent()).isFalse(); }
@Test public void testMissingUserDetails() { SecurityContextHolder.getContext().setAuthentication(new OAuth2Authentication(mock(OAuth2Request.class), mock(Authentication.class))); assertThat(getAccessTokenFromSecurityContext().isPresent()).isFalse(); }
@Test public void testUserDetailsIsNotAMap() { final Authentication userAuthentication = mock(Authentication.class); when(userAuthentication.getDetails()).thenReturn("123456789"); SecurityContextHolder.getContext().setAuthentication(new OAuth2Authentication(mock(OAuth2Request.class), userAuthentication)); assertThat(getAccessTokenFromSecurityContext().isPresent()).isFalse(); }
@Test public void testGetToken() { final Authentication userAuthentication = mock(Authentication.class); when(userAuthentication.getDetails()).thenReturn(singletonMap(ACCESS_TOKEN, "1234567890")); SecurityContextHolder.getContext().setAuthentication(new OAuth2Authentication(mock(OAuth2Request.class), userAuthentication)); assertThat(getAccessTokenFromSecurityContext().get()).contains("1234567890"); }