List of usage examples for org.springframework.security.oauth2.common DefaultOAuth2AccessToken getAdditionalInformation
public Map<String, Object> getAdditionalInformation()
From source file:com.create.security.oauth2.provider.token.AuthenticatedUserTokenEnhancer.java
@Override public OAuth2AccessToken enhance(final OAuth2AccessToken accessToken, final OAuth2Authentication authentication) { final DefaultOAuth2AccessToken enhancedAccessToken = new DefaultOAuth2AccessToken(accessToken); enhancedAccessToken.getAdditionalInformation().put(AUTHENTICATED_USER, authentication.getPrincipal()); return enhancedAccessToken; }
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())); }/*from w ww . j a v a2 s . co 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.companyname.controller.OAuth2AdminController.java
private Collection<OAuth2AccessToken> enhance(Collection<OAuth2AccessToken> tokens) { Collection<OAuth2AccessToken> result = new ArrayList<OAuth2AccessToken>(); for (OAuth2AccessToken prototype : tokens) { DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(prototype); OAuth2Authentication authentication = tokenStore.readAuthentication(token); if (authentication == null) { continue; }// w w w .j av a 2 s. c o m String clientId = authentication.getOAuth2Request().getClientId(); if (clientId != null) { Map<String, Object> map = new HashMap<String, Object>(token.getAdditionalInformation()); map.put("client_id", clientId); token.setAdditionalInformation(map); result.add(token); } } return result; }
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//from ww w. j a v a 2s . c om
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.orcid.core.oauth.service.OrcidTokenStoreServiceImpl.java
private OAuth2AccessToken getOauth2AccessTokenFromDetails(OrcidOauth2TokenDetail detail) { DefaultOAuth2AccessToken token = null; if (detail != null && StringUtils.isNotBlank(detail.getTokenValue())) { token = new DefaultOAuth2AccessToken(detail.getTokenValue()); token.setExpiration(detail.getTokenExpiration()); token.setScope(OAuth2Utils.parseParameterList(detail.getScope())); token.setTokenType(detail.getTokenType()); String refreshToken = detail.getRefreshTokenValue(); OAuth2RefreshToken rt;//from w w w . j a v a2 s.com if (StringUtils.isNotBlank(refreshToken)) { if (detail.getRefreshTokenExpiration() != null) { rt = new DefaultExpiringOAuth2RefreshToken(detail.getRefreshTokenValue(), detail.getRefreshTokenExpiration()); } else { rt = new DefaultOAuth2RefreshToken(detail.getRefreshTokenValue()); } token.setRefreshToken(rt); } ProfileEntity profile = detail.getProfile(); if (profile != null) { Map<String, Object> additionalInfo = new HashMap<String, Object>(); additionalInfo.put(OrcidOauth2Constants.ORCID, profile.getId()); additionalInfo.put(OrcidOauth2Constants.PERSISTENT, detail.isPersistent()); additionalInfo.put(OrcidOauth2Constants.DATE_CREATED, detail.getDateCreated()); additionalInfo.put(OrcidOauth2Constants.TOKEN_VERSION, detail.getVersion()); token.setAdditionalInformation(additionalInfo); } String clientId = detail.getClientDetailsId(); if (!PojoUtil.isEmpty(clientId)) { Map<String, Object> additionalInfo = new HashMap<String, Object>(); Map<String, Object> additionalInfoInToken = token.getAdditionalInformation(); if (additionalInfoInToken != null && !additionalInfoInToken.isEmpty()) { additionalInfo.putAll(additionalInfoInToken); } // Copy to a new one to avoid unmodifiable additionalInfo.put(OrcidOauth2Constants.CLIENT_ID, clientId); token.setAdditionalInformation(additionalInfo); } } return token; }