List of usage examples for org.springframework.security.oauth2.common DefaultOAuth2AccessToken getValue
public String getValue()
From source file:org.osiam.auth.token.OsiamCompositeTokenGranter.java
public OAuth2AccessToken grant(String grantType, AuthorizationRequest authorizationRequest) { OAuth2AccessToken grant = super.grant(grantType, authorizationRequest); if (grant != null) { DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) grant; Map<String, Object> additionalInformation = new HashMap<String, Object>(); additionalInformation.put("access_token", token.getValue()); additionalInformation.put("expires_at", token.getExpiration()); StringBuilder scopes = new StringBuilder(); for (String scopeString : token.getScope()) { scopes.append(scopeString).append(" "); }// w w w. j a v a 2 s .c o m additionalInformation.put("scopes", scopes); if (token.getRefreshToken() != null) { DefaultExpiringOAuth2RefreshToken refreshToken = (DefaultExpiringOAuth2RefreshToken) token .getRefreshToken(); additionalInformation.put("refresh_token", refreshToken.getValue()); additionalInformation.put("refresh_token_expires_at", refreshToken.getExpiration()); } additionalInformation.put("token_type", token.getTokenType()); additionalInformation.put("client_id", authorizationRequest.getClientId()); OAuth2Authentication auth = tokenServices.loadAuthentication(token.getValue()); if (auth.getUserAuthentication() != null && auth.getPrincipal() instanceof User) { User user = (User) auth.getPrincipal(); additionalInformation.put("user_name", user.getUserName()); additionalInformation.put("user_id", user.getId()); } token.setAdditionalInformation(additionalInformation); } return grant; }
From source file:com.ge.predix.uaa.token.lib.TestTokenUtil.java
public String mockAccessToken(final String issuerId, final long issuedAtMillis, final int validitySeconds) { Collection<GrantedAuthority> clientScopes = Arrays .asList(new GrantedAuthority[] { new SimpleGrantedAuthority("uaa.resource") }); Set<String> requestedScopes = new HashSet<>(Arrays.asList(new String[] { "openid" })); Set<String> resourceIds = new HashSet<>(Arrays.asList(new String[] { "none" })); DefaultOAuth2AccessToken openIdToken = createAccessToken(issuerId, "1adc931e-d65f-4357-b90d-dd4131b8749a", "marissa", "marissa@test.com", validitySeconds, clientScopes, requestedScopes, "cf", resourceIds, "passsword", null, null, null, null, issuedAtMillis, "uaa"); return openIdToken.getValue(); }
From source file:com.ge.predix.uaa.token.lib.TestTokenUtil.java
public String mockAccessToken(final int validitySeconds, final String zoneUserScope) { Collection<GrantedAuthority> clientScopes = Arrays.asList(new GrantedAuthority[] { new SimpleGrantedAuthority("uaa.resource"), new SimpleGrantedAuthority(zoneUserScope) }); Set<String> requestedScopes = new HashSet<>(Arrays.asList(new String[] { "openid", zoneUserScope })); Set<String> resourceIds = new HashSet<>(Arrays.asList(new String[] { "none" })); DefaultOAuth2AccessToken openIdToken = createAccessToken(TOKEN_ISSUER_ID, "1adc931e-d65f-4357-b90d-dd4131b8749a", "marissa", "marissa@test.com", validitySeconds, clientScopes, requestedScopes, "cf", resourceIds, "passsword", null, null, null, null, System.currentTimeMillis(), "uaa"); return openIdToken.getValue(); }
From source file:org.cloudfoundry.identity.uaa.oauth.TokenAdminEndpoints.java
private Collection<OAuth2AccessToken> enhance(Collection<OAuth2AccessToken> tokens) { Collection<OAuth2AccessToken> result = new ArrayList<OAuth2AccessToken>(); for (OAuth2AccessToken prototype : tokens) { DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(prototype); Map<String, Object> map = new HashMap<String, Object>(token.getAdditionalInformation()); if (!map.containsKey(JwtTokenEnhancer.TOKEN_ID)) { // The token doesn't have an ID in the token service, but we need one for the endpoint, so add one here map.put(JwtTokenEnhancer.TOKEN_ID, encoder.encode(token.getValue())); }// w ww .j av a 2 s .c o m try { String clientId = tokenServices.getClientId(token.getValue()); if (clientId != null) { map.put("client_id", clientId); } } catch (InvalidTokenException e) { // Ignore defensively in case of bugs in token services } token.setAdditionalInformation(map); result.add(token); } return result; }
From source file:com.ge.predix.uaa.token.lib.TestTokenUtil.java
private DefaultOAuth2AccessToken createAccessToken(final String issuerId, final String userId, final String username, final String userEmail, final int validitySeconds, final Collection<GrantedAuthority> clientScopes, final Set<String> requestedScopes, final String clientId, final Set<String> resourceIds, final String grantType, final String refreshToken, final Map<String, String> additionalAuthorizationAttributes, final Set<String> responseTypes, final String revocableHashSignature, final long issuedAtMillis, final String zoneId) { String tokenId = UUID.randomUUID().toString(); DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken(tokenId); if (validitySeconds > 0) { accessToken.setExpiration(new Date(issuedAtMillis + (validitySeconds * 1000L))); }//from w w w.j av a 2 s .com accessToken.setRefreshToken(refreshToken == null ? null : new DefaultOAuth2RefreshToken(refreshToken)); if (null == requestedScopes || requestedScopes.size() == 0) { // logger.debug("No scopes were granted"); throw new InvalidTokenException("No scopes were granted"); } accessToken.setScope(requestedScopes); Map<String, Object> info = new HashMap<String, Object>(); info.put(JTI, accessToken.getValue()); if (null != additionalAuthorizationAttributes) { info.put(ADDITIONAL_AZ_ATTR, additionalAuthorizationAttributes); } accessToken.setAdditionalInformation(info); String content; try { content = JsonUtils.writeValueAsString(createJWTAccessToken(accessToken, issuerId, userId, username, userEmail, clientScopes, requestedScopes, clientId, resourceIds, grantType, refreshToken, revocableHashSignature, issuedAtMillis, zoneId)); } catch (JsonUtils.JsonUtilException e) { throw new IllegalStateException("Cannot convert access token to JSON", e); } String token = JwtHelper.encode(content, this.signer).getEncoded(); // This setter copies the value and returns. Don't change. accessToken.setValue(token); return accessToken; }
From source file:it.smartcommunitylab.aac.oauth.NonRemovingTokenServices.java
private OAuth2AccessToken createAccessToken(OAuth2Authentication authentication, OAuth2RefreshToken refreshToken) { DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(UUID.randomUUID().toString()); int validitySeconds = getAccessTokenValiditySeconds(authentication.getOAuth2Request()); if (!authentication.isClientOnly()) { token.setExpiration(new Date(System.currentTimeMillis() + (getUserAccessTokenValiditySeconds(authentication.getOAuth2Request()) * 1000L))); } else if (validitySeconds > 0) { token.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * 1000L))); } else {/* w w w .j a v a2 s . com*/ token.setExpiration(new Date(Long.MAX_VALUE)); } token.setRefreshToken(refreshToken); token.setScope(authentication.getOAuth2Request().getScope()); logger.info("Created token " + token.getValue() + " expires at " + token.getExpiration()); return tokenEnhancer != null ? tokenEnhancer.enhance(token, authentication) : token; }
From source file:com.cedac.security.oauth2.provider.token.store.TokenStoreBaseTests.java
@Test public void testRetrieveAccessToken() { //Test approved request OAuth2Request storedOAuth2Request = RequestTokenFactory.createOAuth2Request("id", true); OAuth2Authentication authentication = new OAuth2Authentication(storedOAuth2Request, new TestAuthentication("test2", true)); DefaultOAuth2AccessToken expectedOAuth2AccessToken = new DefaultOAuth2AccessToken("testToken"); expectedOAuth2AccessToken.setExpiration(new Date(Long.MAX_VALUE - 1)); getTokenStore().storeAccessToken(expectedOAuth2AccessToken, authentication); //Test unapproved request storedOAuth2Request = RequestTokenFactory.createOAuth2Request("id", false); authentication = new OAuth2Authentication(storedOAuth2Request, new TestAuthentication("test2", true)); OAuth2AccessToken actualOAuth2AccessToken = getTokenStore().getAccessToken(authentication); assertEquals(expectedOAuth2AccessToken, actualOAuth2AccessToken); assertEquals(authentication.getUserAuthentication(), getTokenStore().readAuthentication(expectedOAuth2AccessToken.getValue()).getUserAuthentication()); // The authorizationRequest does not match because it is unapproved, but the token was granted to an approved request assertFalse(storedOAuth2Request.equals( getTokenStore().readAuthentication(expectedOAuth2AccessToken.getValue()).getOAuth2Request())); actualOAuth2AccessToken = getTokenStore().getAccessToken(authentication); assertEquals(expectedOAuth2AccessToken, actualOAuth2AccessToken); getTokenStore().removeAccessToken(expectedOAuth2AccessToken); assertNull(getTokenStore().readAccessToken("testToken")); assertNull(getTokenStore().readAuthentication(expectedOAuth2AccessToken.getValue())); assertNull(getTokenStore().getAccessToken(authentication)); }
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 av a 2 s.co 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;
}