List of usage examples for org.springframework.web.util UriUtils encode
public static String encode(String source, Charset charset)
From source file:org.mla.cbox.shibboleth.idp.authn.impl.ValidateUsernamePasswordAgainstMlaRest.java
/** {@inheritDoc} */ @Override/* www .j a v a 2s .c om*/ protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext, @Nonnull final AuthenticationContext authenticationContext) { log.debug("{} Attempting to authenticate user {}", getLogPrefix(), getUsernamePasswordContext().getUsername()); try { // Construct the URL composed of the API root, members method with id value equal // to the username entered in the login form, the API key, and time stamp. StringBuilder urlBuilder = new StringBuilder().append(this.apiRoot).append("members/") .append(getUsernamePasswordContext().getUsername()).append("?").append("key=") .append(this.apiKey).append("×tamp=") .append(String.valueOf(Instant.now().getEpochSecond())); // The signature is created by prepending the GET method with a '&' separator to the // URL and then computing the SHA256 HMAC hash using the key. // StringBuilder baseStringBuilder = new StringBuilder().append("GET").append("&") .append(UriUtils.encode(urlBuilder.toString(), "UTF-8")); Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); SecretKeySpec secretKey = new SecretKeySpec(this.apiSecret.getBytes("UTF-8"), "HmacSHA256"); sha256_HMAC.init(secretKey); String signature = Hex .encodeHexString(sha256_HMAC.doFinal(baseStringBuilder.toString().getBytes("UTF-8"))); // Append the signature to the URL. urlBuilder.append("&signature=").append(signature); log.debug("{} MLA query URL is {}", getLogPrefix(), urlBuilder.toString()); // Query the MLA API HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() { @Override public void initialize(HttpRequest request) { /* Set default parser as a JSON parser to make casting to class instance easier */ request.setParser(new JsonObjectParser(JSON_FACTORY)); } }); HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(urlBuilder.toString())); HttpResponse response = request.execute(); // Parse the response and create an instance of the MLAMemberObject. MLAMemberObject mlaMembership = response.parseAs(MLAMemberObject.class); List<MLAMemberObjectData> data = mlaMembership.getData(); // The data element, if present, is a list. If not present then the size of the list // is zero and this indicates that the username could not be found. if (data.size() < 1) { log.info("{} User {} is not known to MLA", getLogPrefix(), getUsernamePasswordContext().getUsername()); handleError(profileRequestContext, authenticationContext, AuthnEventIds.NO_CREDENTIALS, AuthnEventIds.NO_CREDENTIALS); return; } // Parse out the id, username, password hash, and membership status. String memberId = data.get(0).getId(); String username = data.get(0).getAuthentication().getUsername(); String passwordHash = data.get(0).getAuthentication().getPassword(); String membershipStatus = data.get(0).getAuthentication().getMembership_status(); log.debug("{} MLA returned member Id {}", getLogPrefix(), memberId); log.debug("{} MLA returned username {}", getLogPrefix(), username); log.debug("{} MLA returned password hash {}", getLogPrefix(), passwordHash); log.debug("{} MLA returned membership status {}", getLogPrefix(), membershipStatus); // Non-active members cannot authenticate. if (!new String("active").equals(membershipStatus)) { log.info("{} User {} does not have active status", getLogPrefix(), getUsernamePasswordContext().getUsername()); handleError(profileRequestContext, authenticationContext, AuthnEventIds.NO_CREDENTIALS, AuthnEventIds.NO_CREDENTIALS); return; } // Compute the bcrypt hash of the password using the salt sent by the MLA API. String pw_hash = BCrypt.hashpw(getUsernamePasswordContext().getPassword(), passwordHash); log.debug("{} Computed hash {}", getLogPrefix(), pw_hash); // Compare the input username with the password hash returned by the MLA API. if (!pw_hash.equals(passwordHash)) { log.info("{} Invalid password", getLogPrefix(), getUsernamePasswordContext().getUsername()); handleError(profileRequestContext, authenticationContext, AuthnEventIds.INVALID_CREDENTIALS, AuthnEventIds.INVALID_CREDENTIALS); return; } // Set the username in the context directly because the user may have typed the member number // into the form rather than the username. The member number will work for authentication, // but we always want to return the username as the principal. getUsernamePasswordContext().setUsername(username); // Build the authentication result and proceed. log.info("{} Login by '{}' succeeded", getLogPrefix(), getUsernamePasswordContext().getUsername()); buildAuthenticationResult(profileRequestContext, authenticationContext); ActionSupport.buildProceedEvent(profileRequestContext); // } catch (IOException | NoSuchAlgorithmException | InvalidKeyException | InterruptedException e) { } catch (IOException | NoSuchAlgorithmException | InvalidKeyException e) { log.warn("{} Login by {} produced exception", getLogPrefix(), getUsernamePasswordContext().getUsername(), e); handleError(profileRequestContext, authenticationContext, e, AuthnEventIds.AUTHN_EXCEPTION); } }
From source file:io.dacopancm.jfee.managedController.SociosBean.java
public String addSocioAction() { try {/* ww w .j a v a 2 s. c o m*/ socioService.addSocio(selectedSocio); planList = null; FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Afiliacin", "Afiliacin exitosa!")); return "/views/s/adminSocios/facturaAfiliacion.xhtml?faces-redirect=true&socCi=" + selectedSocio.getUsuario().getUsrCi() + "&h=" + UriUtils.encode(new BCryptPasswordEncoder().encode(selectedSocio.getUsuario().getUsrCi()), "UTF-8") + "&r=" + returnPage; } catch (JfeeCustomException fex) { log.error("jfee: " + fex, fex); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", fex.getMessage())); } catch (UnsupportedEncodingException ex) { log.error("jfee: " + ex, ex); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "No se pudo Afiliar.")); } return null; }
From source file:io.dacopancm.jfee.managedController.SociosBean.java
public String editSocioRequestPageAction() { try {//from ww w . j a v a2 s.c o m return "/views/s/adminSocios/editarSocio.xhtml?faces-redirect=true&socCi=" + selectedSocio.getUsuario().getUsrCi() + "&h=" + UriUtils.encode(new BCryptPasswordEncoder().encode(selectedSocio.getUsuario().getUsrCi()), "UTF-8") + "&r=adminSocios"; } catch (UnsupportedEncodingException ex) { log.error("jfee: " + ex, ex); } return null; }