下面列出了怎么用io.jsonwebtoken.lang.Strings的API类实例代码及写法,或者点击链接到github查看源代码。
@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 + "'");
}
@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);
}
}
@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);
}
/**
* 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);
}
}
@SuppressWarnings("deprecation")
@Override
public String getCompressionAlgorithm() {
String alg = getString(COMPRESSION_ALGORITHM);
if (!Strings.hasText(alg)) {
alg = getString(DEPRECATED_COMPRESSION_ALGORITHM);
}
return alg;
}
@Override
public JwtBuilder setIssuer(String iss) {
if (Strings.hasText(iss)) {
ensureClaims().setIssuer(iss);
} else {
if (this.claims != null) {
claims.setIssuer(iss);
}
}
return this;
}
@Override
public JwtBuilder setSubject(String sub) {
if (Strings.hasText(sub)) {
ensureClaims().setSubject(sub);
} else {
if (this.claims != null) {
claims.setSubject(sub);
}
}
return this;
}
@Override
public JwtBuilder setAudience(String aud) {
if (Strings.hasText(aud)) {
ensureClaims().setAudience(aud);
} else {
if (this.claims != null) {
claims.setAudience(aud);
}
}
return this;
}
@Override
public JwtBuilder setId(String jti) {
if (Strings.hasText(jti)) {
ensureClaims().setId(jti);
} else {
if (this.claims != null) {
claims.setId(jti);
}
}
return this;
}
@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);
}
@Override
protected String toTypedValue(Object v, Claims claims) {
String value = String.valueOf(v);
if (!Strings.hasText(value) || "null".equalsIgnoreCase(value)) {
illegal(claims);
}
return value;
}
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;
}
/**
* 获取多个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);
}
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();
}
@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);
}
@SuppressWarnings("deprecation")
@Override
public String getCompressionAlgorithm() {
String alg = getString(COMPRESSION_ALGORITHM);
if (!Strings.hasText(alg)) {
alg = getString(DEPRECATED_COMPRESSION_ALGORITHM);
}
return alg;
}
@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);
}
}
@Override
public CompressionCodec resolveCompressionCodec(Header header) {
String cmpAlg = getAlgorithmFromHeader(header);
final boolean hasCompressionAlgorithm = Strings.hasText(cmpAlg);
if (!hasCompressionAlgorithm) {
return null;
}
return byName(cmpAlg);
}
@Override
public JwtBuilder setIssuer(String iss) {
if (Strings.hasText(iss)) {
ensureClaims().setIssuer(iss);
} else {
if (this.claims != null) {
claims.setIssuer(iss);
}
}
return this;
}
@Override
public JwtBuilder setSubject(String sub) {
if (Strings.hasText(sub)) {
ensureClaims().setSubject(sub);
} else {
if (this.claims != null) {
claims.setSubject(sub);
}
}
return this;
}
@Override
public JwtBuilder setAudience(String aud) {
if (Strings.hasText(aud)) {
ensureClaims().setAudience(aud);
} else {
if (this.claims != null) {
claims.setAudience(aud);
}
}
return this;
}
@Override
public JwtBuilder setId(String jti) {
if (Strings.hasText(jti)) {
ensureClaims().setId(jti);
} else {
if (this.claims != null) {
claims.setId(jti);
}
}
return this;
}
public boolean isEnabled(HttpServletRequest request) throws ServletException {
String headerValue = request.getHeader(headerName);
return Strings.hasText(headerValue);
}
protected T readValue(byte[] bytes) throws IOException {
return gson.fromJson(new String(bytes, Strings.UTF_8), returnType);
}