List of usage examples for org.springframework.security.oauth2.provider OAuth2Authentication getAuthorities
public Collection<GrantedAuthority> getAuthorities()
From source file:com.ar.dev.tierra.api.config.security.CustomTokenEnhancer.java
@Override public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { User user = (User) authentication.getPrincipal(); final Map<String, Object> additionalInfo = new HashMap<>(); String hashedUsername = passwordEncoder.encode(user.getUsername()); additionalInfo.put("role", authentication.getAuthorities()); ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo); return accessToken; }
From source file:com.netflix.genie.web.security.oauth2.pingfederate.PingFederateRemoteTokenServices.java
/** * {@inheritDoc}/* w w w. j a va2 s . c om*/ */ @Override public OAuth2Authentication loadAuthentication(final String accessToken) throws AuthenticationException, InvalidTokenException { final long start = System.nanoTime(); try { final MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(); formData.add(TOKEN_NAME_KEY, accessToken); formData.add(CLIENT_ID_KEY, this.clientId); formData.add(CLIENT_SECRET_KEY, this.clientSecret); formData.add(GRANT_TYPE_KEY, GRANT_TYPE); final Map<String, Object> map = this.postForMap(this.checkTokenEndpointUrl, formData); if (map.containsKey(ERROR_KEY)) { final String error = map.get(ERROR_KEY).toString(); log.debug("Validating the token produced an error: {}", error); throw new InvalidTokenException(error); } Assert.state(map.containsKey(CLIENT_ID_KEY), "Client id must be present in response from auth server"); Assert.state(map.containsKey(SCOPE_KEY), "No scopes included in response from authentication server"); this.convertScopes(map); final OAuth2Authentication authentication = this.converter.extractAuthentication(map); log.info("User {} authenticated with authorities {}", authentication.getPrincipal(), authentication.getAuthorities()); return authentication; } finally { final long finished = System.nanoTime(); this.authenticationTimer.record(finished - start, TimeUnit.NANOSECONDS); } }
From source file:com.netflix.genie.web.security.oauth2.pingfederate.PingFederateJWTTokenServicesUnitTests.java
/** * Make sure we can successfully load an authentication. * * @throws AuthenticationException On error * @throws InvalidTokenException When the token is invalid * @throws InvalidJwtException On invalid JWT token * @throws MalformedClaimException A bad claim *///from www .j av a2s . c o m @Test public void canLoadAuthentication() throws AuthenticationException, InvalidTokenException, InvalidJwtException, MalformedClaimException { final JwtClaims claims = Mockito.mock(JwtClaims.class); final String clientId = UUID.randomUUID().toString(); final String scope1 = "genie_admin"; final String scope2 = UUID.randomUUID().toString(); final Set<String> scopes = Sets.newHashSet(scope1, scope2); Mockito.when(claims.getClaimValue("client_id", String.class)).thenReturn(clientId); Mockito.when(claims.getClaimValue("scope", Collection.class)).thenReturn(scopes); Mockito.when(this.jwtConsumer.processToClaims(Mockito.anyString())).thenReturn(claims); final OAuth2Authentication authentication = this.tokenServices .loadAuthentication(UUID.randomUUID().toString()); Assert.assertNull(authentication.getUserAuthentication()); Assert.assertThat(authentication.getPrincipal(), Matchers.is(clientId)); final Collection<GrantedAuthority> authorities = authentication.getAuthorities(); Assert.assertThat(authorities.size(), Matchers.is(3)); Assert.assertTrue(authorities.containsAll(Sets.newHashSet(new SimpleGrantedAuthority("ROLE_ADMIN"), new SimpleGrantedAuthority("ROLE_" + scope2.toUpperCase()), new SimpleGrantedAuthority("ROLE_USER")))); Mockito.verify(this.loadAuthenticationTimer, Mockito.times(1)).record(Mockito.anyLong(), Mockito.eq(TimeUnit.NANOSECONDS)); }
From source file:com.netflix.genie.web.security.oauth2.pingfederate.PingFederateRemoteTokenServicesUnitTests.java
/** * Make sure we can validate a token./* w w w .j av a 2 s . c om*/ */ @Test public void canLoadAuthentication() { final AccessTokenConverter converter = Mockito.mock(AccessTokenConverter.class); final RestTemplate restTemplate = Mockito.mock(RestTemplate.class); final PingFederateRemoteTokenServices services = new PingFederateRemoteTokenServices( this.resourceServerProperties, converter, this.registry); services.setRestTemplate(restTemplate); final String accessToken = UUID.randomUUID().toString(); final String clientId = UUID.randomUUID().toString(); final String scope1 = UUID.randomUUID().toString(); final String scope2 = UUID.randomUUID().toString(); final Map<String, Object> map = Maps.newHashMap(); map.put(PingFederateRemoteTokenServices.CLIENT_ID_KEY, clientId); map.put(PingFederateRemoteTokenServices.SCOPE_KEY, scope1 + " " + scope2); @SuppressWarnings("unchecked") final ResponseEntity<Map> response = Mockito.mock(ResponseEntity.class); Mockito.when(restTemplate.exchange(Mockito.eq(CHECK_TOKEN_ENDPOINT_URL), Mockito.eq(HttpMethod.POST), Mockito.any(HttpEntity.class), Mockito.eq(Map.class))).thenReturn(response); Mockito.when(response.getBody()).thenReturn(map); final SimpleGrantedAuthority scope1Authority = new SimpleGrantedAuthority(scope1); final SimpleGrantedAuthority scope2Authority = new SimpleGrantedAuthority(scope2); final Set<GrantedAuthority> authorities = Sets.newHashSet(scope1Authority, scope2Authority); final Authentication authentication = new UsernamePasswordAuthenticationToken(clientId, "NA", authorities); final OAuth2Authentication oauth2Authentication = new OAuth2Authentication( Mockito.mock(OAuth2Request.class), authentication); Mockito.when(converter.extractAuthentication(Mockito.eq(map))).thenReturn(oauth2Authentication); final OAuth2Authentication result = services.loadAuthentication(accessToken); Assert.assertThat(result, Matchers.is(oauth2Authentication)); Assert.assertThat(result.getPrincipal(), Matchers.is(clientId)); Assert.assertThat(result.getAuthorities().size(), Matchers.is(2)); Assert.assertTrue(result.getAuthorities().contains(scope1Authority)); Assert.assertTrue(result.getAuthorities().contains(scope2Authority)); Mockito.verify(this.authenticationTimer, Mockito.times(1)).record(Mockito.anyLong(), Mockito.eq(TimeUnit.NANOSECONDS)); }
From source file:org.energyos.espi.common.service.impl.SubscriptionServiceImpl.java
@Override
@Transactional(rollbackFor = { javax.xml.bind.JAXBException.class }, noRollbackFor = {
javax.persistence.NoResultException.class,
org.springframework.dao.EmptyResultDataAccessException.class })
public Subscription createSubscription(OAuth2Authentication authentication) {
Subscription subscription = new Subscription();
subscription.setUUID(UUID.randomUUID());
// Determine requestor's Role
Set<String> role = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
if (role.contains("ROLE_USER")) {
subscription.setApplicationInformation(
applicationInformationService.findByClientId(authentication.getOAuth2Request().getClientId()));
subscription.setRetailCustomer((RetailCustomer) authentication.getPrincipal());
subscription.setUsagePoints(new ArrayList<UsagePoint>());
// set up the subscription's usagePoints list. Keep in mind that right
// now this is ALL usage points belonging to the RetailCustomer.
// TODO - scope this to only a selected (proper) subset of the
// usagePoints as passed
// through from the UX or a restful call.
List<Long> upIds = resourceService.findAllIdsByXPath(subscription.getRetailCustomer().getId(),
UsagePoint.class);
Iterator<Long> it = upIds.iterator();
while (it.hasNext()) {
UsagePoint usagePoint = resourceService.findById(it.next(), UsagePoint.class);
subscription.getUsagePoints().add(usagePoint);
}/*from ww w.jav a 2 s . c om*/
} else {
String clientId = authentication.getOAuth2Request().getClientId();
String ci = clientId;
if (ci.indexOf("REGISTRATION_") != -1) {
if (ci.substring(0, "REGISTRATION_".length()).equals("REGISTRATION_")) {
ci = ci.substring("REGISTRATION_".length());
}
}
if (ci.indexOf("_admin") != -1) {
ci = ci.substring(0, ci.indexOf("_admin"));
}
subscription.setApplicationInformation(applicationInformationService.findByClientId(ci));
subscription.setRetailCustomer(retailCustomerService.findById((long) 0));
}
subscription.setLastUpdate(new GregorianCalendar());
subscriptionRepository.persist(subscription);
return subscription;
}
From source file:eu.trentorise.smartcampus.resourceprovider.filter.ResourceAuthenticationManager.java
/** * Check whether the access to the specific resource is granted. The The * resource is identified from the {@link ResourceCallAuthenticationToken} * fields {@link ResourceCallAuthenticationToken#getRequestPath()} and * {@link ResourceCallAuthenticationToken#getHttpMethod()}. * //from w w w .j a v a2s . com * @param authentication * the authentication token object as instance of * {@link ResourceCallAuthenticationToken}. */ @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { assert authentication instanceof ResourceCallAuthenticationToken; ResourceCallAuthenticationToken rcAuth = (ResourceCallAuthenticationToken) authentication; String token = (String) rcAuth.getPrincipal(); OAuth2Authentication auth = loadAuthentication(token); if (auth == null) { throw new InvalidTokenException("Invalid token: " + token); } String resourceUri; try { resourceUri = getUriManager().getUriFromRequest(rcAuth.getRequestPath(), rcAuth.getHttpMethod(), auth.getAuthorities()); } catch (IOException e) { throw new OAuth2Exception("Problem accessing resource descriptor"); } String resourceID = resourceUri;// resourceStore.loadResourceByResourceUri(resourceUri); // test senza lettura db Collection<String> resourceIds = auth.getAuthorizationRequest().getScope(); if (resourceID == null || resourceIds.isEmpty() || !resourceIds.contains(resourceID)) { throw new OAuth2AccessDeniedException( "Invalid token does not contain resource id (" + resourceUri + ")"); } String authority = authServices.loadResourceAuthorityByResourceUri(resourceUri); if (ROLE_USER.equals(authority) && auth.isClientOnly()) { throw new OAuth2AccessDeniedException("Incorrect access method"); } if (ROLE_CLIENT.equals(authority) && !auth.isClientOnly()) { throw new OAuth2AccessDeniedException("Incorrect access method"); } auth.setDetails(authentication.getDetails()); return auth; }
From source file:net.shibboleth.idp.oidc.client.userinfo.authn.ShibbolethAcrAwareTokenService.java
/** * Calculate amr and acr claims.// ww w.j ava 2 s.c o m * * @param accessToken the access token * @param idClaims the id claims */ private void calculateAmrAndAcrClaims(final OAuth2AccessTokenEntity accessToken, final JWTClaimsSet.Builder idClaims) { final OAuth2Authentication authN = accessToken.getAuthenticationHolder().getAuthentication(); final Collection<GrantedAuthority> authorities = authN.getAuthorities(); for (final GrantedAuthority authority : authorities) { log.debug("Evaluating authority {} of the authentication", authority); final AuthenticationClassRefAuthority acr = AuthenticationClassRefAuthority .getAuthenticationClassRefAuthority(authority); if (acr != null) { idClaims.claim(OIDCConstants.ACR, acr.getAuthority()); log.debug("Added {} claim as", OIDCConstants.ACR, acr.getAuthority()); } final AuthenticationMethodRefAuthority amr = AuthenticationMethodRefAuthority .getAuthenticationClassRefAuthority(authority); if (amr != null) { idClaims.claim(OIDCConstants.AMR, amr.getAuthority()); log.debug("Added {} claim as", OIDCConstants.AMR, amr.getAuthority()); } } }
From source file:com.ge.predix.uaa.token.lib.ZacTokenServiceTest.java
@SuppressWarnings("unchecked") private OAuth2Authentication loadAuthentication(final String zoneName, final String zoneUserScope, final String requestUri, final List<String> nonZoneUriPatterns) { ZacTokenService zacTokenServices = new ZacTokenService(); zacTokenServices.setServiceZoneHeaders(PREDIX_ZONE_HEADER_NAME); Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); authorities.add(new SimpleGrantedAuthority(zoneUserScope)); OAuth2Authentication oauth2Authentication = Mockito.mock(OAuth2Authentication.class); Mockito.when(oauth2Authentication.isAuthenticated()).thenReturn(true); FastTokenServices mockFTS = Mockito.mock(FastTokenServices.class); Mockito.doNothing().when(mockFTS).setUseHttps(true); Mockito.doNothing().when(mockFTS).setStoreClaims(true); Mockito.doNothing().when(mockFTS).setTrustedIssuers(Matchers.anyList()); Mockito.when(oauth2Authentication.getAuthorities()).thenReturn(authorities); Mockito.when(mockFTS.loadAuthentication(Matchers.anyString())).thenReturn(oauth2Authentication); FastTokenServicesCreator mockFTSC = Mockito.mock(FastTokenServicesCreator.class); when(mockFTSC.newInstance()).thenReturn(mockFTS); zacTokenServices.setFastRemoteTokenServicesCreator(mockFTSC); zacTokenServices.setServiceBaseDomain(BASE_DOMAIN); zacTokenServices.setServiceId(SERVICEID); DefaultZoneConfiguration zoneConfig = new DefaultZoneConfiguration(); List<String> trustedIssuers; // Non zone specific request, using default issuer if (StringUtils.isEmpty(zoneName)) { trustedIssuers = Arrays.asList(DEFAULT_TRUSTED_ISSUER); // Zone specific request, using the issuers returned by mockTrustedIssuersResponseEntity } else {// www . jav a 2s .c om trustedIssuers = ZONE_TRUSTED_ISSUERS; } zoneConfig.setTrustedIssuerIds(trustedIssuers); zacTokenServices.setDefaultZoneConfig(zoneConfig); zoneConfig.setAllowedUriPatterns(nonZoneUriPatterns); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); when(request.getServerName()).thenReturn("localhost"); when(request.getHeader(PREDIX_ZONE_HEADER_NAME)).thenReturn(zoneName); when(request.getRequestURI()).thenReturn(requestUri); zacTokenServices.setRequest(request); RestTemplate restTemplateMock = Mockito.mock(RestTemplate.class); zacTokenServices.setOauth2RestTemplate(restTemplateMock); try { zacTokenServices.afterPropertiesSet(); } catch (Exception e) { Assert.fail("Unexpected exception after properties set on zacTokenServices " + e.getMessage()); } when(restTemplateMock.getForEntity("null/v1/registration/" + SERVICEID + "/" + ZONE, TrustedIssuers.class)) .thenReturn(mockTrustedIssuersResponseEntity()); when(restTemplateMock.getForEntity("null/v1/registration/" + SERVICEID + "/" + INVALID_ZONE, TrustedIssuers.class)).thenThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND)); String accessToken = this.tokenUtil.mockAccessToken(600, zoneUserScope); OAuth2Authentication loadAuthentication = zacTokenServices.loadAuthentication(accessToken); // Making sure we are passing the right set of issuers to the FastTokenServices Mockito.verify(mockFTS).setTrustedIssuers(trustedIssuers); return loadAuthentication; }
From source file:org.energyos.espi.datacustodian.oauth.EspiTokenEnhancer.java
@Transactional(rollbackFor = { javax.xml.bind.JAXBException.class }, noRollbackFor = {
javax.persistence.NoResultException.class,
org.springframework.dao.EmptyResultDataAccessException.class })
@Override/* w ww . j a v a 2 s.c o m*/
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
DefaultOAuth2AccessToken result = new DefaultOAuth2AccessToken(accessToken);
System.out.printf("EspiTokenEnhancer: OAuth2Request Parameters = %s\n",
authentication.getOAuth2Request().getRequestParameters());
System.out.printf("EspiTokenEnhancer: Authorities = %s\n", authentication.getAuthorities());
String clientId = authentication.getOAuth2Request().getClientId();
ApplicationInformation ai = null;
// [mjb20150102] Allow REGISTRATION_xxxx and ADMIN_xxxx to use same
// ApplicationInformation record
String ci = clientId;
String clientCredentialsScope = accessToken.getScope().toString();
if (ci.indexOf("REGISTRATION_") != -1) {
if (ci.substring(0, "REGISTRATION_".length()).equals("REGISTRATION_")) {
ci = ci.substring("REGISTRATION_".length());
}
}
if (ci.indexOf("_admin") != -1) {
ci = ci.substring(0, ci.indexOf("_admin"));
}
// Confirm Application Information record exists for ClientID requesting
// an access token
try {
ai = applicationInformationService.findByClientId(ci);
} catch (NoResultException | EmptyResultDataAccessException e) {
System.out.printf(
"\nEspiTokenEnhancer: ApplicationInformation record not found!\n"
+ "OAuth2Request Parameters = %s\n",
authentication.getOAuth2Request().getRequestParameters() + " client_id = " + clientId);
throw new AccessDeniedException(String.format("No client with requested id: %s", clientId));
}
Map<String, String> requestParameters = authentication.getOAuth2Request().getRequestParameters();
String grantType = requestParameters.get(OAuth2Utils.GRANT_TYPE);
grantType = grantType.toLowerCase();
// Is this a "client_credentials" access token grant_type request?
if (grantType.contentEquals("client_credentials")) {
// Processing a "client_credentials" access token grant_type
// request.
// Reject a client_credentials request if Authority equals
// "ROLE_USER"
if (authentication.getAuthorities().toString().contains("[ROLE_USER]")) {
throw new InvalidGrantException(String.format("Client Credentials not valid for ROLE_USER\n"));
}
// Create Authorization and add authorizationURI to /oath/token
// response
Authorization authorization = authorizationService.createAuthorization(null, result.getValue());
result.getAdditionalInformation().put("authorizationURI",
ai.getDataCustodianResourceEndpoint()
+ Routes.DATA_CUSTODIAN_AUTHORIZATION.replace("espi/1_1/resource/", "")
.replace("{authorizationId}", authorization.getId().toString()));
// Create Subscription
Subscription subscription = subscriptionService.createSubscription(authentication);
// Initialize Authorization record
authorization.setThirdParty(authentication.getOAuth2Request().getClientId());
authorization.setAccessToken(accessToken.getValue());
authorization.setTokenType(accessToken.getTokenType());
authorization.setExpiresIn((long) accessToken.getExpiresIn());
authorization.setAuthorizedPeriod(new DateTimeInterval((long) 0, (long) 0));
authorization.setPublishedPeriod(new DateTimeInterval((long) 0, (long) 0));
if (accessToken.getRefreshToken() != null) {
authorization.setRefreshToken(accessToken.getRefreshToken().toString());
}
// Remove "[" and "]" surrounding Scope in accessToken structure
authorization.setScope(accessToken.getScope().toString().substring(1,
(accessToken.getScope().toString().length() - 1)));
// set the authorizationUri
authorization.setAuthorizationURI(ai.getDataCustodianResourceEndpoint()
+ Routes.DATA_CUSTODIAN_AUTHORIZATION.replace("espi/1_1/resource/", "")
.replace("{authorizationId}", authorization.getId().toString()));
// Determine resourceURI value based on Client's Role
Set<String> role = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
if (role.contains("ROLE_DC_ADMIN")) {
authorization.setResourceURI(ai.getDataCustodianResourceEndpoint() + "/");
} else {
if (role.contains("ROLE_TP_ADMIN")) {
authorization.setResourceURI(ai.getDataCustodianResourceEndpoint()
+ Routes.BATCH_BULK_MEMBER.replace("espi/1_1/resource/", "").replace("{bulkId}", "**"));
} else {
if (role.contains("ROLE_UL_ADMIN")) {
authorization
.setResourceURI(ai.getDataCustodianResourceEndpoint() + Routes.BATCH_UPLOAD_MY_DATA
.replace("espi/1_1/resource/", "").replace("{retailCustomerId}", "**"));
} else {
if (role.contains("ROLE_TP_REGISTRATION")) {
authorization.setResourceURI(ai.getDataCustodianResourceEndpoint()
+ Routes.ROOT_APPLICATION_INFORMATION_MEMBER.replace("espi/1_1/resource/", "")
.replace("{applicationInformationId}", ai.getId().toString()));
}
}
}
}
authorization.setApplicationInformation(applicationInformationService.findByClientId(ci));
authorization.setRetailCustomer(retailCustomerService.findById((long) 0));
authorization.setUpdated(new GregorianCalendar());
authorization.setStatus("1"); // Set authorization record status as
// "Active"
authorization.setSubscription(subscription);
authorizationService.merge(authorization);
// Add resourceURI to access_token response
result.getAdditionalInformation().put("resourceURI", authorization.getResourceURI());
// Initialize Subscription record
subscription.setAuthorization(authorization);
subscription.setUpdated(new GregorianCalendar());
subscriptionService.merge(subscription);
} else if (grantType.contentEquals("authorization_code")) {
try {
// Is this a refresh_token grant_type request?
Authorization authorization = authorizationService
.findByRefreshToken(result.getRefreshToken().getValue());
// Yes, update access token
authorization.setAccessToken(accessToken.getValue());
authorizationService.merge(authorization);
// Add ResourceURI and AuthorizationURI to access_token response
result.getAdditionalInformation().put("resourceURI", authorization.getResourceURI());
result.getAdditionalInformation().put("authorizationURI", authorization.getAuthorizationURI());
} catch (NoResultException | EmptyResultDataAccessException e) {
// No, process as initial access token request
// Create Subscription and add resourceURI to /oath/token
// response
Subscription subscription = subscriptionService.createSubscription(authentication);
result.getAdditionalInformation().put("resourceURI",
ai.getDataCustodianResourceEndpoint()
+ Routes.BATCH_SUBSCRIPTION.replace("espi/1_1/resource/", "")
.replace("{subscriptionId}", subscription.getId().toString()));
// Create Authorization and add authorizationURI to /oath/token
// response
Authorization authorization = authorizationService.createAuthorization(subscription,
result.getValue());
result.getAdditionalInformation().put("authorizationURI",
ai.getDataCustodianResourceEndpoint()
+ Routes.DATA_CUSTODIAN_AUTHORIZATION.replace("espi/1_1/resource/", "")
.replace("{authorizationId}", authorization.getId().toString()));
// Update Data Custodian subscription structure
subscription.setAuthorization(authorization);
subscription.setUpdated(new GregorianCalendar());
subscriptionService.merge(subscription);
RetailCustomer retailCustomer = (RetailCustomer) authentication.getPrincipal();
// link in the usage points associated with this subscription
List<Long> usagePointIds = resourceService.findAllIdsByXPath(retailCustomer.getId(),
UsagePoint.class);
Iterator<Long> it = usagePointIds.iterator();
while (it.hasNext()) {
UsagePoint up = resourceService.findById(it.next(), UsagePoint.class);
up.setSubscription(subscription);
resourceService.persist(up); // maybe not needed??
}
// Update Data Custodian authorization structure
authorization.setApplicationInformation(applicationInformationService
.findByClientId(authentication.getOAuth2Request().getClientId()));
authorization.setThirdParty(authentication.getOAuth2Request().getClientId());
authorization.setRetailCustomer(retailCustomer);
authorization.setAccessToken(accessToken.getValue());
authorization.setTokenType(accessToken.getTokenType());
authorization.setExpiresIn((long) accessToken.getExpiresIn());
if (accessToken.getRefreshToken() != null) {
authorization.setRefreshToken(accessToken.getRefreshToken().toString());
}
// Remove "[" and "]" surrounding Scope in accessToken structure
authorization.setScope(accessToken.getScope().toString().substring(1,
(accessToken.getScope().toString().length() - 1)));
authorization.setAuthorizationURI(ai.getDataCustodianResourceEndpoint()
+ Routes.DATA_CUSTODIAN_AUTHORIZATION.replace("espi/1_1/resource/", "")
.replace("{authorizationId}", authorization.getId().toString()));
authorization.setResourceURI(ai.getDataCustodianResourceEndpoint()
+ Routes.BATCH_SUBSCRIPTION.replace("espi/1_1/resource/", "").replace("{subscriptionId}",
subscription.getId().toString()));
authorization.setUpdated(new GregorianCalendar());
authorization.setStatus("1"); // Set authorization record status
// as "Active"
authorization.setSubscription(subscription);
authorization.setAuthorizedPeriod(new DateTimeInterval((long) 0, (long) 0));
authorization.setPublishedPeriod(new DateTimeInterval((long) 0, (long) 0));
authorizationService.merge(authorization);
}
} else {
System.out.printf(
"EspiTokenEnhancer: Invalid Grant_Type processed by Spring Security OAuth2 Framework:\n"
+ "OAuth2Request Parameters = %s\n",
authentication.getOAuth2Request().getRequestParameters());
throw new AccessDeniedException(String.format("Unsupported ESPI OAuth2 grant_type"));
}
return result;
}
From source file:org.cloudfoundry.identity.uaa.oauth.token.UaaTokenServicesTests.java
@Test public void testLoadAuthenticationForAUser() { DefaultAuthorizationRequest authorizationRequest = new DefaultAuthorizationRequest("client", Arrays.asList(new String[] { "read", "write" })); authorizationRequest.setResourceIds(new HashSet<String>(Arrays.asList(new String[] { "scim", "clients" }))); Map<String, String> azParameters = new HashMap<String, String>( authorizationRequest.getAuthorizationParameters()); azParameters.put("grant_type", "authorization_code"); authorizationRequest.setAuthorizationParameters(azParameters); Authentication userAuthentication = new UsernamePasswordAuthenticationToken( new UaaPrincipal(new UaaUser("jdsa", "password", "jdsa@vmware.com", null, null)), "n/a", null); OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest, userAuthentication); OAuth2AccessToken accessToken = testCreateAccessTokenForAUser(authentication, false); OAuth2Authentication loadedAuthentication = tokenServices.loadAuthentication(accessToken.getValue()); assertEquals(UaaAuthority.USER_AUTHORITIES, loadedAuthentication.getAuthorities()); assertEquals("jdsa", loadedAuthentication.getName()); UaaPrincipal uaaPrincipal = new UaaPrincipal(new UaaUser("12345", "jdsa", "password", "jdsa@vmware.com", UaaAuthority.USER_AUTHORITIES, null, null, null, null)); assertEquals(uaaPrincipal, loadedAuthentication.getPrincipal()); assertNull(loadedAuthentication.getDetails()); Authentication userAuth = loadedAuthentication.getUserAuthentication(); assertEquals("jdsa", userAuth.getName()); assertEquals(uaaPrincipal, userAuth.getPrincipal()); assertTrue(userAuth.isAuthenticated()); }