List of usage examples for org.springframework.security.oauth2.common DefaultOAuth2AccessToken getRefreshToken
public OAuth2RefreshToken getRefreshToken()
From source file:org.osiam.auth.token.OsiamTokenEnhancer.java
@Override public OAuth2AccessToken enhance(final OAuth2AccessToken accessToken, final OAuth2Authentication authentication) { DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) accessToken; Map<String, Object> additionalInformation = new HashMap<>(); additionalInformation.put("expires_at", token.getExpiration()); if (token.getRefreshToken() != null) { DefaultExpiringOAuth2RefreshToken refreshToken = (DefaultExpiringOAuth2RefreshToken) token .getRefreshToken();//from w ww . j a va 2 s .c o m additionalInformation.put("refresh_token_expires_at", refreshToken.getExpiration()); } additionalInformation.put("client_id", authentication.getOAuth2Request().getClientId()); if (authentication.getUserAuthentication() != null && authentication.getPrincipal() instanceof User) { User user = (User) authentication.getPrincipal(); additionalInformation.put("user_name", user.getUserName()); additionalInformation.put("user_id", user.getId()); } token.setAdditionalInformation(additionalInformation); return accessToken; }
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(" "); }/*from ww w .j ava 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: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 w w w . java 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.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter.java
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { DefaultOAuth2AccessToken result = new DefaultOAuth2AccessToken(accessToken); Map<String, Object> info = new LinkedHashMap<String, Object>(accessToken.getAdditionalInformation()); String tokenId = result.getValue(); if (!info.containsKey(TOKEN_ID)) { info.put(TOKEN_ID, tokenId);// w ww . j a v a 2 s .co m } result.setAdditionalInformation(info); result.setValue(encode(result, authentication)); OAuth2RefreshToken refreshToken = result.getRefreshToken(); if (refreshToken != null) { DefaultOAuth2AccessToken encodedRefreshToken = new DefaultOAuth2AccessToken(accessToken); DefaultOAuth2RefreshToken token = new DefaultOAuth2RefreshToken( encode(encodedRefreshToken, authentication)); if (refreshToken instanceof ExpiringOAuth2RefreshToken) { Date expiration = ((ExpiringOAuth2RefreshToken) refreshToken).getExpiration(); encodedRefreshToken.setExpiration(expiration); token = new DefaultExpiringOAuth2RefreshToken(encode(encodedRefreshToken, authentication), expiration); } result.setRefreshToken(token); } return result; }