Java Code Examples for io.jsonwebtoken.lang.Strings

The following examples show how to use io.jsonwebtoken.lang.Strings. These examples are extracted from open source projects. 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
@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 Project: jjwt   Source File: OrgJsonDeserializer.java    License: 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 3
Source Project: jjwt   Source File: OrgJsonSerializer.java    License: 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 Project: jjwt   Source File: EllipticCurveProvider.java    License: 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 5
Source Project: lams   Source File: DefaultHeader.java    License: 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 6
Source Project: lams   Source File: DefaultJwtBuilder.java    License: 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 7
Source Project: lams   Source File: DefaultJwtBuilder.java    License: 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 8
Source Project: lams   Source File: DefaultJwtBuilder.java    License: 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 9
Source Project: lams   Source File: DefaultJwtBuilder.java    License: 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 10
Source Project: juiser   Source File: JuiserSecurityAutoConfiguration.java    License: 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 11
Source Project: juiser   Source File: StringClaimResolver.java    License: 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 12
Source Project: juiser   Source File: ConfigJwkResolver.java    License: 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 13
Source Project: j360-dubbo-app-all   Source File: ModelUtil.java    License: 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 14
Source Project: cassandra-reaper   Source File: ShiroJwtVerifyingFilter.java    License: 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 Project: jjwt   Source File: GsonSerializer.java    License: 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 16
Source Project: jjwt   Source File: DefaultHeader.java    License: 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 17
Source Project: jjwt   Source File: DefaultJwtParser.java    License: 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 18
Source Project: jjwt   Source File: DefaultCompressionCodecResolver.java    License: 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 19
Source Project: jjwt   Source File: DefaultJwtBuilder.java    License: 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 20
Source Project: jjwt   Source File: DefaultJwtBuilder.java    License: 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 21
Source Project: jjwt   Source File: DefaultJwtBuilder.java    License: 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 22
Source Project: jjwt   Source File: DefaultJwtBuilder.java    License: 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 23
Source Project: juiser   Source File: ForwardedUserFilter.java    License: 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);
}
 
Example 24
Source Project: jjwt   Source File: GsonDeserializer.java    License: 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);
}