List of usage examples for org.springframework.util LinkedMultiValueMap LinkedMultiValueMap
public LinkedMultiValueMap()
From source file:org.mitre.oauth2.introspectingfilter.IntrospectingTokenService.java
/** * Validate a token string against the introspection endpoint, * then parse it and store it in the local cache if caching is enabled. * * @param accessToken Token to pass to the introspection endpoint * @return TokenCacheObject containing authentication and token if the token was valid, otherwise null *//*from ww w. j a va 2 s. c o m*/ private TokenCacheObject parseToken(String accessToken) { // find out which URL to ask String introspectionUrl; RegisteredClient client; try { introspectionUrl = introspectionConfigurationService.getIntrospectionUrl(accessToken); client = introspectionConfigurationService.getClientConfiguration(accessToken); } catch (IllegalArgumentException e) { logger.error("Unable to load introspection URL or client configuration", e); return null; } // Use the SpringFramework RestTemplate to send the request to the // endpoint String validatedToken = null; RestTemplate restTemplate; MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); final String clientId = client.getClientId(); final String clientSecret = client.getClientSecret(); if (SECRET_BASIC.equals(client.getTokenEndpointAuthMethod())) { // use BASIC auth if configured to do so restTemplate = new RestTemplate(factory) { @Override protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException { ClientHttpRequest httpRequest = super.createRequest(url, method); httpRequest.getHeaders().add("Authorization", String.format("Basic %s", Base64.encode(String.format("%s:%s", clientId, clientSecret)))); return httpRequest; } }; } else { //Alternatively use form based auth restTemplate = new RestTemplate(factory); form.add("client_id", clientId); form.add("client_secret", clientSecret); } form.add("token", accessToken); try { validatedToken = restTemplate.postForObject(introspectionUrl, form, String.class); } catch (RestClientException rce) { logger.error("validateToken", rce); return null; } if (validatedToken != null) { // parse the json JsonElement jsonRoot = new JsonParser().parse(validatedToken); if (!jsonRoot.isJsonObject()) { return null; // didn't get a proper JSON object } JsonObject tokenResponse = jsonRoot.getAsJsonObject(); if (tokenResponse.get("error") != null) { // report an error? logger.error("Got an error back: " + tokenResponse.get("error") + ", " + tokenResponse.get("error_description")); return null; } if (!tokenResponse.get("active").getAsBoolean()) { // non-valid token logger.info("Server returned non-active token"); return null; } // create an OAuth2Authentication OAuth2Authentication auth = new OAuth2Authentication(createStoredRequest(tokenResponse), createAuthentication(tokenResponse)); // create an OAuth2AccessToken OAuth2AccessToken token = createAccessToken(tokenResponse, accessToken); if (token.getExpiration() == null || token.getExpiration().after(new Date())) { // Store them in the cache TokenCacheObject tco = new TokenCacheObject(token, auth); if (cacheTokens && (cacheNonExpiringTokens || token.getExpiration() != null)) { authCache.put(accessToken, tco); } return tco; } } // when the token is invalid for whatever reason return null; }
From source file:com.emergya.spring.security.oauth.google.GoogleAuthorizationCodeAccessTokenProvider.java
private MultiValueMap<String, String> getParametersForTokenRequest( final AuthorizationCodeResourceDetails resource, final AccessTokenRequest request) { MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); form.set("grant_type", "authorization_code"); form.set("code", request.getAuthorizationCode()); Object preservedState = request.getPreservedState(); if (request.getStateKey() != null) { // The token endpoint has no use for the state so we don't send it back, but we are using it // for CSRF detection client side... if (preservedState == null) { throw new InvalidRequestException( "Possible CSRF detected - state parameter was present but no state could be found"); }/* w ww. j a v a 2 s . c om*/ } // Extracting the redirect URI from a saved request should ignore the current URI, so it's not simply a call to // resource.getRedirectUri() String redirectUri; // Get the redirect uri from the stored state if (preservedState instanceof String) { // Use the preserved state in preference if it is there // TODO: treat redirect URI as a special kind of state (this is a historical mini hack) redirectUri = String.valueOf(preservedState); } else { redirectUri = resource.getRedirectUri(request); } if (redirectUri != null && !"NONE".equals(redirectUri)) { form.set("redirect_uri", redirectUri); } return form; }
From source file:org.socialsignin.spring.data.dynamodb.repository.query.AbstractDynamoDBQueryCriteria.java
protected String getGlobalSecondaryIndexName() { // Lazy evaluate the globalSecondaryIndexName if not already set // We must have attribute conditions specified in order to use a global secondary index, otherwise return null for index name // Also this method only evaluates the if (globalSecondaryIndexName == null && attributeConditions != null && !attributeConditions.isEmpty()) { // Declare map of index names by attribute name which we will populate below - this will be used to determine which index to use if multiple indexes are applicable Map<String, String[]> indexNamesByAttributeName = new HashMap<String, String[]>(); // Declare map of attribute lists by index name which we will populate below - this will be used to determine whether we have an exact match index for specified attribute conditions MultiValueMap<String, String> attributeListsByIndexName = new LinkedMultiValueMap<String, String>(); // Populate the above maps for (Entry<String, String[]> indexNamesForPropertyNameEntry : entityInformation .getGlobalSecondaryIndexNamesByPropertyName().entrySet()) { String propertyName = indexNamesForPropertyNameEntry.getKey(); String attributeName = getAttributeName(propertyName); indexNamesByAttributeName.put(attributeName, indexNamesForPropertyNameEntry.getValue()); for (String indexNameForPropertyName : indexNamesForPropertyNameEntry.getValue()) { attributeListsByIndexName.add(indexNameForPropertyName, attributeName); }/* w w w . j a va 2 s. c om*/ } // Declare lists to store matching index names List<String> exactMatchIndexNames = new ArrayList<String>(); List<String> partialMatchIndexNames = new ArrayList<String>(); // Populate matching index name lists - an index is either an exact match ( the index attributes match all the specified criteria exactly) // or a partial match ( the properties for the specified criteria are contained within the property set for an index ) for (Entry<String, List<String>> attributeListForIndexNameEntry : attributeListsByIndexName .entrySet()) { String indexNameForAttributeList = attributeListForIndexNameEntry.getKey(); List<String> attributeList = attributeListForIndexNameEntry.getValue(); if (attributeList.containsAll(attributeConditions.keySet())) { if (attributeConditions.keySet().containsAll(attributeList)) { exactMatchIndexNames.add(indexNameForAttributeList); } else { partialMatchIndexNames.add(indexNameForAttributeList); } } } if (exactMatchIndexNames.size() > 1) { throw new RuntimeException( "Multiple indexes defined on same attribute set:" + attributeConditions.keySet()); } else if (exactMatchIndexNames.size() == 1) { globalSecondaryIndexName = exactMatchIndexNames.get(0); } else if (partialMatchIndexNames.size() > 1) { if (attributeConditions.size() == 1) { globalSecondaryIndexName = getFirstDeclaredIndexNameForAttribute(indexNamesByAttributeName, partialMatchIndexNames, attributeConditions.keySet().iterator().next()); } if (globalSecondaryIndexName == null) { globalSecondaryIndexName = partialMatchIndexNames.get(0); } } else if (partialMatchIndexNames.size() == 1) { globalSecondaryIndexName = partialMatchIndexNames.get(0); } } return globalSecondaryIndexName; }
From source file:org.cloudfoundry.identity.uaa.integration.ClientAdminEndpointsIntegrationTests.java
private OAuth2AccessToken getClientCredentialsAccessToken(String scope) throws Exception { String clientId = testAccounts.getAdminClientId(); String clientSecret = testAccounts.getAdminClientSecret(); MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>(); formData.add("grant_type", "client_credentials"); formData.add("client_id", clientId); formData.add("scope", scope); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.set("Authorization", "Basic " + new String(Base64.encode(String.format("%s:%s", clientId, clientSecret).getBytes()))); @SuppressWarnings("rawtypes") ResponseEntity<Map> response = serverRunning.postForMap("/oauth/token", formData, headers); assertEquals(HttpStatus.OK, response.getStatusCode()); @SuppressWarnings("unchecked") OAuth2AccessToken accessToken = DefaultOAuth2AccessToken.valueOf(response.getBody()); return accessToken; }
From source file:test.phoenixnap.oss.plugin.naming.RamlStyleCheckerTest.java
@Test public void test_Get404Check_Fails() { RamlRoot published = RamlVerifier.loadRamlFromFile("test-style-missing-get404-fails.raml"); MultiValueMap<String, HttpStatus> statusChecks = new LinkedMultiValueMap<>(); HttpStatus status = HttpStatus.NOT_FOUND; statusChecks.add(HttpMethod.GET.name(), status); RamlVerifier verifier = new RamlVerifier(published, null, Collections.emptyList(), null, null, Collections.singletonList(new ResponseCodeDefinitionStyleChecker(statusChecks))); assertFalse("Check that raml passes rules", verifier.hasErrors()); assertTrue("Check that implementation matches rules", verifier.hasWarnings()); assertEquals("Check that implementation shuld have 1 warnings", 1, verifier.getWarnings().size()); TestHelper/*from w ww .j a v a 2 s .com*/ .verifyIssuesUnordered(verifier.getWarnings(), new Issue[] { new Issue(IssueSeverity.WARNING, IssueLocation.CONTRACT, IssueType.STYLE, String.format(ResponseCodeDefinitionStyleChecker.DESCRIPTION, "GET", status.name(), status.value()), "GET /base/endpointThatWillBoom") }); }
From source file:com.zhm.config.MyAuthorizationCodeAccessTokenProvider.java
private MultiValueMap<String, String> getParametersForAuthorizeRequest( AuthorizationCodeResourceDetails resource, AccessTokenRequest request) { MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); form.set("response_type", "code"); form.set("client_id", resource.getClientId()); if (request.get("scope") != null) { form.set("scope", request.getFirst("scope")); } else {//from w w w. j a v a2s. co m form.set("scope", OAuth2Utils.formatParameterList(resource.getScope())); } // Extracting the redirect URI from a saved request should ignore the current URI, so it's not simply a call to // resource.getRedirectUri() String redirectUri = resource.getPreEstablishedRedirectUri(); Object preservedState = request.getPreservedState(); if (redirectUri == null && preservedState != null) { // no pre-established redirect uri: use the preserved state // TODO: treat redirect URI as a special kind of state (this is a historical mini hack) redirectUri = String.valueOf(preservedState); } else { redirectUri = request.getCurrentUri(); } String stateKey = request.getStateKey(); if (stateKey != null) { form.set("state", stateKey); if (preservedState == null) { throw new InvalidRequestException( "Possible CSRF detected - state parameter was present but no state could be found"); } } if (redirectUri != null) { form.set("redirect_uri", redirectUri); } return form; }
From source file:com.github.notizklotz.derbunddownloader.download.IssueDownloadService.java
private boolean checkUserAccount() { if (BuildConfig.DEBUG) { Log.d(LOG_TAG, "Checking user account validity"); }/*w w w .ja v a 2s. com*/ try { final SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); final String username = sharedPref.getString(Settings.KEY_USERNAME, ""); final String password = sharedPref.getString(Settings.KEY_PASSWORD, ""); RestTemplate restTemplate = new RestTemplate(true); LinkedMultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); form.add("user", username); form.add("password", password); form.add("dologin", "1"); form.add("t", ""); String response = restTemplate.postForObject("http://epaper.derbund.ch", form, String.class); boolean loginSuccessful = response.contains("flashcontent"); Log.d(LOG_TAG, "Login successful? " + loginSuccessful); return loginSuccessful; } catch (RestClientException e) { Log.e(LOG_TAG, "Error while trying to login", e); return false; } }
From source file:de.tudarmstadt.ukp.csniper.webapp.evaluation.EvaluationRepository.java
/** * Persist the given items. If they already exist in the database, replace the item in the list * with the item from the database. Transient data (e.g. match offsets) is preserved. * /* www. ja v a 2s. c om*/ * @param aCreate * true = missing evaluation items are created and returned; false = missing * evaluation items are not created and returned */ @Transactional public List<EvaluationItem> writeEvaluationItems(List<EvaluationItem> aItems, boolean aCreate) { long start = System.currentTimeMillis(); log.info("Building index on in-memory items"); List<EvaluationItem> result = new ArrayList<EvaluationItem>(aItems.size()); LinkedMultiValueMap<String, EvaluationItem> idx = new LinkedMultiValueMap<String, EvaluationItem>(); for (EvaluationItem i : aItems) { idx.add(i.getCollectionId() + "-" + i.getDocumentId() + "-" + i.getType(), i); } TypedQuery<EvaluationItem> query = entityManager .createQuery("FROM EvaluationItem WHERE collectionId = :collectionId AND documentId = " + ":documentId AND type = :type", EvaluationItem.class); log.info("Merging with in-database items in " + idx.size() + " chunks"); ProgressMeter progress = new ProgressMeter(idx.size()); for (List<EvaluationItem> items : idx.values()) { progress.next(); EvaluationItem ref = items.get(0); List<EvaluationItem> pItems = query.setParameter("collectionId", ref.getCollectionId()) .setParameter("documentId", ref.getDocumentId()).setParameter("type", ref.getType()) .getResultList(); Comparator<EvaluationItem> cmp = new Comparator<EvaluationItem>() { @Override public int compare(EvaluationItem aO1, EvaluationItem aO2) { if (aO1.getBeginOffset() > aO2.getBeginOffset()) { return 1; } else if (aO1.getBeginOffset() < aO2.getBeginOffset()) { return -1; } else if (aO1.getEndOffset() > aO2.getEndOffset()) { return 1; } else if (aO1.getEndOffset() < aO2.getEndOffset()) { return -1; } else { return 0; } } }; Collections.sort(pItems, cmp); for (EvaluationItem item : items) { int i = Collections.binarySearch(pItems, item, cmp); if (i < 0) { if (aCreate) { entityManager.persist(item); result.add(item); } } else { EvaluationItem pItem = pItems.get(i); pItem.copyTransientData(item); result.add(pItem); } } log.info(progress); } log.info("writeEvaluationItems for " + aItems.size() + " items completed in " + (System.currentTimeMillis() - start) + " ms"); return result; // String query = "FROM EvaluationItem WHERE collectionId = :collectionId AND documentId = " // + // ":documentId AND type = :type AND beginOffset = :beginOffset AND endOffset = :endOffset"; // for (ListIterator<EvaluationItem> li = aItems.listIterator(); li.hasNext();) { // EvaluationItem item = li.next(); // try { // EvaluationItem pItem = entityManager.createQuery(query, EvaluationItem.class) // .setParameter("collectionId", item.getCollectionId()) // .setParameter("documentId", item.getDocumentId()) // .setParameter("type", item.getType()) // .setParameter("beginOffset", item.getBeginOffset()) // .setParameter("endOffset", item.getEndOffset()).getSingleResult(); // // // if item already exists, use that instead of persisting the new // pItem.copyTransientData(item); // li.set(pItem); // } // catch (NoResultException e) { // // persist item if not exists // if (aCreate) { // entityManager.persist(item); // } // } // } }
From source file:org.mitreid.multiparty.web.ClientController.java
@RequestMapping(value = "claims_submitted") public String claimsSubmissionCallback(@RequestParam("authorization_state") String authorizationState, @RequestParam("state") String returnState, @RequestParam("ticket") String ticket, HttpSession session, Model m) {//from w w w.ja va 2 s . c o m // get our saved information out of the session String savedState = (String) session.getAttribute(STATE_SESSION_VAR); String savedResource = (String) session.getAttribute(RESOURCE_SESSION_VAR); String savedAuthServerUri = (String) session.getAttribute(AUTHSERVERURI_SESSION_VAR); // make sure the state matches if (Strings.isNullOrEmpty(returnState) || !returnState.equals(savedState)) { // it's an error if it doesn't logger.error("Unable to match states"); return "home"; } if (authorizationState.equals("claims_submitted")) { // claims have been submitted, let's go try to get a token again // find the AS we need to talk to (maybe discover) MultipartyServerConfiguration server = serverConfig.getServerConfiguration(savedAuthServerUri); // find the client configuration (maybe register) RegisteredClient client = clientConfig.getClientConfiguration(server); HttpHeaders tokenHeaders = new HttpHeaders(); tokenHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED); // send request to the token endpoint MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add("client_id", client.getClientId()); params.add("client_secret", client.getClientSecret()); params.add("grant_type", "urn:ietf:params:oauth:grant_type:multiparty-delegation"); params.add("ticket", ticket); //params.add("scope", "read write"); HttpEntity<MultiValueMap<String, String>> tokenRequest = new HttpEntity<>(params, tokenHeaders); ResponseEntity<String> tokenResponse = restTemplate.postForEntity(server.getTokenEndpointUri(), tokenRequest, String.class); JsonObject o = parser.parse(tokenResponse.getBody()).getAsJsonObject(); if (o.has("error")) { if (o.get("error").getAsString().equals("need_info")) { // if we get need info, redirect JsonObject details = o.get("error_details").getAsJsonObject(); // this is the URL to send the user to String claimsEndpoint = details.get("requesting_party_claims_endpoint").getAsString(); String newTicket = details.get("ticket").getAsString(); // set a state value for our return String state = UUID.randomUUID().toString(); session.setAttribute(STATE_SESSION_VAR, state); // save bits about the request we were trying to make session.setAttribute(RESOURCE_SESSION_VAR, savedResource); session.setAttribute(AUTHSERVERURI_SESSION_VAR, savedAuthServerUri); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(claimsEndpoint) .queryParam("client_id", client.getClientId()).queryParam("ticket", newTicket) .queryParam("claims_redirect_uri", client.getClaimsRedirectUris().iterator().next()) // get the first one and punt .queryParam("state", state); return "redirect:" + builder.build(); } else { // it's an error we don't know how to deal with, give up logger.error("Unknown error from token endpoint: " + o.get("error").getAsString()); return "home"; } } else { // if we get an access token, try it again String accessTokenValue = o.get("access_token").getAsString(); acccessTokenService.saveAccesstoken(savedResource, accessTokenValue); HttpHeaders headers = new HttpHeaders(); if (!Strings.isNullOrEmpty(accessTokenValue)) { headers.add("Authorization", "Bearer " + accessTokenValue); } HttpEntity<Object> request = new HttpEntity<>(headers); ResponseEntity<String> responseEntity = restTemplate.exchange(savedResource, HttpMethod.GET, request, String.class); if (responseEntity.getStatusCode().equals(HttpStatus.OK)) { // if we get back data, display it JsonObject rso = parser.parse(responseEntity.getBody()).getAsJsonObject(); m.addAttribute("label", rso.get("label").getAsString()); m.addAttribute("value", rso.get("value").getAsString()); return "home"; } else { logger.error("Unable to get a token"); return "home"; } } } else { logger.error("Unknown response from claims endpoing: " + authorizationState); return "home"; } }
From source file:de.codecentric.boot.admin.zuul.filters.route.SimpleHostRoutingFilter.java
private MultiValueMap<String, String> revertHeaders(Header[] headers) { MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); for (Header header : headers) { String name = header.getName(); if (!map.containsKey(name)) { map.put(name, new ArrayList<String>()); }/*from ww w. ja v a2s . com*/ map.get(name).add(header.getValue()); } return map; }