io.jsonwebtoken.lang.Assert Java Examples

The following examples show how to use io.jsonwebtoken.lang.Assert. 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: DefaultSignerFactory.java    From jjwt with Apache License 2.0 6 votes vote down vote up
@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.");
    }
}
 
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: DefaultJwtBuilder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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;
}
 
Example #4
Source File: ForwardedUserFilter.java    From juiser with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #5
Source File: RsaSignatureValidator.java    From jjwt with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #6
Source File: DefaultSignerFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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.");
    }
}
 
Example #7
Source File: DefaultSignatureValidatorFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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.");
    }
}
 
Example #8
Source File: MacProvider.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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());
}
 
Example #9
Source File: RestAuthenticationProvider.java    From IOT-Technical-Guide with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #10
Source File: RsaProvider.java    From jjwt with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #11
Source File: DefaultCompressionCodecResolver.java    From jjwt with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #12
Source File: SigningKeyResolverAdapter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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());
}
 
Example #13
Source File: DefaultJwtParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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;
}
 
Example #14
Source File: DefaultJwtParserBuilder.java    From jjwt with Apache License 2.0 5 votes vote down vote up
@Override
public JwtParserBuilder 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;
}
 
Example #15
Source File: JacksonSerializer.java    From jjwt with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example #16
Source File: DefaultJwtBuilder.java    From jjwt with Apache License 2.0 5 votes vote down vote up
@Override
public JwtBuilder signWith(Key key, SignatureAlgorithm alg) throws InvalidKeyException {
    Assert.notNull(key, "Key argument cannot be null.");
    Assert.notNull(alg, "SignatureAlgorithm cannot be null.");
    alg.assertValidSigningKey(key); //since 0.10.0 for https://github.com/jwtk/jjwt/issues/334
    this.algorithm = alg;
    this.key = key;
    return this;
}
 
Example #17
Source File: Services.java    From jjwt with Apache License 2.0 5 votes vote down vote up
/**
 * Loads and instantiates all service implementation of the given SPI class and returns them as a List.
 *
 * @param spi The class of the Service Provider Interface
 * @param <T> The type of the SPI
 * @return An unmodifiable list with an instance of all available implementations of the SPI. No guarantee is given
 * on the order of implementations, if more than one.
 */
public static <T> List<T> loadAll(Class<T> spi) {
    Assert.notNull(spi, "Parameter 'spi' must not be null.");

    for (ClassLoaderAccessor classLoaderAccessor : CLASS_LOADER_ACCESSORS) {
        List<T> implementations = loadAll(spi, classLoaderAccessor.getClassLoader());
        if (!implementations.isEmpty()) {
            return Collections.unmodifiableList(implementations);
        }
    }

    throw new UnavailableImplementationException(spi);
}
 
Example #18
Source File: DefaultJwtBuilder.java    From jjwt with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #19
Source File: AbstractCompressionCodec.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example #20
Source File: DefaultJwtBuilder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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;
}
 
Example #21
Source File: DefaultJwtBuilder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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);
}
 
Example #22
Source File: AbstractCompressionCodec.java    From jjwt with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example #23
Source File: JwsToUserDetailsConverter.java    From juiser with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #24
Source File: CloudFoundryAppScheduler.java    From spring-cloud-deployer-cloudfoundry with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #25
Source File: ConfigJwkResolver.java    From juiser with Apache License 2.0 5 votes vote down vote up
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;
    }
}
 
Example #26
Source File: DefaultJwtParser.java    From jjwt with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #27
Source File: CloudFoundryTaskPlatformFactory.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #28
Source File: JwsClaimsExtractor.java    From juiser with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #29
Source File: ImmutablePhone.java    From juiser with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #30
Source File: Services.java    From jjwt with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}