Search in sources :

Example 6 with Verification

use of com.auth0.jwt.interfaces.Verification 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 7 with Verification

use of com.auth0.jwt.interfaces.Verification in project ARLAS-server by gisaia.

the class AuthorizationFilter method filter.

@Override
public void filter(ContainerRequestContext ctx) {
    Transaction transaction = ElasticApm.currentTransaction();
    boolean isPublic = ctx.getUriInfo().getPath().concat(":").concat(ctx.getMethod()).matches(authConf.getPublicRegex());
    String header = ctx.getHeaderString(HttpHeaders.AUTHORIZATION);
    if (header == null || (header != null && !header.toLowerCase().startsWith("bearer "))) {
        if (isPublic || ctx.getMethod() == "OPTIONS") {
            return;
        } else {
            ctx.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
        }
    }
    try {
        // header presence and format already checked before in AuthenticationFilter
        DecodedJWT jwt = jwtVerifier.verify(header.substring(7));
        // remove it in case it's been set manually
        ctx.getHeaders().remove(authConf.headerUser);
        String userId = jwt.getSubject();
        if (!StringUtil.isNullOrEmpty(userId)) {
            ctx.getHeaders().putSingle(authConf.headerUser, userId);
            transaction.setUser(userId, "", "");
        }
        // remove it in case it's been set manually
        ctx.getHeaders().remove(authConf.headerGroup);
        Claim jwtClaimRoles = jwt.getClaim(authConf.claimRoles);
        if (!jwtClaimRoles.isNull()) {
            List<String> groups = jwtClaimRoles.asList(String.class).stream().filter(r -> r.toLowerCase().startsWith("group")).collect(Collectors.toList());
            ctx.setProperty("groups", groups);
            ctx.getHeaders().put(authConf.headerGroup, groups);
        }
        Claim jwtClaimPermissions = jwt.getClaim(authConf.claimPermissions);
        if (!jwtClaimPermissions.isNull()) {
            ArlasClaims arlasClaims = new ArlasClaims(jwtClaimPermissions.asList(String.class));
            ctx.setProperty("claims", arlasClaims);
            if (arlasClaims.isAllowed(ctx.getMethod(), ctx.getUriInfo().getPath())) {
                arlasClaims.injectHeaders(ctx.getHeaders(), transaction);
                return;
            }
        }
        if (isPublic) {
            return;
        } else {
            ctx.abortWith(Response.status(Response.Status.FORBIDDEN).build());
        }
    } catch (JWTVerificationException e) {
        LOGGER.warn("JWT verification failed.", e);
        if (!isPublic) {
            ctx.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
        }
        return;
    }
    ctx.abortWith(Response.status(Response.Status.FORBIDDEN).build());
}
Also used : X509Certificate(java.security.cert.X509Certificate) JWT(com.auth0.jwt.JWT) Transaction(co.elastic.apm.api.Transaction) StringUtil(io.arlas.server.core.utils.StringUtil) Provider(javax.ws.rs.ext.Provider) CertificateFactory(java.security.cert.CertificateFactory) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) URL(java.net.URL) LoggerFactory(org.slf4j.LoggerFactory) Priorities(javax.ws.rs.Priorities) ContainerRequestFilter(javax.ws.rs.container.ContainerRequestFilter) ContainerRequestContext(javax.ws.rs.container.ContainerRequestContext) Algorithm(com.auth0.jwt.algorithms.Algorithm) RSAPublicKey(java.security.interfaces.RSAPublicKey) JWTVerifier(com.auth0.jwt.interfaces.JWTVerifier) Claim(com.auth0.jwt.interfaces.Claim) JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) ArlasAuthConfiguration(io.arlas.server.core.app.ArlasAuthConfiguration) Logger(org.slf4j.Logger) ElasticApm(co.elastic.apm.api.ElasticApm) FileInputStream(java.io.FileInputStream) Collectors(java.util.stream.Collectors) Priority(javax.annotation.Priority) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Response(javax.ws.rs.core.Response) InputStream(java.io.InputStream) JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) Transaction(co.elastic.apm.api.Transaction) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Claim(com.auth0.jwt.interfaces.Claim)

Example 8 with Verification

use of com.auth0.jwt.interfaces.Verification in project auth0-java-mvc-common by auth0.

the class IdTokenVerifier method verify.

/**
 * Verifies a provided ID Token follows the OIDC specification.
 * See https://openid.net/specs/openid-connect-core-1_0-final.html#IDTokenValidation
 *
 * @param token         the ID Token to verify.
 * @param verifyOptions the verification options, like audience, issuer, algorithm.
 * @throws TokenValidationException If the ID Token is null, its signing algorithm not supported, its signature invalid or one of its claim invalid.
 */
void verify(String token, Options verifyOptions) throws TokenValidationException {
    Validate.notNull(verifyOptions);
    if (isEmpty(token)) {
        throw new TokenValidationException("ID token is required but missing");
    }
    DecodedJWT decoded = verifyOptions.verifier.verifySignature(token);
    if (isEmpty(decoded.getIssuer())) {
        throw new TokenValidationException("Issuer (iss) claim must be a string present in the ID token");
    }
    if (!decoded.getIssuer().equals(verifyOptions.issuer)) {
        throw new TokenValidationException(String.format("Issuer (iss) claim mismatch in the ID token, expected \"%s\", found \"%s\"", verifyOptions.issuer, decoded.getIssuer()));
    }
    if (isEmpty(decoded.getSubject())) {
        throw new TokenValidationException("Subject (sub) claim must be a string present in the ID token");
    }
    final List<String> audience = decoded.getAudience();
    if (audience == null) {
        throw new TokenValidationException("Audience (aud) claim must be a string or array of strings present in the ID token");
    }
    if (!audience.contains(verifyOptions.audience)) {
        throw new TokenValidationException(String.format("Audience (aud) claim mismatch in the ID token; expected \"%s\" but found \"%s\"", verifyOptions.audience, decoded.getAudience()));
    }
    // validate org if set
    if (verifyOptions.organization != null) {
        String orgIdClaim = decoded.getClaim("org_id").asString();
        if (isEmpty(orgIdClaim)) {
            throw new TokenValidationException("Organization Id (org_id) claim must be a string present in the ID token");
        }
        if (!verifyOptions.organization.equals(orgIdClaim)) {
            throw new TokenValidationException(String.format("Organization (org_id) claim mismatch in the ID token; expected \"%s\" but found \"%s\"", verifyOptions.organization, orgIdClaim));
        }
    }
    final Calendar cal = Calendar.getInstance();
    final Date now = verifyOptions.clock != null ? verifyOptions.clock : cal.getTime();
    final int clockSkew = verifyOptions.clockSkew != null ? verifyOptions.clockSkew : DEFAULT_CLOCK_SKEW;
    if (decoded.getExpiresAt() == null) {
        throw new TokenValidationException("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 TokenValidationException(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 TokenValidationException("Issued At (iat) claim must be a number present in the ID token");
    }
    cal.setTime(decoded.getIssuedAt());
    cal.add(Calendar.SECOND, -1 * clockSkew);
    if (verifyOptions.nonce != null) {
        String nonceClaim = decoded.getClaim(NONCE_CLAIM).asString();
        if (isEmpty(nonceClaim)) {
            throw new TokenValidationException("Nonce (nonce) claim must be a string present in the ID token");
        }
        if (!verifyOptions.nonce.equals(nonceClaim)) {
            throw new TokenValidationException(String.format("Nonce (nonce) claim mismatch in the ID token; expected \"%s\", found \"%s\"", verifyOptions.nonce, nonceClaim));
        }
    }
    if (audience.size() > 1) {
        String azpClaim = decoded.getClaim(AZP_CLAIM).asString();
        if (isEmpty(azpClaim)) {
            throw new TokenValidationException("Authorized Party (azp) claim must be a string present in the ID token when Audience (aud) claim has multiple values");
        }
        if (!verifyOptions.audience.equals(azpClaim)) {
            throw new TokenValidationException(String.format("Authorized Party (azp) claim mismatch in the ID token; expected \"%s\", found \"%s\"", verifyOptions.audience, azpClaim));
        }
    }
    if (verifyOptions.maxAge != null) {
        Date authTime = decoded.getClaim(AUTH_TIME_CLAIM).asDate();
        if (authTime == null) {
            throw new TokenValidationException("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, verifyOptions.maxAge);
        cal.add(Calendar.SECOND, clockSkew);
        Date authTimeDate = cal.getTime();
        if (now.after(authTimeDate)) {
            throw new TokenValidationException(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 : Calendar(java.util.Calendar) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Date(java.util.Date)

Example 9 with Verification

use of com.auth0.jwt.interfaces.Verification in project simple-jwt by vorbote.

the class AccessKeyUtil method Info.

/**
 * Decode the token, and you can easily get some info from
 * this token.
 *
 * @param token The token.
 * @return The decoded jwt token.
 * @throws com.auth0.jwt.exceptions.AlgorithmMismatchException     If the algorithm stated in the token's
 *                                                                 header it's not equal to the one
 *                                                                 defined in the JWTVerifier.
 * @throws com.auth0.jwt.exceptions.SignatureVerificationException If the signature is invalid.
 * @throws com.auth0.jwt.exceptions.TokenExpiredException          If the token has expired.
 * @throws com.auth0.jwt.exceptions.InvalidClaimException          If a claim contained a different value
 *                                                                 than the expected one.
 * @throws com.auth0.jwt.exceptions.JWTVerificationException       If any of the verification steps fail
 * @see JWTVerifier#verify(String)
 */
public DecodedJWT Info(String token) {
    JWTVerifier verifier;
    switch(algorithm) {
        case HS256:
            verifier = JWT.require(Algorithm.HMAC256(secret)).build();
            break;
        case HS384:
            verifier = JWT.require(Algorithm.HMAC384(secret)).build();
            break;
        case HS512:
            verifier = JWT.require(Algorithm.HMAC512(secret)).build();
            break;
        default:
            // 这里理论上应该抛出异常的,但是实在是懒得做了,就先这样吧。
            // 至于其他的算法,后续再考虑加上。
            verifier = JWT.require(Algorithm.HMAC256(secret)).build();
            log.error("This algorithm is not supported yet, will use HMAC256 by default.");
    }
    return verifier.verify(token);
}
Also used : JWTVerifier(com.auth0.jwt.JWTVerifier)

Example 10 with Verification

use of com.auth0.jwt.interfaces.Verification in project tanafaso-backend by tanafaso.

the class ApiAuthenticationController method validateAppleAuthCode.

private boolean validateAppleAuthCode(AppleAuthenticationRequest request) {
    Map<String, Object> appleApiRequestHeader = new HashMap<>();
    appleApiRequestHeader.put("alg", "ES256");
    appleApiRequestHeader.put("kid", appleSignInKeyId);
    appleApiRequestHeader.put("typ", "JWT");
    InputStreamReader appleAuthPrivateKeyInputStreamReader;
    try {
        appleAuthPrivateKeyInputStreamReader = new InputStreamReader(new ClassPathResource(appleAuthPrivateKeyFile).getInputStream());
    } catch (IOException e) {
        logger.error("Couldn't read the apple authorization private key file.", e);
        return false;
    }
    ECPrivateKey privateKey;
    try {
        PemObject pemObject;
        pemObject = new PemReader(appleAuthPrivateKeyInputStreamReader).readPemObject();
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(pemObject.getContent());
        KeyFactory factory;
        factory = KeyFactory.getInstance("EC");
        privateKey = (ECPrivateKey) factory.generatePrivate(spec);
    } catch (Exception e) {
        logger.error("Could not convert Apple private key into an EC key.", e);
        return false;
    }
    String signedJwt = JWT.create().withHeader(appleApiRequestHeader).withIssuer(appleTeamId).withIssuedAt(new Date(System.currentTimeMillis())).withExpiresAt(new Date(System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(10))).withAudience("https://appleid.apple.com").withSubject("com.tanafaso.azkar").sign(Algorithm.ECDSA256(privateKey));
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
    map.add("client_id", "com.tanafaso.azkar");
    map.add("client_secret", signedJwt);
    map.add("code", request.getAuthCode());
    map.add("grant_type", "authorization_code");
    HttpEntity<MultiValueMap<String, String>> appleApiRequestHttpEntity = new HttpEntity<>(map, headers);
    logger.info("Sending to Apple auth code verification API.");
    ResponseEntity<AppleIdToken> appleIdToken = restTemplate.postForEntity("https://appleid.apple.com/auth/token", appleApiRequestHttpEntity, AppleIdToken.class);
    if (appleIdToken.getStatusCode() == HttpStatus.OK) {
        DecodedJWT decodedJwt = JWT.decode(appleIdToken.getBody().getIdToken());
        boolean emailIsVerified = decodedJwt.getClaim("email_verified").asString().equals("true");
        String potentiallyVerifiedEmail = decodedJwt.getClaim("email").asString().toLowerCase();
        if (emailIsVerified && potentiallyVerifiedEmail.equals(request.getEmail())) {
            return true;
        }
        logger.info("Failed to verify user signing in with apple: email={}, firstName={}, " + "lastName={}, emailIsVerified={}, appleApiReturnedEmail={}", request.getEmail(), request.getFirstName(), request.getLastName(), emailIsVerified, potentiallyVerifiedEmail);
        return false;
    }
    logger.info("Failed to verify user signing in with apple as apple API returned status code: " + "{} for email={}, firstName={}, lastName={}", appleIdToken.getStatusCode().toString(), request.getEmail(), request.getFirstName(), request.getLastName());
    return false;
}
Also used : ECPrivateKey(java.security.interfaces.ECPrivateKey) HttpHeaders(org.springframework.http.HttpHeaders) InputStreamReader(java.io.InputStreamReader) HttpEntity(org.springframework.http.HttpEntity) HashMap(java.util.HashMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) IOException(java.io.IOException) ClassPathResource(org.springframework.core.io.ClassPathResource) MessagingException(javax.mail.MessagingException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) Date(java.util.Date) PemObject(org.bouncycastle.util.io.pem.PemObject) PemReader(org.bouncycastle.util.io.pem.PemReader) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) PemObject(org.bouncycastle.util.io.pem.PemObject) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) KeyFactory(java.security.KeyFactory) MultiValueMap(org.springframework.util.MultiValueMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap)

Aggregations

Test (org.junit.Test)29 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)28 Algorithm (com.auth0.jwt.algorithms.Algorithm)14 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)11 Date (java.util.Date)11 Verification (com.auth0.jwt.interfaces.Verification)9 UnsupportedEncodingException (java.io.UnsupportedEncodingException)6 JWTVerifier (com.auth0.jwt.JWTVerifier)5 RSAPublicKey (java.security.interfaces.RSAPublicKey)5 Job (com.auth0.json.mgmt.jobs.Job)4 Claim (com.auth0.jwt.interfaces.Claim)4 Clock (com.auth0.jwt.interfaces.Clock)4 List (java.util.List)4 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)4 JWT (com.auth0.jwt.JWT)3 JWTVerifier (com.auth0.jwt.interfaces.JWTVerifier)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)3 IOException (java.io.IOException)3 ByteBuffer (java.nio.ByteBuffer)3 FloodlightModuleException (net.floodlightcontroller.core.module.FloodlightModuleException)3