io.jsonwebtoken.lang.Strings Java Examples

The following examples show how to use io.jsonwebtoken.lang.Strings. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DefaultCompressionCodecResolver.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public CompressionCodec resolveCompressionCodec(Header header) {
    String cmpAlg = getAlgorithmFromHeader(header);

    final boolean hasCompressionAlgorithm = Strings.hasText(cmpAlg);

    if (!hasCompressionAlgorithm) {
        return null;
    }
    if (CompressionCodecs.DEFLATE.getAlgorithmName().equalsIgnoreCase(cmpAlg)) {
        return CompressionCodecs.DEFLATE;
    }
    if (CompressionCodecs.GZIP.getAlgorithmName().equalsIgnoreCase(cmpAlg)) {
        return CompressionCodecs.GZIP;
    }

    throw new CompressionException("Unsupported compression algorithm '" + cmpAlg + "'");
}
 
Example #2
Source File: EllipticCurveProvider.java    From jjwt with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a new secure-random key pair of sufficient strength for the specified Elliptic Curve {@link
 * SignatureAlgorithm} (must be one of {@code ES256}, {@code ES384} or {@code ES512}) using the specified {@link
 * SecureRandom} random number generator via the specified JCA provider and algorithm name.
 *
 * @param jcaAlgorithmName the JCA name of the algorithm to use for key pair generation, for example, {@code
 *                         ECDSA}.
 * @param jcaProviderName  the JCA provider name of the algorithm implementation (for example {@code "BC"} for
 *                         BouncyCastle) or {@code null} if the default provider should be used.
 * @param alg              alg the algorithm indicating strength, must be one of {@code ES256}, {@code ES384} or
 *                         {@code ES512}
 * @param random           the SecureRandom generator to use during key generation.
 * @return a new secure-randomly generated key pair of sufficient strength for the specified Elliptic Curve {@link
 * SignatureAlgorithm} (must be one of {@code ES256}, {@code ES384} or {@code ES512}) using the specified {@link
 * SecureRandom} random number generator via the specified JCA provider and algorithm name.
 * @see #generateKeyPair()
 * @see #generateKeyPair(SignatureAlgorithm)
 * @see #generateKeyPair(SignatureAlgorithm, SecureRandom)
 */
public static KeyPair generateKeyPair(String jcaAlgorithmName, String jcaProviderName, SignatureAlgorithm alg,
                                      SecureRandom random) {
    Assert.notNull(alg, "SignatureAlgorithm argument cannot be null.");
    Assert.isTrue(alg.isEllipticCurve(), "SignatureAlgorithm argument must represent an Elliptic Curve algorithm.");
    try {
        KeyPairGenerator g;

        if (Strings.hasText(jcaProviderName)) {
            g = KeyPairGenerator.getInstance(jcaAlgorithmName, jcaProviderName);
        } else {
            g = KeyPairGenerator.getInstance(jcaAlgorithmName);
        }

        String paramSpecCurveName = EC_CURVE_NAMES.get(alg);
        ECGenParameterSpec spec = new ECGenParameterSpec(paramSpecCurveName);
        g.initialize(spec, random);
        return g.generateKeyPair();
    } catch (Exception e) {
        throw new IllegalStateException("Unable to generate Elliptic Curve KeyPair: " + e.getMessage(), e);
    }
}
 
Example #3
Source File: OrgJsonSerializer.java    From jjwt with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("WeakerAccess") //for testing
protected byte[] toBytes(Object o) {
    String s;
    // https://github.com/jwtk/jjwt/issues/380 for Android compatibility (Android doesn't have org.json.JSONWriter):
    // This instanceof check is a sneaky (hacky?) heuristic: A JwtBuilder only ever provides Map<String,Object>
    // instances to its serializer instances, so by the time this method is invoked, 'o' will always be a
    // JSONObject.
    //
    // This is sufficient for all JJWT-supported scenarios on Android since Android users shouldn't ever use
    // JJWT's internal Serializer implementation for general JSON serialization.  That is, its intended use
    // is within the context of JwtBuilder execution and not for application use outside of that.
    if (o instanceof JSONObject) {
        s = o.toString();
    } else {
        // we still call JSONWriter for all other values 'just in case', and this works for all valid JSON values
        // This would fail on Android unless they include the newer org.json dependency and ignore Android's.
        s = Classes.invokeStatic(JSON_WRITER_CLASS_NAME, "valueToString", VALUE_TO_STRING_ARG_TYPES, o);
    }
    return s.getBytes(Strings.UTF_8);
}
 
Example #4
Source File: OrgJsonDeserializer.java    From jjwt with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Object deserialize(byte[] bytes) throws DeserializationException {

    Assert.notNull(bytes, "JSON byte array cannot be null");

    if (bytes.length == 0) {
        throw new DeserializationException("Invalid JSON: zero length byte array.");
    }

    try {
        String s = new String(bytes, Strings.UTF_8);
        return parse(s);
    } catch (Exception e) {
        String msg = "Invalid JSON: " + e.getMessage();
        throw new DeserializationException(msg, e);
    }
}
 
Example #5
Source File: DefaultJwtBuilder.java    From jjwt with Apache License 2.0 5 votes vote down vote up
@Override
public JwtBuilder setId(String jti) {
    if (Strings.hasText(jti)) {
        ensureClaims().setId(jti);
    } else {
        if (this.claims != null) {
            claims.setId(jti);
        }
    }
    return this;
}
 
Example #6
Source File: DefaultHeader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public String getCompressionAlgorithm() {
    String alg = getString(COMPRESSION_ALGORITHM);
    if (!Strings.hasText(alg)) {
        alg = getString(DEPRECATED_COMPRESSION_ALGORITHM);
    }
    return alg;
}
 
Example #7
Source File: DefaultJwtBuilder.java    From jjwt with Apache License 2.0 5 votes vote down vote up
@Override
public JwtBuilder setAudience(String aud) {
    if (Strings.hasText(aud)) {
        ensureClaims().setAudience(aud);
    } else {
        if (this.claims != null) {
            claims.setAudience(aud);
        }
    }
    return this;
}
 
Example #8
Source File: DefaultJwtBuilder.java    From jjwt with Apache License 2.0 5 votes vote down vote up
@Override
public JwtBuilder setSubject(String sub) {
    if (Strings.hasText(sub)) {
        ensureClaims().setSubject(sub);
    } else {
        if (this.claims != null) {
            claims.setSubject(sub);
        }
    }
    return this;
}
 
Example #9
Source File: DefaultJwtBuilder.java    From jjwt with Apache License 2.0 5 votes vote down vote up
@Override
public JwtBuilder setIssuer(String iss) {
    if (Strings.hasText(iss)) {
        ensureClaims().setIssuer(iss);
    } else {
        if (this.claims != null) {
            claims.setIssuer(iss);
        }
    }
    return this;
}
 
Example #10
Source File: DefaultCompressionCodecResolver.java    From jjwt with Apache License 2.0 5 votes vote down vote up
@Override
public CompressionCodec resolveCompressionCodec(Header header) {
    String cmpAlg = getAlgorithmFromHeader(header);

    final boolean hasCompressionAlgorithm = Strings.hasText(cmpAlg);

    if (!hasCompressionAlgorithm) {
        return null;
    }
    return byName(cmpAlg);
}
 
Example #11
Source File: DefaultJwtParser.java    From jjwt with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected Map<String, ?> readValue(String val) {
    try {
        byte[] bytes = val.getBytes(Strings.UTF_8);
        return deserializer.deserialize(bytes);
    } catch (DeserializationException e) {
        throw new MalformedJwtException("Unable to read JSON value: " + val, e);
    }
}
 
Example #12
Source File: DefaultHeader.java    From jjwt with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public String getCompressionAlgorithm() {
    String alg = getString(COMPRESSION_ALGORITHM);
    if (!Strings.hasText(alg)) {
        alg = getString(DEPRECATED_COMPRESSION_ALGORITHM);
    }
    return alg;
}
 
Example #13
Source File: GsonSerializer.java    From jjwt with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("WeakerAccess") //for testing
protected byte[] writeValueAsBytes(T t) {
    Object o;
    if (t instanceof byte[]) {
        o = Encoders.BASE64.encode((byte[]) t);
    } else if (t instanceof char[]) {
        o = new String((char[]) t);
    } else {
        o = t;
    }
    return this.gson.toJson(o).getBytes(Strings.UTF_8);
}
 
Example #14
Source File: ShiroJwtVerifyingFilter.java    From cassandra-reaper with Apache License 2.0 5 votes vote down vote up
private static Optional<String> getJwtUser(ServletRequest req) {
  String jwt = WebUtils.toHttp(req).getHeader("Authorization");
  if (null != jwt && jwt.startsWith("Bearer ")) {
    try {
      jwt = jwt.substring(jwt.indexOf(' ') + 1);
      Jws<Claims> claims = Jwts.parser().setSigningKey(ShiroJwtProvider.SIGNING_KEY).parseClaimsJws(jwt);
      String user = claims.getBody().getSubject();
      return Strings.hasText(user) ? Optional.of(user) : Optional.empty();
    } catch (JwtException | IllegalArgumentException e) {
      LOG.error("Failed validating JWT {} from {}", jwt, WebUtils.toHttp(req).getRemoteAddr());
      LOG.debug("exception", e);
    }
  }
  return Optional.empty();
}
 
Example #15
Source File: ModelUtil.java    From j360-dubbo-app-all with Apache License 2.0 5 votes vote down vote up
/**
 * 获取多个redis的keys
 * @param format
 * @param ids
 * @return
 */
public static String[] formatStrings(String format, List<Long> ids) {
    if (CollectionUtils.isEmpty(ids)) {
        return null;
    }
    List<String> formatList = ids.stream().map( s -> {
        return String.format(format, s);
    }).collect(Collectors.toList());
    return Strings.toStringArray(formatList);
}
 
Example #16
Source File: ConfigJwkResolver.java    From juiser with Apache License 2.0 5 votes vote down vote up
private Resource getResource(JwkConfig jwk) {
    if (jwk.isEnabled()) {
        final String value = jwk.getResource();
        if (Strings.hasText(value)) {
            try {
                return this.resourceLoader.getResource(value);
            } catch (Exception e) {
                String msg = "Unable to load juiser.header.jwt.key.resource [" + value + "].";
                throw new IllegalArgumentException(msg, e);
            }
        }
    }
    return null;
}
 
Example #17
Source File: StringClaimResolver.java    From juiser with Apache License 2.0 5 votes vote down vote up
@Override
protected String toTypedValue(Object v, Claims claims) {

    String value = String.valueOf(v);

    if (!Strings.hasText(value) || "null".equalsIgnoreCase(value)) {
        illegal(claims);
    }

    return value;
}
 
Example #18
Source File: JuiserSecurityAutoConfiguration.java    From juiser with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean(name = "juiserJwtDataExtractor")
public Function<Claims, Collection<String>> juiserGrantedAuthoritiesClaimResolver() {

    final SpringSecurityJwtConfig jwt = forwardedHeaderConfig().getJwt();

    String expression = jwt.getGrantedAuthoritiesExpression();

    if (!Strings.hasText(expression)) {
        expression = "['user']['groups']['items'].![get('name')]";
    }

    return new StringCollectionClaimResolver(new ClaimsExpressionEvaluator(expression), false);
}
 
Example #19
Source File: DefaultJwtBuilder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public JwtBuilder setId(String jti) {
    if (Strings.hasText(jti)) {
        ensureClaims().setId(jti);
    } else {
        if (this.claims != null) {
            claims.setId(jti);
        }
    }
    return this;
}
 
Example #20
Source File: DefaultJwtBuilder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public JwtBuilder setAudience(String aud) {
    if (Strings.hasText(aud)) {
        ensureClaims().setAudience(aud);
    } else {
        if (this.claims != null) {
            claims.setAudience(aud);
        }
    }
    return this;
}
 
Example #21
Source File: DefaultJwtBuilder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public JwtBuilder setSubject(String sub) {
    if (Strings.hasText(sub)) {
        ensureClaims().setSubject(sub);
    } else {
        if (this.claims != null) {
            claims.setSubject(sub);
        }
    }
    return this;
}
 
Example #22
Source File: DefaultJwtBuilder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public JwtBuilder setIssuer(String iss) {
    if (Strings.hasText(iss)) {
        ensureClaims().setIssuer(iss);
    } else {
        if (this.claims != null) {
            claims.setIssuer(iss);
        }
    }
    return this;
}
 
Example #23
Source File: GsonDeserializer.java    From jjwt with Apache License 2.0 4 votes vote down vote up
protected T readValue(byte[] bytes) throws IOException {
    return gson.fromJson(new String(bytes, Strings.UTF_8), returnType);
}
 
Example #24
Source File: ForwardedUserFilter.java    From juiser with Apache License 2.0 4 votes vote down vote up
public boolean isEnabled(HttpServletRequest request) throws ServletException {
    String headerValue = request.getHeader(headerName);
    return Strings.hasText(headerValue);
}