Search in sources :

Example 31 with Algorithm

use of com.auth0.jwt.Algorithm in project auth0-java by auth0.

the class IdTokenVerifier method verify.

/**
 * Verifies a provided ID Token follows the <a href="https://openid.net/specs/openid-connect-core-1_0-final.html#IDTokenValidation">OIDC specification.</a>
 *
 * @param token                the ID Token to verify. Must not be null or empty.
 * @param nonce                the nonce expected on the ID token, which must match the nonce specified on the authorization request.
 *                             If null, no validation of the nonce will occur.
 * @param maxAuthenticationAge The maximum authentication age allowed, which specifies the allowable elapsed time in seconds
 *                             since the last time the end-user was actively authenticated. This must match the specified
 *                             {@code max_age} parameter specified on the authorization request. If null, no validation
 *                             of the {@code auth_time} claim will occur.
 * @throws IdTokenValidationException if:
 *                                    <ul>
 *                                        <li>The ID token is null</li>
 *                                        <li>The ID token's signing algorithm is not supported</li>
 *                                        <li>The ID token's signature is invalid</li>
 *                                        <li>Any of the ID token's claims are invalid</li>
 *                                    </ul>
 * @see IdTokenVerifier#verify(String)
 * @see IdTokenVerifier#verify(String, String)
 */
public void verify(String token, String nonce, Integer maxAuthenticationAge) throws IdTokenValidationException {
    if (isEmpty(token)) {
        throw new IdTokenValidationException("ID token is required but missing");
    }
    DecodedJWT decoded = this.signatureVerifier.verifySignature(token);
    if (isEmpty(decoded.getIssuer())) {
        throw new IdTokenValidationException("Issuer (iss) claim must be a string present in the ID token");
    }
    if (!decoded.getIssuer().equals(this.issuer)) {
        throw new IdTokenValidationException(String.format("Issuer (iss) claim mismatch in the ID token, expected \"%s\", found \"%s\"", this.issuer, decoded.getIssuer()));
    }
    if (isEmpty(decoded.getSubject())) {
        throw new IdTokenValidationException("Subject (sub) claim must be a string present in the ID token");
    }
    final List<String> audience = decoded.getAudience();
    if (audience == null) {
        throw new IdTokenValidationException("Audience (aud) claim must be a string or array of strings present in the ID token");
    }
    if (!audience.contains(this.audience)) {
        throw new IdTokenValidationException(String.format("Audience (aud) claim mismatch in the ID token; expected \"%s\" but found \"%s\"", this.audience, decoded.getAudience()));
    }
    // Org verification
    if (this.organization != null) {
        String orgClaim = decoded.getClaim("org_id").asString();
        if (isEmpty(orgClaim)) {
            throw new IdTokenValidationException("Organization Id (org_id) claim must be a string present in the ID token");
        }
        if (!this.organization.equals(orgClaim)) {
            throw new IdTokenValidationException(String.format("Organization (org_id) claim mismatch in the ID token; expected \"%s\" but found \"%s\"", this.organization, orgClaim));
        }
    }
    final Calendar cal = Calendar.getInstance();
    final Date now = this.clock != null ? this.clock : cal.getTime();
    final int clockSkew = this.leeway != null ? this.leeway : DEFAULT_LEEWAY;
    if (decoded.getExpiresAt() == null) {
        throw new IdTokenValidationException("Expiration Time (exp) claim must be a number present in the ID token");
    }
    cal.setTime(decoded.getExpiresAt());
    cal.add(Calendar.SECOND, clockSkew);
    Date expDate = cal.getTime();
    if (now.after(expDate)) {
        throw new IdTokenValidationException(String.format("Expiration Time (exp) claim error in the ID token; current time (%d) is after expiration time (%d)", now.getTime() / 1000, expDate.getTime() / 1000));
    }
    if (decoded.getIssuedAt() == null) {
        throw new IdTokenValidationException("Issued At (iat) claim must be a number present in the ID token");
    }
    cal.setTime(decoded.getIssuedAt());
    cal.add(Calendar.SECOND, -1 * clockSkew);
    if (nonce != null) {
        String nonceClaim = decoded.getClaim(NONCE_CLAIM).asString();
        if (isEmpty(nonceClaim)) {
            throw new IdTokenValidationException("Nonce (nonce) claim must be a string present in the ID token");
        }
        if (!nonce.equals(nonceClaim)) {
            throw new IdTokenValidationException(String.format("Nonce (nonce) claim mismatch in the ID token; expected \"%s\", found \"%s\"", nonce, nonceClaim));
        }
    }
    if (audience.size() > 1) {
        String azpClaim = decoded.getClaim(AZP_CLAIM).asString();
        if (isEmpty(azpClaim)) {
            throw new IdTokenValidationException("Authorized Party (azp) claim must be a string present in the ID token when Audience (aud) claim has multiple values");
        }
        if (!this.audience.equals(azpClaim)) {
            throw new IdTokenValidationException(String.format("Authorized Party (azp) claim mismatch in the ID token; expected \"%s\", found \"%s\"", this.audience, azpClaim));
        }
    }
    if (maxAuthenticationAge != null) {
        Date authTime = decoded.getClaim(AUTH_TIME_CLAIM).asDate();
        if (authTime == null) {
            throw new IdTokenValidationException("Authentication Time (auth_time) claim must be a number present in the ID token when Max Age (max_age) is specified");
        }
        cal.setTime(authTime);
        cal.add(Calendar.SECOND, maxAuthenticationAge);
        cal.add(Calendar.SECOND, clockSkew);
        Date authTimeDate = cal.getTime();
        if (now.after(authTimeDate)) {
            throw new IdTokenValidationException(String.format("Authentication Time (auth_time) claim in the ID token indicates that too much time has passed since the last end-user authentication. Current time (%d) is after last auth at (%d)", now.getTime() / 1000, authTimeDate.getTime() / 1000));
        }
    }
}
Also used : IdTokenValidationException(com.auth0.exception.IdTokenValidationException) Calendar(java.util.Calendar) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Date(java.util.Date)

Example 32 with Algorithm

use of com.auth0.jwt.Algorithm in project restheart by SoftInstigate.

the class JwtAuthenticationMechanism method init.

@InjectConfiguration
public void init(Map<String, Object> args) throws ConfigurationException {
    // get configuration arguments
    base64Encoded = argValue(args, "base64Encoded");
    algorithm = argValue(args, "algorithm");
    key = argValue(args, "key");
    usernameClaim = argValue(args, "usernameClaim");
    rolesClaim = argValue(args, "rolesClaim");
    fixedRoles = argValue(args, "fixedRoles");
    issuer = argValue(args, "issuer");
    audience = argValue(args, "audience");
    Algorithm _algorithm;
    try {
        _algorithm = getAlgorithm(algorithm, key);
    } catch (CertificateException | UnsupportedEncodingException ex) {
        throw new ConfigurationException("wrong JWT configuration, " + "cannot setup algorithm", ex);
    }
    Verification v = JWT.require(_algorithm);
    if (audience != null) {
        v.withAudience(audience);
    }
    if (issuer != null) {
        v.withIssuer(issuer);
    }
    if (rolesClaim != null && fixedRoles != null) {
        throw new ConfigurationException("wrong JWT configuration, " + "cannot set both 'rolesClaim' and 'fixedRoles'");
    }
    if (rolesClaim == null && fixedRoles == null) {
        throw new ConfigurationException("wrong JWT configuration, " + "need to set either 'rolesClaim' or 'fixedRoles'");
    }
    this.jwtVerifier = v.build();
}
Also used : ConfigurationException(org.restheart.ConfigurationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CertificateException(java.security.cert.CertificateException) Verification(com.auth0.jwt.interfaces.Verification) Algorithm(com.auth0.jwt.algorithms.Algorithm) InjectConfiguration(org.restheart.plugins.InjectConfiguration)

Example 33 with Algorithm

use of com.auth0.jwt.Algorithm in project CSKY by SHU-Silence.

the class UserServiceImpl method createToken.

private String createToken(User user) {
    UserVo userVo = new UserVo();
    BeanUtils.copyProperties(user, userVo);
    Algorithm algorithm = Algorithm.HMAC256(user.getPassword());
    Date nowDate = new Date();
    Date expireDate = new Date(System.currentTimeMillis() + 2 * 60 * 60 * 1000);
    return JWT.create().withIssuedAt(// 设置 载荷 生成签名的时间
    nowDate).withExpiresAt(// 设置 载荷 签名过期的时间
    expireDate).withAudience(JSON.toJSONString(userVo), user.getUsername()).sign(// 签名 Signature
    algorithm);
}
Also used : UserVo(shu.java.csky.vo.UserVo) Algorithm(com.auth0.jwt.algorithms.Algorithm) Date(java.util.Date)

Example 34 with Algorithm

use of com.auth0.jwt.Algorithm in project bookmark by FleyX.

the class JwtUtil method encode.

/**
 * Description: 生成一个jwt字符串
 *
 * @param map     data携带数据
 * @param secret  秘钥
 * @param timeOut 超时时间(单位s)
 * @return java.lang.String
 * @author fanxb
 * @date 2019/3/4 17:26
 */
public static String encode(Map<String, String> map, String secret, long timeOut) {
    Algorithm algorithm = Algorithm.HMAC256(secret);
    JWTCreator.Builder builder = JWT.create().withExpiresAt(new Date(System.currentTimeMillis() + timeOut));
    // 设置负载
    map.forEach(builder::withClaim);
    return builder.sign(algorithm);
}
Also used : JWTCreator(com.auth0.jwt.JWTCreator) Algorithm(com.auth0.jwt.algorithms.Algorithm) Date(java.util.Date)

Example 35 with Algorithm

use of com.auth0.jwt.Algorithm in project teamapps by teamapps-org.

the class MediaSoupV3TokenGenerator method generateJwtToken.

public static String generateJwtToken(String secret, MediaSoupV3ApiOperation operation, String streamUuid, Duration tokenValidityDuration) {
    if (secret == null) {
        return "";
    }
    try {
        Algorithm algorithm = Algorithm.HMAC512(secret);
        JWTCreator.Builder builder = JWT.create();
        if (operation != null) {
            builder = builder.withClaim("operation", operation.ordinal());
        }
        if (streamUuid != null) {
            builder = builder.withClaim("stream", streamUuid);
        }
        if (tokenValidityDuration != null) {
            builder = builder.withExpiresAt(new Date(Instant.now().plus(tokenValidityDuration).toEpochMilli()));
        }
        return builder.sign(algorithm);
    } catch (JWTCreationException exception) {
        throw new RuntimeException("Could not create auth token - this should never happen!");
    }
}
Also used : JWTCreator(com.auth0.jwt.JWTCreator) Algorithm(com.auth0.jwt.algorithms.Algorithm) Date(java.util.Date) JWTCreationException(com.auth0.jwt.exceptions.JWTCreationException)

Aggregations

Algorithm (com.auth0.jwt.algorithms.Algorithm)206 Test (org.junit.Test)160 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)90 JWTVerifier (com.auth0.jwt.JWTVerifier)79 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)79 ECDSAAlgorithmTest (com.auth0.jwt.algorithms.ECDSAAlgorithmTest)61 Date (java.util.Date)57 ECDSAKeyProvider (com.auth0.jwt.interfaces.ECDSAKeyProvider)51 RSAPublicKey (java.security.interfaces.RSAPublicKey)36 ECPublicKey (java.security.interfaces.ECPublicKey)34 RSAKeyProvider (com.auth0.jwt.interfaces.RSAKeyProvider)31 IOException (java.io.IOException)30 JWTCreator (com.auth0.jwt.JWTCreator)28 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)25 ECPrivateKey (java.security.interfaces.ECPrivateKey)23 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)21 HashMap (java.util.HashMap)17 UnsupportedEncodingException (java.io.UnsupportedEncodingException)16 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)15 JsonObject (com.google.gson.JsonObject)15