Пример #1
0
  /**
   * Parse the given String into a single {@code MimeType}.
   *
   * @param mimeType the string to parse
   * @return the mime type
   * @throws InvalidMimeTypeException if the string cannot be parsed
   */
  public static MimeType parseMimeType(String mimeType) {
    if (!Strings.hasLength(mimeType)) {
      throw new InvalidMimeTypeException(mimeType, "'mimeType' must not be empty");
    }
    String[] parts = Strings.tokenizeToStringArray(mimeType, ";");

    String fullType = parts[0].trim();
    // java.net.HttpURLConnection returns a *; q=.2 Accept header
    if (MimeType.WILDCARD_TYPE.equals(fullType)) {
      fullType = "*/*";
    }
    int subIndex = fullType.indexOf('/');
    if (subIndex == -1) {
      throw new InvalidMimeTypeException(mimeType, "does not contain '/'");
    }
    if (subIndex == fullType.length() - 1) {
      throw new InvalidMimeTypeException(mimeType, "does not contain subtype after '/'");
    }
    String type = fullType.substring(0, subIndex);
    String subtype = fullType.substring(subIndex + 1, fullType.length());
    if (MimeType.WILDCARD_TYPE.equals(type) && !MimeType.WILDCARD_TYPE.equals(subtype)) {
      throw new InvalidMimeTypeException(
          mimeType, "wildcard type is legal only in '*/*' (all mime types)");
    }

    Map<String, String> parameters = null;
    if (parts.length > 1) {
      parameters = new LinkedHashMap<String, String>(parts.length - 1);
      for (int i = 1; i < parts.length; i++) {
        String parameter = parts[i];
        int eqIndex = parameter.indexOf('=');
        if (eqIndex != -1) {
          String attribute = parameter.substring(0, eqIndex);
          String value = parameter.substring(eqIndex + 1, parameter.length());
          parameters.put(attribute, value);
        }
      }
    }

    try {
      return new MimeType(type, subtype, parameters);
    } catch (UnsupportedCharsetException ex) {
      throw new InvalidMimeTypeException(
          mimeType, "unsupported charset '" + ex.getCharsetName() + "'");
    } catch (IllegalArgumentException ex) {
      throw new InvalidMimeTypeException(mimeType, ex.getMessage());
    }
  }
 public static boolean containsEmailAddress(String password) {
   if (!Strings.hasText(password)) {
     return false;
   }
   matcher = pattern.matcher(password);
   return matcher.matches();
 }
  @Override
  public CsrfToken loadToken(HttpServletRequest request) {

    String token = Strings.clean(request.getParameter(parameterName));

    if (token == null) {
      token = Strings.clean(request.getHeader(headerName));
    }

    if (token == null) {
      return null;
    }

    try {
      Jws<Claims> jws = Jwts.parser().setSigningKey(signingKey).parseClaimsJws(token);

      // signature is valid, now let's ensure it hasn't been submitted before:

      String id = jws.getBody().getId();

      String usedNonce = null;

      Cache.ValueWrapper wrapper = nonceCache.get(id);
      if (wrapper != null) {
        Object val = wrapper.get();
        if (val != null) {
          usedNonce = val.toString();
        }
      }

      if (usedNonce == null) {
        // CSRF token hasn't been used yet, mark it as used:
        nonceCache.put(id, token);

        return new DefaultCsrfToken(headerName, parameterName, token);
      }
    } catch (Exception e) {
      log.debug(
          "CSRF token is invalid (this is likely to happen and not necessarily an error condition).",
          e);
    }

    return null;
  }
  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder(128);
    for (Criterion c : criterionEntries) {
      if (sb.length() > 0) {
        sb.append(" and ");
      }
      sb.append(c);
    }

    if (!orderEntries.isEmpty()) {
      if (sb.length() > 0) {
        sb.append(" ");
      }
      sb.append("order by ").append(Strings.collectionToDelimitedString(orderEntries, ", "));
    }

    if (offset != null) {
      if (sb.length() > 0) {
        sb.append(" ");
      }
      sb.append("offset ").append(offset);
    }

    if (limit != null) {
      if (sb.length() > 0) {
        sb.append(" ");
      }
      sb.append("limit ").append(limit);
    }

    if (!options.isEmpty() && options instanceof Expandable) {
      Expandable expandable = (Expandable) options;
      if (sb.length() > 0) {
        sb.append(" ");
      }
      sb.append("expand ")
          .append(Strings.collectionToDelimitedString(expandable.getExpansions(), ", "));
    }

    return sb.toString();
  }
Пример #5
0
 /**
  * Parse the given, comma-separated string into a list of {@code MimeType} objects.
  *
  * @param mimeTypes the string to parse
  * @return the list of mime types
  * @throws IllegalArgumentException if the string cannot be parsed
  */
 public static List<MimeType> parseMimeTypes(String mimeTypes) {
   if (!Strings.hasLength(mimeTypes)) {
     return Collections.emptyList();
   }
   String[] tokens = mimeTypes.split(",\\s*");
   List<MimeType> result = new ArrayList<MimeType>(tokens.length);
   for (String token : tokens) {
     result.add(parseMimeType(token));
   }
   return result;
 }
Пример #6
0
 /**
  * Return the {@link ConfigFactory} implementation class to use, either the default {@link
  * com.stormpath.sdk.servlet.config.impl.DefaultConfigFactory} or a custom class if specified.
  *
  * @param servletContext current servlet context
  * @return the ConfigFactory implementation class to use
  * @see #CONFIG_FACTORY_CLASS_PARAM_NAME
  * @see com.stormpath.sdk.servlet.config.impl.DefaultConfigFactory
  */
 protected Class<?> determineConfigFactoryClass(ServletContext servletContext) {
   String className = servletContext.getInitParameter(CONFIG_FACTORY_CLASS_PARAM_NAME);
   className = Strings.trimWhitespace(className);
   if (className != null) {
     try {
       return Classes.forName(className);
     } catch (UnknownClassException ex) {
       throw new IllegalStateException(
           "Failed to load custom ConfigFactory class [" + className + "]", ex);
     }
   } else {
     return DefaultConfigFactory.class;
   }
 }
  private String getJwtResponse(Object httpRequestObject) {
    String jwtResponse;

    if (HttpRequest.class.isAssignableFrom(httpRequestObject.getClass())) {

      HttpRequest httpRequest = (HttpRequest) httpRequestObject;

      Assert.isTrue(
          httpRequest.getMethod() == HttpMethod.GET, "Only Http GET method is supported.");

      jwtResponse = httpRequest.getParameter(JWT_RESPONSE);

    } else {
      // This must never happen, if the object request is of HttpServletRequest type the
      // HTTP_SERVLET_REQUEST_WRAPPER_CLASS
      // must be already loaded and therefore cannot be null.
      if (HTTP_SERVLET_REQUEST_WRAPPER_CLASS == null) {
        throw new RuntimeException(
            "DefaultHttpServletRequestWrapper not loaded error occurred while handling httpRequest of type: "
                + httpRequestObject.getClass().getName());
      }

      Constructor<? extends HttpServletRequestWrapper> ctor =
          Classes.getConstructor(HTTP_SERVLET_REQUEST_WRAPPER_CLASS, Object.class);

      HttpServletRequestWrapper httpServletRequestWrapper =
          Classes.instantiate(ctor, httpRequestObject);
      HttpMethod method = HttpMethod.fromName(httpServletRequestWrapper.getMethod());
      Assert.isTrue(HttpMethod.GET == method, "Only Http GET method is supported.");

      jwtResponse = httpServletRequestWrapper.getParameter(JWT_RESPONSE);
    }

    if (!Strings.hasText(jwtResponse)) {
      throw new InvalidJwtException(InvalidJwtException.JWT_REQUIRED_ERROR);
    }
    return jwtResponse;
  }
  @Override
  public AccountResult getAccountResult() {

    JwtWrapper jwtWrapper = new JwtWrapper(jwtResponse);

    Map jsonPayload = jwtWrapper.getJsonPayloadAsMap();

    String apiKeyId;

    Map jsonHeader = jwtWrapper.getJsonHeaderAsMap();
    apiKeyId = getRequiredValue(jsonHeader, KEY_ID);

    getJwtSignatureValidator(apiKeyId).validate(jwtWrapper);

    Number expire = getRequiredValue(jsonPayload, Claims.EXPIRATION);

    verifyJwtIsNotExpired(expire.longValue());

    String issuer = getRequiredValue(jsonPayload, Claims.ISSUER);

    // JSDK-261: Enable Java SDK to handle new ID Site error callbacks
    // We are processing the error after the token has been properly validated
    if (isError(jsonPayload)) {
      throw new IDSiteRuntimeException(constructError(jsonPayload, jsonHeader));
    }

    String responseNonce = getRequiredValue(jsonPayload, RESPONSE_ID);

    if (nonceStore.hasNonce(responseNonce)) {
      throw new InvalidJwtException(InvalidJwtException.ALREADY_USED_JWT_ERROR);
    }

    nonceStore.putNonce(responseNonce);

    // the 'sub' field can be null if calling /sso/logout when the subject is already logged out:
    String accountHref = getOptionalValue(jsonPayload, Claims.SUBJECT);
    boolean accountHrefPresent = Strings.hasText(accountHref);
    // but this is only legal during the logout scenario, so assert this:
    IdSiteResultStatus resultStatus =
        IdSiteResultStatus.valueOf((String) getRequiredValue(jsonPayload, STATUS));
    if (!accountHrefPresent && !IdSiteResultStatus.LOGOUT.equals(resultStatus)) {
      throw new InvalidJwtException(InvalidJwtException.JWT_RESPONSE_MISSING_PARAMETER_ERROR);
    }

    Boolean isNewAccount = getRequiredValue(jsonPayload, IS_NEW_SUBJECT);
    String state = getOptionalValue(jsonPayload, STATE);

    Map<String, Object> properties = new LinkedHashMap<String, Object>();
    properties.put(DefaultAccountResult.NEW_ACCOUNT.getName(), isNewAccount);
    properties.put(DefaultAccountResult.STATE.getName(), state);

    if (accountHrefPresent) {
      Map<String, Object> account = new HashMap<String, Object>();
      account.put(DefaultAccountResult.HREF_PROP_NAME, accountHref);
      properties.put(DefaultAccountResult.ACCOUNT.getName(), account);
    }

    AccountResult accountResult = new DefaultAccountResult(dataStore, properties);

    // @since 1.0.RC7.3
    if (this.resultListeners.size() > 0) {
      dispatchResponseStatus(resultStatus, properties);
    }

    return accountResult;
  }