List of usage examples for org.springframework.security.oauth2.common OAuth2AccessToken getAdditionalInformation
Map<String, Object> getAdditionalInformation();
From source file:am.ik.categolj2.app.authentication.AuthenticationHelper.java
@SuppressWarnings("unchecked") void writeLoginHistory(OAuth2AccessToken accessToken, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException { // user//from w ww.jav a 2 s . co m Map<String, ?> user = (Map<String, ?>) accessToken.getAdditionalInformation().get("user"); if (user != null) { String username = (String) user.get("username"); String firstName = (String) user.get("firstName"); String lastName = (String) user.get("lastName"); String email = (String) user.get("email"); LoginHistory loginHistory = createHistory(username, request); loginHistoryService.save(loginHistory); saveUserInformationInCookie(username, firstName, lastName, email, accessToken, response); } else { logger.error("No user information! (access_token={})", accessToken); } }
From source file:org.apigw.authserver.web.controller.CertifiedClientsController.java
@RequestMapping(value = "/oauth/revoke", method = RequestMethod.POST) public String revokeAuthorization(@RequestParam("grantId") long grantId) { log.debug("revokeAuthorization"); UserDetails user = getUserDetailsFromSecurityContext(); Collection<OAuth2AccessToken> tokens = getAccessTokens(user.getUsername()); String tokenValue = null;/*from w w w. jav a2 s .c o m*/ for (OAuth2AccessToken t : tokens) { Map<String, Object> additionalInformation = t.getAdditionalInformation(); long id = (Long) additionalInformation.get("authorization_grant_id"); if (grantId == id) { tokenValue = t.getValue(); break; } } if (tokenValue == null) { throw new RuntimeException("No token found for grantId=" + grantId); //TODO: throw something better? } try { consumerTokenServices.revokeToken(tokenValue); } catch (RuntimeException e) { log.error("Caught exception while trying to revoke token", e); throw (e); } log.debug("returning from revokeAuthorization"); return "redirect:/oauth/clients"; }
From source file:sample.jsp.WelcomeController.java
@RequestMapping("/authorization_code") public String authCode(Map<String, Object> model) throws Exception { if (ssoServiceUrl.equals("placeholder")) { model.put("header", "Warning: You need to bind to the SSO service."); model.put("warning", "Please bind your app to restore regular functionality"); return "configure_warning"; }//w w w. ja v a 2s. c o m Map<?, ?> userInfoResponse = oauth2RestTemplate.getForObject("{ssoServiceUrl}/userinfo", Map.class, ssoServiceUrl); model.put("ssoServiceUrl", ssoServiceUrl); model.put("response", toPrettyJsonString(userInfoResponse)); OAuth2AccessToken accessToken = oauth2RestTemplate.getOAuth2ClientContext().getAccessToken(); if (accessToken != null) { model.put("access_token", toPrettyJsonString(parseToken(accessToken.getValue()))); model.put("id_token", toPrettyJsonString( parseToken((String) accessToken.getAdditionalInformation().get("id_token")))); } return "authorization_code"; }
From source file:org.cloudfoundry.identity.uaa.oauth.DefaultTokenConverter.java
@Override public Map<String, ?> convertAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) { Map<String, Object> response = new HashMap<String, Object>(); AuthorizationRequest clientToken = authentication.getAuthorizationRequest(); if (!authentication.isClientOnly()) { response.putAll(userTokenConverter.convertUserAuthentication(authentication.getUserAuthentication())); }// w w w .j ava 2s .c om response.put(OAuth2AccessToken.SCOPE, token.getScope()); if (token.getAdditionalInformation().containsKey(JwtTokenEnhancer.TOKEN_ID)) { response.put(JwtTokenEnhancer.TOKEN_ID, token.getAdditionalInformation().get(JwtTokenEnhancer.TOKEN_ID)); } if (token.getExpiration() != null) { response.put("exp", token.getExpiration().getTime() / 1000); } response.putAll(token.getAdditionalInformation()); response.put("client_id", clientToken.getClientId()); if (clientToken.getResourceIds() != null && !clientToken.getResourceIds().isEmpty()) { response.put("aud", clientToken.getResourceIds()); } return response; }
From source file:org.openmhealth.shim.ihealth.IHealthShim.java
@Override protected ResponseEntity<ShimDataResponse> getData(OAuth2RestOperations restTemplate, ShimDataRequest shimDataRequest) throws ShimException { final IHealthDataTypes dataType; try {/* w w w.j av a2 s .c om*/ dataType = valueOf(shimDataRequest.getDataTypeKey().trim().toUpperCase()); } catch (NullPointerException | IllegalArgumentException e) { throw new ShimException("Null or Invalid data type parameter: " + shimDataRequest.getDataTypeKey() + " in shimDataRequest, cannot retrieve data."); } OffsetDateTime now = OffsetDateTime.now(); OffsetDateTime startDate = shimDataRequest.getStartDateTime() == null ? now.minusDays(1) : shimDataRequest.getStartDateTime(); OffsetDateTime endDate = shimDataRequest.getEndDateTime() == null ? now.plusDays(1) : shimDataRequest.getEndDateTime(); /* The physical activity point handles start and end datetimes differently than the other endpoints. It requires use to include the range until the beginning of the next day. */ if (dataType == PHYSICAL_ACTIVITY) { endDate = endDate.plusDays(1); } // SC and SV values are client-based keys that are unique to each endpoint within a project String scValue = getScValue(); List<String> svValues = getSvValues(dataType); List<JsonNode> responseEntities = newArrayList(); int i = 0; // We iterate because one of the measures (Heart rate) comes from multiple endpoints, so we submit // requests to each of these endpoints, map the responses separately and then combine them for (String endPoint : dataType.getEndPoint()) { UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(API_URL); // Need to use a dummy userId if we haven't authenticated yet. This is the case where we are using // getData to trigger Spring to conduct the OAuth exchange String userId = "uk"; if (shimDataRequest.getAccessParameters() != null) { OAuth2AccessToken token = SerializationUtils .deserialize(shimDataRequest.getAccessParameters().getSerializedToken()); userId = Preconditions.checkNotNull((String) token.getAdditionalInformation().get("UserID")); uriBuilder.queryParam("access_token", token.getValue()); } uriBuilder.path("/user/").path(userId + "/").path(endPoint) .queryParam("client_id", restTemplate.getResource().getClientId()) .queryParam("client_secret", restTemplate.getResource().getClientSecret()) .queryParam("start_time", startDate.toEpochSecond()) .queryParam("end_time", endDate.toEpochSecond()).queryParam("locale", "default") .queryParam("sc", scValue).queryParam("sv", svValues.get(i)); ResponseEntity<JsonNode> responseEntity; try { URI url = uriBuilder.build().encode().toUri(); responseEntity = restTemplate.getForEntity(url, JsonNode.class); } catch (HttpClientErrorException | HttpServerErrorException e) { // FIXME figure out how to handle this logger.error("A request for iHealth data failed.", e); throw e; } if (shimDataRequest.getNormalize()) { IHealthDataPointMapper mapper; switch (dataType) { case PHYSICAL_ACTIVITY: mapper = new IHealthPhysicalActivityDataPointMapper(); break; case BLOOD_GLUCOSE: mapper = new IHealthBloodGlucoseDataPointMapper(); break; case BLOOD_PRESSURE: mapper = new IHealthBloodPressureDataPointMapper(); break; case BODY_WEIGHT: mapper = new IHealthBodyWeightDataPointMapper(); break; case BODY_MASS_INDEX: mapper = new IHealthBodyMassIndexDataPointMapper(); break; case STEP_COUNT: mapper = new IHealthStepCountDataPointMapper(); break; case SLEEP_DURATION: mapper = new IHealthSleepDurationDataPointMapper(); break; case HEART_RATE: // there are two different mappers for heart rate because the data can come from two endpoints if (endPoint == "bp.json") { mapper = new IHealthBloodPressureEndpointHeartRateDataPointMapper(); break; } else if (endPoint == "spo2.json") { mapper = new IHealthBloodOxygenEndpointHeartRateDataPointMapper(); break; } case OXYGEN_SATURATION: mapper = new IHealthOxygenSaturationDataPointMapper(); break; default: throw new UnsupportedOperationException(); } responseEntities.addAll(mapper.asDataPoints(singletonList(responseEntity.getBody()))); } else { responseEntities.add(responseEntity.getBody()); } i++; } return ResponseEntity.ok().body(ShimDataResponse.result(SHIM_KEY, responseEntities)); }
From source file:no.imr.common.security.jwt.DefaultAccessTokenConverter.java
public Map<String, ?> convertAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) { Map<String, Object> response = new HashMap<String, Object>(); OAuth2Request clientToken = authentication.getOAuth2Request(); if (!authentication.isClientOnly()) { response.putAll(userTokenConverter.convertUserAuthentication(authentication.getUserAuthentication())); } else {// ww w . j ava 2 s . co m if (clientToken.getAuthorities() != null && !clientToken.getAuthorities().isEmpty()) { response.put(UserAuthenticationConverter.AUTHORITIES, AuthorityUtils.authorityListToSet(clientToken.getAuthorities())); } } if (token.getScope() != null) { response.put(SCOPE, token.getScope()); } if (token.getAdditionalInformation().containsKey(JTI)) { response.put(JTI, token.getAdditionalInformation().get(JTI)); } if (token.getExpiration() != null) { response.put(EXP, token.getExpiration().getTime() / 1000); } if (includeGrantType && authentication.getOAuth2Request().getGrantType() != null) { response.put(GRANT_TYPE, authentication.getOAuth2Request().getGrantType()); } response.putAll(token.getAdditionalInformation()); response.put(CLIENT_ID, clientToken.getClientId()); if (clientToken.getResourceIds() != null && !clientToken.getResourceIds().isEmpty()) { response.put(AUD, clientToken.getResourceIds()); } return response; }
From source file:org.apigw.authserver.web.controller.CertifiedClientsController.java
private CertifiedClientDetails retrieveUserDetailsForCertifiedClient(String clientID, Map<String, Collection<OAuth2AccessToken>> accessTokens) { SimpleDateFormat formatter = getTimestampFormatter(); Date now = new Date(); CertifiedClientDetails certifiedClientDetails = new CertifiedClientDetails(); for (Map.Entry<String, Collection<OAuth2AccessToken>> entry : accessTokens.entrySet()) { //Find all users that match this client for (OAuth2AccessToken token : entry.getValue()) { if (token.getExpiration() == null || token.getExpiration().before(now)) { continue; }//from ww w . j a va 2 s. c o m String tokenValue = token.getValue(); String userClientID = consumerTokenServices.getClientId(tokenValue); if (userClientID.equalsIgnoreCase(clientID)) { UserDetail userDetails = new UserDetail(); userDetails.setResidentId(entry.getKey()); if (token.getExpiration() != null) { userDetails.setExpires(formatter.format(token.getExpiration())); } String scopes = getScopesString(token.getScope()); userDetails.setScopes(scopes); Map<String, Object> addInfo = token.getAdditionalInformation(); userDetails.setGrantId(addInfo.get("authorization_grant_id").toString()); if (addInfo != null && addInfo.get("issue_date") != null && addInfo.get("issue_date") instanceof Date) { userDetails.setIssued(formatter.format(addInfo.get("issue_date"))); } if (certifiedClientDetails.getClientId() != null) { certifiedClientDetails.getUserDetails().add(userDetails); } else { CertifiedClient client = (CertifiedClient) clientDetailsService .loadClientByClientId(userClientID); certifiedClientDetails.setClientId(clientID); certifiedClientDetails.setClientName(client.getName()); certifiedClientDetails.setOrganization(client.getOrganization()); certifiedClientDetails.setDescription(client.getDescription()); certifiedClientDetails.getUserDetails().add(userDetails); } } } } return certifiedClientDetails; }
From source file:org.springframework.security.oauth2.common.OAuth2AccessTokenJackson2Serializer.java
@Override public void serialize(OAuth2AccessToken token, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { jgen.writeStartObject();/*from ww w . jav a 2 s .c o m*/ jgen.writeStringField(OAuth2AccessToken.ACCESS_TOKEN, token.getValue()); jgen.writeStringField(OAuth2AccessToken.TOKEN_TYPE, token.getTokenType()); OAuth2RefreshToken refreshToken = token.getRefreshToken(); if (refreshToken != null) { jgen.writeStringField(OAuth2AccessToken.REFRESH_TOKEN, refreshToken.getValue()); } Date expiration = token.getExpiration(); if (expiration != null) { long now = System.currentTimeMillis(); jgen.writeNumberField(OAuth2AccessToken.EXPIRES_IN, (expiration.getTime() - now) / 1000); } Set<String> scope = token.getScope(); if (scope != null && !scope.isEmpty()) { StringBuffer scopes = new StringBuffer(); for (String s : scope) { Assert.hasLength(s, "Scopes cannot be null or empty. Got " + scope + ""); scopes.append(s); scopes.append(" "); } jgen.writeStringField(OAuth2AccessToken.SCOPE, scopes.substring(0, scopes.length() - 1)); } Map<String, Object> additionalInformation = token.getAdditionalInformation(); for (String key : additionalInformation.keySet()) { jgen.writeObjectField(key, additionalInformation.get(key)); } jgen.writeEndObject(); }
From source file:org.cloudfoundry.identity.uaa.oauth.token.UaaTokenServicesTests.java
@Test public void testCreateAccessTokenAuthcodeGrantAdditionalAuthorizationAttributes() { 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"); azParameters.put("authorities", "{\"az_attr\":{\"external_group\":\"domain\\\\group1\", \"external_id\":\"abcd1234\"}}"); 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 token = testCreateAccessTokenForAUser(authentication, false); Map<String, String> azMap = new LinkedHashMap<String, String>(); azMap.put("external_group", "domain\\group1"); azMap.put("external_id", "abcd1234"); assertEquals(azMap, token.getAdditionalInformation().get("az_attr")); }