List of usage examples for org.springframework.util LinkedMultiValueMap LinkedMultiValueMap
public LinkedMultiValueMap()
From source file:com.emergya.spring.security.oauth.google.GoogleAuthorizationCodeAccessTokenProvider.java
private MultiValueMap<String, String> getParametersForAuthorizeRequest(GoogleAuthCodeResourceDetails resource, AccessTokenRequest request) {/*from ww w .jav a 2s . c om*/ MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); form.set("response_type", "code"); form.set("client_id", resource.getClientId()); if (request.get("scope") != null) { form.set("scope", request.getFirst("scope")); } else { 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"); } } form.set("approval_prompt", resource.getApprovalPrompt()); if (StringUtils.isEmpty(resource.getLoginHint())) { form.set("login_hint", resource.getLoginHint()); } if (redirectUri != null) { form.set("redirect_uri", redirectUri); } return form; }
From source file:com.htmlhifive.sync.service.SyncResourceProcessor.java
/** * ?????.<br/>/*from w w w . j a va 2 s. c o m*/ * sync?????????. * * @param requestMessages * @throws AbstractResourceException */ private void processUploadControl(RequestMessageContainer requestMessages) throws AbstractResourceException { UploadControlType controlType = UploadControlType.valueOf(syncConfigurationParameter.UPLOAD_CONTROL_TYPE); if (controlType == UploadControlType.NONE) { return; } MultiValueMap<ResourceItemCommonDataId, RequestMessage> messageMap = new LinkedMultiValueMap<>(); for (RequestMessage requestMessage : requestMessages.getMessages()) { ResourceItemCommonDataId resourceItemCommonDataId = (ResourceItemCommonDataId) requestMessage .get(syncConfigurationParameter.RESOURCE_ITEM_COMMON_DATA_ID); messageMap.add(resourceItemCommonDataId, requestMessage); } // ID? List<ResourceItemCommonDataId> commonDataIdList = new ArrayList<>(messageMap.keySet()); Collections.sort(commonDataIdList); switch (controlType) { case SORT: // Container?Message??? List<RequestMessage> sorted = new ArrayList<>(); for (ResourceItemCommonDataId itemCommonDataId : commonDataIdList) { List<RequestMessage> messagesForId = messageMap.get(itemCommonDataId); for (RequestMessage message : messagesForId) { sorted.add(message); } } requestMessages.setMessages(sorted); break; case LOCK: // ???? for (ResourceItemCommonDataId itemCommonDataId : commonDataIdList) { List<RequestMessage> messagesForId = messageMap.get(itemCommonDataId); for (RequestMessage message : messagesForId) { // ?? ResourceMethodInvoker resourceMethod = getResourceManager().getResourceMethodByName( itemCommonDataId.getResourceName(), syncConfigurationParameter.ACTION_FOR_GETFORUPDATE, message); applyDefaultSynchronizer(resourceMethod); // ??? // ???????? @SuppressWarnings("unchecked") List<ResourceItemCommonData> got = (List<ResourceItemCommonData>) resourceMethod .invoke(message); message.put(syncConfigurationParameter.RESOURCE_ITEM_COMMON_DATA, got); } } break; default: break; } }
From source file:org.cloudfoundry.identity.uaa.login.feature.OpenIdTokenGrantsIT.java
private void doOpenIdHybridFlowIdTokenAndCode(Set<String> responseTypes, String responseTypeMatcher) throws Exception { HttpHeaders headers = new HttpHeaders(); // TODO: should be able to handle just TEXT_HTML headers.setAccept(Arrays.asList(MediaType.TEXT_HTML, MediaType.ALL)); StringBuilder responseType = new StringBuilder(); Iterator<String> rTypes = responseTypes.iterator(); while (rTypes.hasNext()) { String type = rTypes.next(); responseType.append(type);/*w w w . j av a2 s . c om*/ if (rTypes.hasNext()) { responseType.append(" "); } } String state = new RandomValueStringGenerator().generate(); String clientId = "app"; String clientSecret = "appclientsecret"; String redirectUri = "http://anywhere.com"; String uri = loginUrl + "/oauth/authorize?response_type={response_type}&" + "state={state}&client_id={client_id}&redirect_uri={redirect_uri}"; ResponseEntity<Void> result = restOperations.exchange(uri, HttpMethod.GET, new HttpEntity<>(null, headers), Void.class, responseType, state, clientId, redirectUri); assertEquals(HttpStatus.FOUND, result.getStatusCode()); String location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8"); if (result.getHeaders().containsKey("Set-Cookie")) { String cookie = result.getHeaders().getFirst("Set-Cookie"); headers.set("Cookie", cookie); } ResponseEntity<String> response = restOperations.exchange(location, HttpMethod.GET, new HttpEntity<>(null, headers), String.class); // should be directed to the login screen... assertTrue(response.getBody().contains("/login.do")); assertTrue(response.getBody().contains("username")); assertTrue(response.getBody().contains("password")); MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(); formData.add("username", user.getUserName()); formData.add("password", "secret"); // Should be redirected to the original URL, but now authenticated result = restOperations.exchange(loginUrl + "/login.do", HttpMethod.POST, new HttpEntity<>(formData, headers), Void.class); assertEquals(HttpStatus.FOUND, result.getStatusCode()); if (result.getHeaders().containsKey("Set-Cookie")) { String cookie = result.getHeaders().getFirst("Set-Cookie"); headers.set("Cookie", cookie); } location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8"); response = restOperations.exchange(location, HttpMethod.GET, new HttpEntity<>(null, headers), String.class); if (response.getStatusCode() == HttpStatus.OK) { // The grant access page should be returned assertTrue(response.getBody().contains("You can change your approval of permissions")); formData.clear(); formData.add("user_oauth_approval", "true"); result = restOperations.exchange(loginUrl + "/oauth/authorize", HttpMethod.POST, new HttpEntity<>(formData, headers), Void.class); assertEquals(HttpStatus.FOUND, result.getStatusCode()); location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8"); } else { // Token cached so no need for second approval assertEquals(HttpStatus.FOUND, response.getStatusCode()); location = UriUtils.decode(response.getHeaders().getLocation().toString(), "UTF-8"); } assertTrue("Wrong location: " + location, location.matches(redirectUri + responseTypeMatcher.toString())); formData.clear(); formData.add("client_id", clientId); formData.add("redirect_uri", redirectUri); formData.add("grant_type", "authorization_code"); formData.add("code", location.split("code=")[1].split("&")[0]); HttpHeaders tokenHeaders = new HttpHeaders(); String basicDigestHeaderValue = "Basic " + new String(Base64.encodeBase64((clientId + ":" + clientSecret).getBytes())); tokenHeaders.set("Authorization", basicDigestHeaderValue); @SuppressWarnings("rawtypes") ResponseEntity<Map> tokenResponse = restOperations.exchange(loginUrl + "/oauth/token", HttpMethod.POST, new HttpEntity<>(formData, tokenHeaders), Map.class); assertEquals(HttpStatus.OK, tokenResponse.getStatusCode()); @SuppressWarnings("unchecked") Map<String, String> body = tokenResponse.getBody(); Jwt token = JwtHelper.decode(body.get("access_token")); assertTrue("Wrong claims: " + token.getClaims(), token.getClaims().contains("\"aud\"")); assertTrue("Wrong claims: " + token.getClaims(), token.getClaims().contains("\"user_id\"")); }
From source file:architecture.ee.web.community.spring.controller.SocialConnectController.java
/** * /*from w w w . ja va2 s .co m*/ * @param providerId * @param request * @return */ protected RedirectView oauthRedirect(String providerId, NativeWebRequest request) { sessionStrategy.removeAttribute(request, PROVIDER_ERROR_ATTRIBUTE); ConnectionFactory<?> connectionFactory = ConnectionFactoryLocator.getConnectionFactory(providerId); MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>(); try { String callbackUrl = ServiceProviderHelper.getCallbackUrl(providerId); connectSupport.setCallbackUrl(callbackUrl); // String oauthUrl = connectSupport.buildOAuthUrl(connectionFactory, // request, parameters); // log.debug("oauth url:" + oauthUrl); return new RedirectView(connectSupport.buildOAuthUrl(connectionFactory, request, parameters)); } catch (Exception e) { log.error("woops error..", e); sessionStrategy.setAttribute(request, PROVIDER_ERROR_ATTRIBUTE, e); return connectionStatusRedirect(providerId, request); } }
From source file:de.uni_koeln.spinfo.maalr.webapp.controller.WebMVCController.java
@RequestMapping(value = "/persona/login", method = RequestMethod.POST) @ResponseBody//from ww w . ja v a 2s .c om public String authenticateWithPersona(@RequestParam String assertion, HttpServletRequest request, Model model) throws IOException { String contextPath = Configuration.getInstance().getDictContext(); if (SecurityContextHolder.getContext().getAuthentication() != null) { if (!SecurityContextHolder.getContext().getAuthentication().getName().equals("anonymousUser")) { Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext() .getAuthentication().getAuthorities(); for (GrantedAuthority grantedAuthority : authorities) { logger.info("GrantedAuthority: " + grantedAuthority.getAuthority()); if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) return contextPath + "/admin/admin"; if (grantedAuthority.getAuthority().equals("ROLE_TRUSTED_IN")) return contextPath + "/editor/editor"; return contextPath; } } } MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>(); params.add("assertion", assertion); params.add("audience", request.getScheme() + "://" + request.getServerName() + ":" + (request.getServerPort() == 80 ? "" : request.getServerPort())); // Initialize RestTamplate RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); restTemplate.getMessageConverters().add(new StringHttpMessageConverter()); PersonaVerificationResponse response = restTemplate.postForObject( "https://verifier.login.persona.org/verify", params, PersonaVerificationResponse.class); logger.info("PersonaAuth: PersonaVerificationResponse={}", response.toString()); if (response.getStatus().equals("okay")) { request.getSession().setMaxInactiveInterval(30 * 60); // Set session timeout to 30 minutes MaalrUserInfo user = users.getByEmail(response.getEmail()); if (user == null) { user = register(response); logger.info("PersonaAuth: signed up new user for email={}", user.getEmail()); authUser(user); return contextPath; } else { logger.info("PersonaAuth: user found by email={}", user.getEmail()); authUser(user); return contextPath; } } else { logger.warn("Persona authentication failed due to reason: " + response.getReason()); throw new IllegalStateException("Authentication failed"); } }
From source file:com.htmlhifive.sync.service.SyncResourceProcessor.java
/** * ?????.<br/>/*from w w w.j a v a 2 s . co m*/ * sync?????????. * * @param requestMessages * @throws AbstractResourceException */ private void processDownloadControl(RequestMessageContainer requestMessages) throws AbstractResourceException { DownloadControlType controlType = DownloadControlType .valueOf(syncConfigurationParameter.DOWNLOAD_CONTROL_TYPE); switch (controlType) { // LOCK??????? case LOCK: MultiValueMap<ResourceItemCommonDataId, RequestMessage> messageMap = new LinkedMultiValueMap<>(); for (RequestMessage requestMessage : requestMessages.getMessages()) { ResourceItemCommonDataId resourceItemCommonDataId = (ResourceItemCommonDataId) requestMessage .get(syncConfigurationParameter.RESOURCE_ITEM_COMMON_DATA_ID); messageMap.add(resourceItemCommonDataId, requestMessage); } List<ResourceItemCommonDataId> commonDataIdList = new ArrayList<>(messageMap.keySet()); Collections.sort(commonDataIdList); for (ResourceItemCommonDataId itemCommonDataId : commonDataIdList) { List<RequestMessage> messagesForId = messageMap.get(itemCommonDataId); for (RequestMessage message : messagesForId) { // ?? ResourceMethodInvoker resourceMethod = getResourceManager().getResourceMethodByName( itemCommonDataId.getResourceName(), syncConfigurationParameter.ACTION_FOR_GETFORUPDATE, message); applyDefaultSynchronizer(resourceMethod); // ??? @SuppressWarnings("unchecked") List<ResourceItemCommonData> got = (List<ResourceItemCommonData>) resourceMethod .invoke(message); message.put(syncConfigurationParameter.RESOURCE_ITEM_COMMON_DATA, got); } } case NONE: default: break; } }
From source file:org.mitreid.multiparty.web.ResourceController.java
/** * @param incomingAccessToken//from w ww. j a v a 2s .c om * @param server * @param client * @param protectionAccessTokenValue * @return */ private JsonObject introspectToken(String incomingAccessToken, MultipartyServerConfiguration server, RegisteredClient client, String protectionAccessTokenValue) { // POST to the introspection endpoint and get the results MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add("token", incomingAccessToken); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); headers.add("Authorization", "Bearer " + protectionAccessTokenValue); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers); HttpEntity<String> responseEntity = restTemplate.postForEntity(server.getIntrospectionEndpointUri(), request, String.class); JsonObject rso = parser.parse(responseEntity.getBody()).getAsJsonObject(); return rso; }
From source file:de.codecentric.batch.test.metrics.BatchMetricsFlatFileToDbIntegrationTest.java
private JobExecution runJob(String jobName, String pathToFile) throws InterruptedException { MultiValueMap<String, Object> requestMap = new LinkedMultiValueMap<>(); requestMap.add("jobParameters", "pathToFile=" + pathToFile); Long executionId = restTemplate.postForObject( "http://localhost:" + port + "/batch/operations/jobs/" + jobName, requestMap, Long.class); while (!restTemplate .getForObject("http://localhost:" + port + "/batch/operations/jobs/executions/{executionId}", String.class, executionId) .equals("COMPLETED") && !restTemplate.getForObject( "http://localhost:" + port + "/batch/operations/jobs/executions/{executionId}", String.class, executionId).equals("FAILED")) { Thread.sleep(1000);/* ww w . java2s.c om*/ } JobExecution jobExecution = jobExplorer.getJobExecution(executionId); return jobExecution; }
From source file:tigase.muc.modules.PresenceModule.java
private int internalValidRoom(String room, String user) { int result = -1; MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>(); try {/*from w ww. ja v a2s . c o m*/ String userId = user.substring(0, user.indexOf("@")); String domain = user.substring(user.indexOf("@"), user.length()); String roomId = room.substring(0, room.indexOf("@")); map.add("roomId", roomId); ResponseEntity<Map> data = DataUtil.postForm(DataUtil.WEB_SERVER_ADDRESS + "internalRoom", map, Map.class); Map body = data.getBody(); if (data.getStatusCode() == HttpStatus.OK) { String ownerId = (String) body.get("ownerId"); String status = (String) body.get("status"); if (ownerId != null && ownerId.equals(userId)) { result = 0; } else if ("1".equals(status)) { result = 1; } } } catch (Exception e) { // TODO log exception e.printStackTrace(); } return result; }