类io.jsonwebtoken.lang.Assert源码实例Demo

下面列出了怎么用io.jsonwebtoken.lang.Assert的API类实例代码及写法,或者点击链接到github查看源代码。

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.notNull(authentication, "No authentication data provided");

    Object principal = authentication.getPrincipal();
    if (!(principal instanceof UserPrincipal)) {
        throw new BadCredentialsException("Authentication Failed. Bad user principal.");
    }

    UserPrincipal userPrincipal = (UserPrincipal) principal;
    if (userPrincipal.getType() == UserPrincipal.Type.USER_NAME) {
        String username = userPrincipal.getValue();
        String password = (String) authentication.getCredentials();
        return authenticateByUsernameAndPassword(userPrincipal, username, password);
    } else {
        String publicId = userPrincipal.getValue();
        return authenticateByPublicId(userPrincipal, (long)1);
    }
}
 
源代码2 项目: lams   文件: MacProvider.java
/**
 * Generates a new secure-random secret key of a length suitable for creating and verifying HMAC signatures
 * according to the specified {@code SignatureAlgorithm} using the specified SecureRandom number generator.  This
 * implementation returns secure-random key sizes as follows:
 *
 * <table> <caption>Key Sizes</caption> <thead> <tr> <th>Signature Algorithm</th> <th>Generated Key Size</th> </tr> </thead> <tbody> <tr>
 * <td>HS256</td> <td>256 bits (32 bytes)</td> </tr> <tr> <td>HS384</td> <td>384 bits (48 bytes)</td> </tr> <tr>
 * <td>HS512</td> <td>512 bits (64 bytes)</td> </tr> </tbody> </table>
 *
 * @param alg    the signature algorithm that will be used with the generated key
 * @param random the secure random number generator used during key generation
 * @return a new secure-random secret key of a length suitable for creating and verifying HMAC signatures according
 * to the specified {@code SignatureAlgorithm} using the specified SecureRandom number generator.
 * @see #generateKey()
 * @see #generateKey(SignatureAlgorithm)
 * @since 0.5
 */
public static SecretKey generateKey(SignatureAlgorithm alg, SecureRandom random) {

    Assert.isTrue(alg.isHmac(), "SignatureAlgorithm argument must represent an HMAC algorithm.");

    byte[] bytes;

    switch (alg) {
        case HS256:
            bytes = new byte[32];
            break;
        case HS384:
            bytes = new byte[48];
            break;
        default:
            bytes = new byte[64];
    }

    random.nextBytes(bytes);

    return new SecretKeySpec(bytes, alg.getJcaName());
}
 
源代码3 项目: lams   文件: DefaultSignatureValidatorFactory.java
@Override
public SignatureValidator createSignatureValidator(SignatureAlgorithm alg, Key key) {
    Assert.notNull(alg, "SignatureAlgorithm cannot be null.");
    Assert.notNull(key, "Signing Key cannot be null.");

    switch (alg) {
        case HS256:
        case HS384:
        case HS512:
            return new MacValidator(alg, key);
        case RS256:
        case RS384:
        case RS512:
        case PS256:
        case PS384:
        case PS512:
            return new RsaSignatureValidator(alg, key);
        case ES256:
        case ES384:
        case ES512:
            return new EllipticCurveSignatureValidator(alg, key);
        default:
            throw new IllegalArgumentException("The '" + alg.name() + "' algorithm cannot be used for signing.");
    }
}
 
源代码4 项目: lams   文件: DefaultSignerFactory.java
@Override
public Signer createSigner(SignatureAlgorithm alg, Key key) {
    Assert.notNull(alg, "SignatureAlgorithm cannot be null.");
    Assert.notNull(key, "Signing Key cannot be null.");

    switch (alg) {
        case HS256:
        case HS384:
        case HS512:
            return new MacSigner(alg, key);
        case RS256:
        case RS384:
        case RS512:
        case PS256:
        case PS384:
        case PS512:
            return new RsaSigner(alg, key);
        case ES256:
        case ES384:
        case ES512:
            return new EllipticCurveSigner(alg, key);
        default:
            throw new IllegalArgumentException("The '" + alg.name() + "' algorithm cannot be used for signing.");
    }
}
 
源代码5 项目: jjwt   文件: EllipticCurveProvider.java
/**
 * 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);
    }
}
 
源代码6 项目: lams   文件: DefaultJwtBuilder.java
@Override
public JwtBuilder claim(String name, Object value) {
    Assert.hasText(name, "Claim property name cannot be null or empty.");
    if (this.claims == null) {
        if (value != null) {
            ensureClaims().put(name, value);
        }
    } else {
        if (value == null) {
            this.claims.remove(name);
        } else {
            this.claims.put(name, value);
        }
    }

    return this;
}
 
源代码7 项目: juiser   文件: ForwardedUserFilter.java
public ForwardedUserFilter(String headerName,
                           Function<HttpServletRequest, User> userFactory,
                           Collection<String> requestAttributeNames) {
    Assert.hasText(headerName, "headerName cannot be null or empty.");
    Assert.notNull(userFactory, "userFactory function cannot be null.");

    this.headerName = headerName;
    this.userFactory = userFactory;

    //always ensure that the fully qualified interface name is accessible:
    LinkedHashSet<String> set = new LinkedHashSet<>();
    set.add(User.class.getName());
    if (!Collections.isEmpty(requestAttributeNames)) {
        set.addAll(requestAttributeNames);
    }
    this.requestAttributeNames = set;
}
 
源代码8 项目: jjwt   文件: RsaSignatureValidator.java
@Override
public boolean isValid(byte[] data, byte[] signature) {
    if (key instanceof PublicKey) {
        Signature sig = createSignatureInstance();
        PublicKey publicKey = (PublicKey) key;
        try {
            return doVerify(sig, publicKey, data, signature);
        } catch (Exception e) {
            String msg = "Unable to verify RSA signature using configured PublicKey. " + e.getMessage();
            throw new SignatureException(msg, e);
        }
    } else {
        Assert.notNull(this.SIGNER, "RSA Signer instance cannot be null.  This is a bug.  Please report it.");
        byte[] computed = this.SIGNER.sign(data);
        return MessageDigest.isEqual(computed, signature);
    }
}
 
源代码9 项目: jjwt   文件: RsaProvider.java
/**
 * Generates a new RSA secure-randomly key pair suitable for the specified SignatureAlgorithm using JJWT's
 * default {@link SignatureProvider#DEFAULT_SECURE_RANDOM SecureRandom instance}.  This is a convenience method
 * that immediately delegates to {@link #generateKeyPair(int)} based on the relevant key size for the specified
 * algorithm.
 *
 * @param alg the signature algorithm to inspect to determine a size in bits.
 * @return a new RSA secure-random key pair of the specified size.
 * @see #generateKeyPair()
 * @see #generateKeyPair(int, SecureRandom)
 * @see #generateKeyPair(String, int, SecureRandom)
 * @since 0.10.0
 */
@SuppressWarnings("unused") //used by io.jsonwebtoken.security.Keys
public static KeyPair generateKeyPair(SignatureAlgorithm alg) {
    Assert.isTrue(alg.isRsa(), "Only RSA algorithms are supported by this method.");
    int keySizeInBits = 4096;
    switch (alg) {
        case RS256:
        case PS256:
            keySizeInBits = 2048;
            break;
        case RS384:
        case PS384:
            keySizeInBits = 3072;
            break;
    }
    return generateKeyPair(keySizeInBits, DEFAULT_SECURE_RANDOM);
}
 
源代码10 项目: jjwt   文件: DefaultSignerFactory.java
@Override
public Signer createSigner(SignatureAlgorithm alg, Key key) {
    Assert.notNull(alg, "SignatureAlgorithm cannot be null.");
    Assert.notNull(key, "Signing Key cannot be null.");

    switch (alg) {
        case HS256:
        case HS384:
        case HS512:
            return new MacSigner(alg, key);
        case RS256:
        case RS384:
        case RS512:
        case PS256:
        case PS384:
        case PS512:
            return new RsaSigner(alg, key);
        case ES256:
        case ES384:
        case ES512:
            return new EllipticCurveSigner(alg, key);
        default:
            throw new IllegalArgumentException("The '" + alg.name() + "' algorithm cannot be used for signing.");
    }
}
 
源代码11 项目: lams   文件: SigningKeyResolverAdapter.java
@Override
public Key resolveSigningKey(JwsHeader header, Claims claims) {
    SignatureAlgorithm alg = SignatureAlgorithm.forName(header.getAlgorithm());
    Assert.isTrue(alg.isHmac(), "The default resolveSigningKey(JwsHeader, Claims) implementation cannot be " +
                                "used for asymmetric key algorithms (RSA, Elliptic Curve).  " +
                                "Override the resolveSigningKey(JwsHeader, Claims) method instead and return a " +
                                "Key instance appropriate for the " + alg.name() + " algorithm.");
    byte[] keyBytes = resolveSigningKeyBytes(header, claims);
    return new SecretKeySpec(keyBytes, alg.getJcaName());
}
 
源代码12 项目: lams   文件: SigningKeyResolverAdapter.java
@Override
public Key resolveSigningKey(JwsHeader header, String plaintext) {
    SignatureAlgorithm alg = SignatureAlgorithm.forName(header.getAlgorithm());
    Assert.isTrue(alg.isHmac(), "The default resolveSigningKey(JwsHeader, String) implementation cannot be " +
                                "used for asymmetric key algorithms (RSA, Elliptic Curve).  " +
                                "Override the resolveSigningKey(JwsHeader, String) method instead and return a " +
                                "Key instance appropriate for the " + alg.name() + " algorithm.");
    byte[] keyBytes = resolveSigningKeyBytes(header, plaintext);
    return new SecretKeySpec(keyBytes, alg.getJcaName());
}
 
源代码13 项目: jjwt   文件: DefaultJwtBuilder.java
@Deprecated // remove before 1.0 - call the serializer and base64UrlEncoder directly
protected String base64UrlEncode(Object o, String errMsg) {
    Assert.isInstanceOf(Map.class, o, "object argument must be a map.");
    Map m = (Map)o;
    byte[] bytes;
    try {
        bytes = toJson(m);
    } catch (SerializationException e) {
        throw new IllegalStateException(errMsg, e);
    }

    return base64UrlEncoder.encode(bytes);
}
 
源代码14 项目: lams   文件: DefaultJwtParser.java
@Override
public JwtParser require(String claimName, Object value) {
    Assert.hasText(claimName, "claim name cannot be null or empty.");
    Assert.notNull(value, "The value cannot be null for claim name: " + claimName);
    expectedClaims.put(claimName, value);
    return this;
}
 
源代码15 项目: jjwt   文件: DefaultJwtBuilder.java
@SuppressWarnings("unchecked")
@Deprecated //remove before 1.0 - call the serializer directly
protected byte[] toJson(Object object) throws SerializationException {
    Assert.isInstanceOf(Map.class, object, "object argument must be a map.");
    Map m = (Map)object;
    return serializer.serialize(m);
}
 
源代码16 项目: lams   文件: AbstractCompressionCodec.java
/**
 * Asserts the compressed bytes is not null and calls {@link #doDecompress(byte[]) doDecompress}
 *
 * @param compressed compressed bytes
 * @return decompressed bytes
 * @throws CompressionException if {@link #doDecompress(byte[]) doDecompress} throws an IOException
 */
@Override
public final byte[] decompress(byte[] compressed) {
    Assert.notNull(compressed, "compressed bytes cannot be null.");

    try {
        return doDecompress(compressed);
    } catch (IOException e) {
        throw new CompressionException("Unable to decompress bytes.", e);
    }
}
 
源代码17 项目: lams   文件: DefaultJwtBuilder.java
@Override
public JwtBuilder signWith(SignatureAlgorithm alg, byte[] secretKey) {
    Assert.notNull(alg, "SignatureAlgorithm cannot be null.");
    Assert.notEmpty(secretKey, "secret key byte array cannot be null or empty.");
    Assert.isTrue(alg.isHmac(), "Key bytes may only be specified for HMAC signatures.  If using RSA or Elliptic Curve, use the signWith(SignatureAlgorithm, Key) method instead.");
    this.algorithm = alg;
    this.keyBytes = secretKey;
    return this;
}
 
源代码18 项目: lams   文件: DefaultJwtBuilder.java
@Override
public JwtBuilder signWith(SignatureAlgorithm alg, String base64EncodedSecretKey) {
    Assert.hasText(base64EncodedSecretKey, "base64-encoded secret key cannot be null or empty.");
    Assert.isTrue(alg.isHmac(), "Base64-encoded key bytes may only be specified for HMAC signatures.  If using RSA or Elliptic Curve, use the signWith(SignatureAlgorithm, Key) method instead.");
    byte[] bytes = TextCodec.BASE64.decode(base64EncodedSecretKey);
    return signWith(alg, bytes);
}
 
源代码19 项目: jjwt   文件: AbstractCompressionCodec.java
/**
 * Asserts the compressed bytes is not null and calls {@link #doDecompress(byte[]) doDecompress}
 *
 * @param compressed compressed bytes
 * @return decompressed bytes
 * @throws CompressionException if {@link #doDecompress(byte[]) doDecompress} throws an IOException
 */
@Override
public final byte[] decompress(byte[] compressed) {
    Assert.notNull(compressed, "compressed bytes cannot be null.");

    try {
        return doDecompress(compressed);
    } catch (IOException e) {
        throw new CompressionException("Unable to decompress bytes.", e);
    }
}
 
源代码20 项目: juiser   文件: JwsToUserDetailsConverter.java
public JwsToUserDetailsConverter(Function<String, Claims> claimsExtractor,
                                 Function<Claims, User> claimsUserFactory,
                                 Function<Claims, Collection<? extends GrantedAuthority>> authoritiesResolver) {
    Assert.notNull(claimsExtractor, "claimsExtractor cannot be null.");
    Assert.notNull(claimsUserFactory, "claimsUserFactory cannot be null.");
    this.claimsExtractor = claimsExtractor;
    this.claimsUserFactory = claimsUserFactory;
    this.authoritiesResolver = authoritiesResolver;
}
 
源代码21 项目: jjwt   文件: DefaultJwtParser.java
@Override
public JwtParser require(String claimName, Object value) {
    Assert.hasText(claimName, "claim name cannot be null or empty.");
    Assert.notNull(value, "The value cannot be null for claim name: " + claimName);
    expectedClaims.put(claimName, value);
    return this;
}
 
源代码22 项目: juiser   文件: ImmutablePhone.java
public ImmutablePhone(String number, String name, String description, boolean verified) {
    Assert.hasText(number, "number argument cannot be null or empty.");
    this.number = number;
    this.digitString = digitsOnly(number);
    this.name = name;
    this.description = description;
    this.verified = verified;
}
 
源代码23 项目: juiser   文件: JwsClaimsExtractor.java
public JwsClaimsExtractor(byte[] hmacSigningKeyBytes) {
    Assert.isTrue(hmacSigningKeyBytes != null && hmacSigningKeyBytes.length > 0,
        "hmacSigningKeyByte array argument cannot be null or empty.");
    this.signingKeyBytes = hmacSigningKeyBytes;
    this.signingKey = null;
    this.signingKeyResolver = null;
}
 
源代码24 项目: juiser   文件: ConfigJwkResolver.java
static SignatureAlgorithm getAlgorithm(byte[] hmacSigningKeyBytes) {
    Assert.isTrue(hmacSigningKeyBytes != null && hmacSigningKeyBytes.length > 0,
        "hmacSigningBytes cannot be null or empty.");
    if (hmacSigningKeyBytes.length >= 64) {
        return SignatureAlgorithm.HS512;
    } else if (hmacSigningKeyBytes.length >= 48) {
        return SignatureAlgorithm.HS384;
    } else { //<= 32
        return SignatureAlgorithm.HS256;
    }
}
 
public CloudFoundryAppScheduler(SchedulerClient client, CloudFoundryOperations operations,
		CloudFoundryConnectionProperties properties, CloudFoundryTaskLauncher taskLauncher,
		CloudFoundrySchedulerProperties schedulerProperties) {
	Assert.notNull(client, "client must not be null");
	Assert.notNull(operations, "operations must not be null");
	Assert.notNull(properties, "properties must not be null");
	Assert.notNull(taskLauncher, "taskLauncher must not be null");
	Assert.notNull(schedulerProperties, "schedulerProperties must not be null");

	this.client = client;
	this.operations = operations;
	this.properties = properties;
	this.taskLauncher = taskLauncher;
	this.schedulerProperties = schedulerProperties;
}
 
public CloudFoundryTaskPlatformFactory build() {
	Assert.notNull(platformProperties, "'platformProperties' is required.");
	Assert.notNull(platformTokenProvider, "'platformTokenProvider' is required.");
	Assert.notNull(connectionContextProvider, "'connectionContextProvider' is required.");
	Assert.notNull(cloudFoundryClientProvider, "'cloudFoundryClientProvider' is required.");

	return new CloudFoundryTaskPlatformFactory(
			platformProperties,
			platformTokenProvider,
			connectionContextProvider,
			cloudFoundryClientProvider,
			cloudFoundrySchedulerClientProvider);
}
 
源代码27 项目: jjwt   文件: Services.java
/**
 * Loads the first available implementation the given SPI class from the classpath. Uses the {@link ServiceLoader}
 * to find implementations. When multiple implementations are available it will return the first one that it
 * encounters. There is no guarantee with regard to ordering.
 *
 * @param spi The class of the Service Provider Interface
 * @param <T> The type of the SPI
 * @return A new instance of the service.
 * @throws UnavailableImplementationException When no implementation the SPI is available on the classpath.
 */
public static <T> T loadFirst(Class<T> spi) {
    Assert.notNull(spi, "Parameter 'spi' must not be null.");

    for (ClassLoaderAccessor classLoaderAccessor : CLASS_LOADER_ACCESSORS) {
        T result = loadFirst(spi, classLoaderAccessor.getClassLoader());
        if (result != null) {
            return result;
        }
    }
    throw new UnavailableImplementationException(spi);
}
 
源代码28 项目: jjwt   文件: DefaultCompressionCodecResolver.java
private CompressionCodec byName(String name) {
    Assert.hasText(name, "'name' must not be empty");

    CompressionCodec codec = codecs.get(name.toUpperCase());
    if (codec == null) {
        throw new CompressionException(String.format(MISSING_COMPRESSION_MESSAGE, name));
    }

    return codec;
}
 
源代码29 项目: jjwt   文件: GsonSerializer.java
@Override
public byte[] serialize(T t) throws SerializationException {
    Assert.notNull(t, "Object to serialize cannot be null.");
    try {
        return writeValueAsBytes(t);
    } catch (Exception e) {
        String msg = "Unable to serialize object: " + e.getMessage();
        throw new SerializationException(msg, e);
    }
}
 
源代码30 项目: jjwt   文件: JacksonSerializer.java
@Override
public byte[] serialize(T t) throws SerializationException {
    Assert.notNull(t, "Object to serialize cannot be null.");
    try {
        return writeValueAsBytes(t);
    } catch (JsonProcessingException e) {
        String msg = "Unable to serialize object: " + e.getMessage();
        throw new SerializationException(msg, e);
    }
}
 
 类所在包