List of usage examples for org.springframework.util LinkedMultiValueMap LinkedMultiValueMap
public LinkedMultiValueMap()
From source file:org.kaaproject.kaa.server.common.admin.AdminClient.java
/** * Revokes security credentials from the corresponding credentials storage. * Also launches an asynchronous process to terminate all active sessions of * the endpoint that uses these credentials. * * @param applicationToken the application token * @param credentialsId the id of the credentials *//*from w w w .j ava 2s .c om*/ public void revokeCredentials(String applicationToken, String credentialsId) { MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<>(); parameters.add("applicationToken", applicationToken); parameters.add("credentialsId", credentialsId); this.restTemplate.postForLocation(restTemplate.getUrl() + "revokeCredentials", parameters); }
From source file:org.kaaproject.kaa.server.common.admin.AdminClient.java
/** * Used if credentials stored in external storage and Kaa server can't directly revoke them but * can be notified about security credentials revocation by external system. * * <p>If an endpoint is already registered with the specified credentials, this API * call launches an asynchronous process to terminate all active sessions of * the corresponding endpoint.</p> * * @param applicationToken the application token * @param credentialsId the id of the credentials *//*from w w w . jav a 2 s.c om*/ public void onCredentialsRevoked(String applicationToken, String credentialsId) { MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<>(); parameters.add("applicationToken", applicationToken); parameters.add("credentialsId", credentialsId); this.restTemplate.postForLocation(restTemplate.getUrl() + "notifyRevoked", parameters); }
From source file:org.kuali.rice.kew.doctype.service.impl.DocumentSecurityServiceImpl.java
protected void processDocumentRequiringExtensionProcessing(List<Document> documentsRequiringExtensionProcessing, SecuritySession securitySession, Set<String> authorizations) { if (CollectionUtils.isNotEmpty(documentsRequiringExtensionProcessing)) { LOG.info("Beginning processing of documents requiring extension processing (total: " + documentsRequiringExtensionProcessing.size() + " documents)"); long start = System.currentTimeMillis(); MultiValueMap<PartitionKey, Document> partitions = partitionDocumentsForSecurity( documentsRequiringExtensionProcessing, securitySession); MultiValueMap<String, DocumentSecurityDirective> applicationSecurityDirectives = new LinkedMultiValueMap<String, DocumentSecurityDirective>(); for (PartitionKey partitionKey : partitions.keySet()) { DocumentSecurityDirective directive = DocumentSecurityDirective .create(partitionKey.getDocumentSecurityAttributeNameList(), partitions.get(partitionKey)); applicationSecurityDirectives.add(partitionKey.applicationId, directive); }//from ww w .j a va 2s .com for (String applicationId : applicationSecurityDirectives.keySet()) { List<DocumentSecurityDirective> documentSecurityDirectives = applicationSecurityDirectives .get(applicationId); DocumentSecurityHandlerService securityHandler = loadSecurityHandler(applicationId); List<String> authorizedDocumentIds = securityHandler .getAuthorizedDocumentIds(securitySession.getPrincipalId(), documentSecurityDirectives); if (CollectionUtils.isNotEmpty(authorizedDocumentIds)) { authorizations.addAll(authorizedDocumentIds); } } long end = System.currentTimeMillis(); LOG.info("Finished processing of documents requiring extension processing (total time: " + (start - end) + ")"); } }
From source file:org.kuali.rice.kew.doctype.service.impl.DocumentSecurityServiceImpl.java
protected MultiValueMap<PartitionKey, Document> partitionDocumentsForSecurity(List<Document> documents, SecuritySession securitySession) { MultiValueMap<PartitionKey, Document> partitions = new LinkedMultiValueMap<PartitionKey, Document>(); for (Document document : documents) { DocumentTypeSecurity security = getDocumentTypeSecurity(document.getDocumentTypeName(), securitySession);// w ww . ja v a 2 s . c om MultiValueMap<String, ExtensionDefinition> securityAttributeExtensionDefinitions = loadExtensionDefinitions( security, securitySession); for (String applicationId : securityAttributeExtensionDefinitions.keySet()) { List<ExtensionDefinition> extensionDefinitions = securityAttributeExtensionDefinitions .get(applicationId); PartitionKey key = new PartitionKey(applicationId, extensionDefinitions); partitions.add(key, document); } } return partitions; }
From source file:org.kuali.rice.kew.doctype.service.impl.DocumentSecurityServiceImpl.java
protected MultiValueMap<String, ExtensionDefinition> loadExtensionDefinitions(DocumentTypeSecurity security, SecuritySession securitySession) { MultiValueMap<String, ExtensionDefinition> securityAttributeExtensionDefinitions = new LinkedMultiValueMap<String, ExtensionDefinition>(); List<String> securityAttributeExtensionNames = security.getSecurityAttributeExtensionNames(); for (String securityAttributeExtensionName : securityAttributeExtensionNames) { ExtensionDefinition extensionDefinition = extensionRepositoryService .getExtensionByName(securityAttributeExtensionName); securityAttributeExtensionDefinitions.add(extensionDefinition.getApplicationId(), extensionDefinition); }/*from w w w . j av a 2 s . co m*/ return securityAttributeExtensionDefinitions; }
From source file:org.kuali.rice.kim.impl.role.RoleServiceImpl.java
/** * Checks each of the result records to determine if there are potentially applicable delegation members for that * role membership. If there are, applicable delegations and members will be linked to the RoleMemberships in the * given list. An updated list will be returned from this method which includes the appropriate linked delegations. */// w ww . j ava 2 s. c o m protected List<RoleMembership.Builder> applyDelegationsToRoleMembers(List<RoleMembership> roleMemberships, Collection<DelegateTypeBo> delegations, Map<String, String> qualification) { MultiValueMap<String, String> roleIdToRoleMembershipIds = new LinkedMultiValueMap<String, String>(); Map<String, RoleMembership.Builder> roleMembershipIdToBuilder = new HashMap<String, RoleMembership.Builder>(); List<RoleMembership.Builder> roleMembershipBuilders = new ArrayList<RoleMembership.Builder>(); // to make our algorithm less painful, let's do some indexing and load the given list of RoleMemberships into // builders for (RoleMembership roleMembership : roleMemberships) { roleIdToRoleMembershipIds.add(roleMembership.getRoleId(), roleMembership.getId()); RoleMembership.Builder builder = RoleMembership.Builder.create(roleMembership); roleMembershipBuilders.add(builder); roleMembershipIdToBuilder.put(roleMembership.getId(), builder); } for (DelegateTypeBo delegation : delegations) { // determine the candidate role memberships where this delegation can be mapped List<String> candidateRoleMembershipIds = roleIdToRoleMembershipIds.get(delegation.getRoleId()); if (CollectionUtils.isNotEmpty(candidateRoleMembershipIds)) { DelegationTypeService delegationTypeService = getDelegationTypeService( delegation.getDelegationId()); for (DelegateMemberBo delegationMember : delegation.getMembers()) { // Make sure that the delegation member is active if (delegationMember.isActive(DateTime.now()) && (delegationTypeService == null || delegationTypeService.doesDelegationQualifierMatchQualification(qualification, delegationMember.getQualifier()))) { DelegateMember.Builder delegateMemberBuilder = DelegateMember.Builder .create(delegationMember); // if the member has no role member id, check qualifications and apply to all matching role memberships on the role if (StringUtils.isBlank(delegationMember.getRoleMemberId())) { RoleTypeService roleTypeService = getRoleTypeService(delegation.getRoleId()); for (String roleMembershipId : candidateRoleMembershipIds) { RoleMembership.Builder roleMembershipBuilder = roleMembershipIdToBuilder .get(roleMembershipId); if (roleTypeService == null || roleTypeService.doesRoleQualifierMatchQualification( roleMembershipBuilder.getQualifier(), delegationMember.getQualifier())) { linkDelegateToRoleMembership(delegation, delegateMemberBuilder, roleMembershipBuilder); } } } else if (candidateRoleMembershipIds.contains(delegationMember.getRoleMemberId())) { RoleMembership.Builder roleMembershipBuilder = roleMembershipIdToBuilder .get(delegationMember.getRoleMemberId()); linkDelegateToRoleMembership(delegation, delegateMemberBuilder, roleMembershipBuilder); } } } } } return roleMembershipBuilders; }
From source file:org.mitre.openid.connect.client.AbstractOIDCAuthenticationFilter.java
/** * Handles the authorization grant response * /* ww w.jav a 2 s. com*/ * @param authorizationGrant * The Authorization grant code * @param request * The request from which to extract parameters and perform the * authentication * @return The authenticated user token, or null if authentication is * incomplete. * @throws Exception * @throws UnsupportedEncodingException */ protected Authentication handleAuthorizationGrantResponse(String authorizationGrant, HttpServletRequest request, OIDCServerConfiguration serverConfig) { final boolean debug = logger.isDebugEnabled(); // Handle Token Endpoint interaction HttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter("http.socket.timeout", new Integer(httpSocketTimeout)); // // TODO: basic auth is untested (it wasn't working last I // tested) // UsernamePasswordCredentials credentials = new // UsernamePasswordCredentials(serverConfig.getClientId(), // serverConfig.getClientSecret()); // ((DefaultHttpClient) // httpClient).getCredentialsProvider().setCredentials(AuthScope.ANY, // credentials); // HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient); RestTemplate restTemplate = new RestTemplate(factory); MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); form.add("grant_type", "authorization_code"); form.add("code", authorizationGrant); form.add("redirect_uri", AbstractOIDCAuthenticationFilter.buildRedirectURI(request, null)); // pass clientId and clientSecret in post of request form.add("client_id", serverConfig.getClientId()); form.add("client_secret", serverConfig.getClientSecret()); if (debug) { logger.debug("tokenEndpointURI = " + serverConfig.getTokenEndpointURI()); logger.debug("form = " + form); } ; String jsonString = null; try { jsonString = restTemplate.postForObject(serverConfig.getTokenEndpointURI(), form, String.class); } catch (HttpClientErrorException httpClientErrorException) { // Handle error logger.error("Token Endpoint error response: " + httpClientErrorException.getStatusText() + " : " + httpClientErrorException.getMessage()); throw new AuthenticationServiceException("Unable to obtain Access Token."); } logger.debug("from TokenEndpoint jsonString = " + jsonString); JsonElement jsonRoot = new JsonParser().parse(jsonString); if (jsonRoot.getAsJsonObject().get("error") != null) { // Handle error String error = jsonRoot.getAsJsonObject().get("error").getAsString(); logger.error("Token Endpoint returned: " + error); throw new AuthenticationServiceException( "Unable to obtain Access Token. Token Endpoint returned: " + error); } else { // Extract the id_token to insert into the // OpenIdConnectAuthenticationToken IdToken idToken = null; JwtSigningAndValidationService jwtValidator = getValidatorForServer(serverConfig); if (jsonRoot.getAsJsonObject().get("id_token") != null) { try { idToken = IdToken.parse(jsonRoot.getAsJsonObject().get("id_token").getAsString()); } catch (AuthenticationServiceException e) { // I suspect this could happen logger.error("Problem parsing id_token: " + e); // e.printStackTrace(); throw new AuthenticationServiceException( "Problem parsing id_token return from Token endpoint: " + e); } if (jwtValidator .validateSignature(jsonRoot.getAsJsonObject().get("id_token").getAsString()) == false) { throw new AuthenticationServiceException("Signature not validated"); } if (idToken.getClaims().getIssuer() == null) { throw new AuthenticationServiceException("Issuer is null"); } if (!idToken.getClaims().getIssuer().equals(serverConfig.getIssuer())) { throw new AuthenticationServiceException("Issuers do not match"); } if (jwtValidator.isJwtExpired(idToken)) { throw new AuthenticationServiceException("Id Token is expired"); } if (jwtValidator.validateIssuedAt(idToken) == false) { throw new AuthenticationServiceException("Id Token issuedAt failed"); } } else { // An error is unlikely, but it good security to check logger.error("Token Endpoint did not return an id_token"); throw new AuthenticationServiceException("Token Endpoint did not return an id_token"); } // Clients are required to compare nonce claim in ID token to // the nonce sent in the Authorization request. The client // stores this value as a signed session cookie to detect a // replay by third parties. // // See: OpenID Connect Messages Section 2.1.1 entitled "ID Token" // // http://openid.net/specs/openid-connect-messages-1_0.html#id_token // //String nonce = idToken.getClaims().getClaimAsString("nonce"); String nonce = idToken.getClaims().getNonce(); if (StringUtils.isBlank(nonce)) { logger.error("ID token did not contain a nonce claim."); throw new AuthenticationServiceException("ID token did not contain a nonce claim."); } Cookie nonceSignatureCookie = WebUtils.getCookie(request, NONCE_SIGNATURE_COOKIE_NAME); if (nonceSignatureCookie != null) { String sigText = nonceSignatureCookie.getValue(); if (sigText != null && !sigText.isEmpty()) { if (!verify(signer, publicKey, nonce, sigText)) { logger.error("Possible replay attack detected! " + "The comparison of the nonce in the returned " + "ID Token to the signed session " + NONCE_SIGNATURE_COOKIE_NAME + " failed."); throw new AuthenticationServiceException("Possible replay attack detected! " + "The comparison of the nonce in the returned " + "ID Token to the signed session " + NONCE_SIGNATURE_COOKIE_NAME + " failed."); } } else { logger.error(NONCE_SIGNATURE_COOKIE_NAME + " cookie was found but value was null or empty"); throw new AuthenticationServiceException( NONCE_SIGNATURE_COOKIE_NAME + " cookie was found but value was null or empty"); } } else { logger.error(NONCE_SIGNATURE_COOKIE_NAME + " cookie was not found."); throw new AuthenticationServiceException(NONCE_SIGNATURE_COOKIE_NAME + " cookie was not found."); } // pull the user_id out as a claim on the id_token String userId = idToken.getTokenClaims().getUserId(); // construct an OpenIdConnectAuthenticationToken and return // a Authentication object w/the userId and the idToken OpenIdConnectAuthenticationToken token = new OpenIdConnectAuthenticationToken(userId, idToken); Authentication authentication = this.getAuthenticationManager().authenticate(token); return authentication; } }
From source file:org.openlmis.upload.AuthService.java
/** * Retrieves access token from the auth service. * * @return token//from www . jav a 2 s . c om */ public String obtainAccessToken() { String plainCreds = configuration.getClientId() + ":" + configuration.getClientSecret(); byte[] plainCredsBytes = plainCreds.getBytes(); byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes); String base64Creds = new String(base64CredsBytes); HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", "Basic " + base64Creds); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); form.add("username", configuration.getLogin()); form.add("password", configuration.getPassword()); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(form, headers); RequestParameters params = RequestParameters.init().set("grant_type", "password"); try { ResponseEntity<?> response = restTemplate.exchange( createUri(configuration.getHost() + "/api/oauth/token", params), HttpMethod.POST, request, Object.class); return ((Map<String, String>) response.getBody()).get(ACCESS_TOKEN); } catch (RestClientException ex) { throw new AuthorizationException("Cannot obtain access token using the provided credentials. " + "Please verify they are correct.", ex); } }
From source file:org.opentestsystem.shared.security.oauth.client.grant.samlbearer.SamlAssertionAccessTokenProvider.java
private MultiValueMap<String, String> getParametersForTokenRequest( final BaseOAuth2ProtectedResourceDetails resource, final String assertion) { final MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); form.set("grant_type", SAML2_BEARER_GRANT_TYPE); form.set("assertion", assertion); form.set("client_id", resource.getClientId()); LOGGER.info("YEAH... " + resource.getClientId()); if (resource.isScoped()) { final String scopeString = resource.getScope() != null ? StringUtils.collectionToDelimitedString(resource.getScope(), " ") : ""; form.set("scope", scopeString); LOGGER.info("YEAH... scope " + scopeString); }/*from ww w .j ava 2s. c o m*/ return form; }
From source file:org.pesc.cds.web.TranscriptRequestController.java
private void sendDocument(File outboxFile, String endpointURI, Transaction tx, String fileFormat, String documentType, String department) throws IOException { byte[] fileSignature = pkiService.createDigitalSignature(new FileInputStream(outboxFile), pkiService.getSigningKeys().getPrivate()); try {// w w w .ja v a 2 s.c o m LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>(); map.add("recipient_id", tx.getRecipientId()); map.add("sender_id", tx.getSenderId()); map.add("signer_id", localServerId); map.add("file_format", fileFormat); map.add("document_type", documentType); map.add("department", department); map.add("transaction_id", tx.getId()); map.add("ack_url", localServerWebServiceURL); map.add("file", new FileSystemResource(outboxFile)); map.add("signature", new ByteArrayResource(fileSignature) { @Override public String getFilename() { return "signature.dat"; } }); org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders(); headers.setContentType(org.springframework.http.MediaType.MULTIPART_FORM_DATA); ResponseEntity<String> response = restTemplate.exchange(endpointURI, HttpMethod.POST, new org.springframework.http.HttpEntity<Object>(map, headers), String.class); if (response.getStatusCode() != HttpStatus.OK) { throw new IllegalArgumentException( "Failed to send document. Reason: " + response.getStatusCode().getReasonPhrase()); } log.info(response.getStatusCode().getReasonPhrase()); } catch (ResourceAccessException e) { //Force the OAuth client to retrieve the token again whenever it is used again. restTemplate.getOAuth2ClientContext().setAccessToken(null); tx.setError(e.getMessage()); transactionService.update(tx); log.error(e); throw new IllegalArgumentException(e); } catch (Exception e) { tx.setError(e.getMessage()); transactionService.update(tx); log.error(e); throw new IllegalArgumentException(e); } }