Search in sources :

Example 26 with Claim

use of com.auth0.jwt.Claim in project goobi-workflow by intranda.

the class AuthorizationFilter method checkJwt.

/**
 * Verifies the JSON web token and checks if the "api_path" and "api_methods" claims match the actual request
 *
 * @param jwt
 * @param path the endpoint path the request tries to use
 * @param method the HTTP method used in the request
 * @return true, if the JWT authorizes the usage of the API path and method. Else: false
 */
public static boolean checkJwt(String jwt, String path, String method) {
    if (StringUtils.isBlank(jwt)) {
        return false;
    }
    try {
        DecodedJWT decodedJWT = JwtHelper.verifyTokenAndReturnClaims(jwt);
        Claim pathClaim = decodedJWT.getClaim("api_path");
        if (pathClaim == null || pathClaim.isNull()) {
            return false;
        }
        if (!Pattern.matches(pathClaim.asString(), path)) {
            return false;
        }
        Claim methodsClaim = decodedJWT.getClaim("api_methods");
        if (methodsClaim == null) {
            return false;
        }
        boolean methodMatch = Arrays.stream(methodsClaim.asArray(String.class)).anyMatch(claimMethod -> method.equalsIgnoreCase(claimMethod));
        if (!methodMatch) {
            return false;
        }
        return true;
    } catch (javax.naming.ConfigurationException | JWTVerificationException e) {
        log.error(e);
        return false;
    }
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) ConfigurationException(org.apache.commons.configuration.ConfigurationException) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Claim(com.auth0.jwt.interfaces.Claim)

Example 27 with Claim

use of com.auth0.jwt.Claim in project goobi-workflow by intranda.

the class Login method openIdLogin.

@POST
@Path("/openid")
@Operation(summary = "OpenID connect callback", description = "Verifies an openID claim and starts a session for the user")
@ApiResponse(responseCode = "200", description = "OK")
@ApiResponse(responseCode = "400", description = "Bad request")
@ApiResponse(responseCode = "500", description = "Internal error")
public void openIdLogin(@FormParam("error") String error, @FormParam("id_token") String idToken) throws IOException {
    ConfigurationHelper config = ConfigurationHelper.getInstance();
    String clientID = config.getOIDCClientID();
    String nonce = (String) servletRequest.getSession().getAttribute("openIDNonce");
    if (error == null) {
        // no error - we should have a token. Verify it.
        DecodedJWT jwt = JwtHelper.verifyOpenIdToken(idToken);
        if (jwt != null) {
            // now check if the nonce is the same as in the old session
            if (nonce.equals(jwt.getClaim("nonce").asString()) && clientID.equals(jwt.getClaim("aud").asString())) {
                // all OK, login the user
                HttpSession session = servletRequest.getSession();
                LoginBean userBean = Helper.getLoginBeanFromSession(session);
                // get the user by the configured claim from the JWT
                String login = jwt.getClaim(config.getOIDCIdClaim()).asString();
                log.debug("logging in user " + login);
                User user = UserManager.getUserBySsoId(login);
                if (user == null) {
                    userBean.setSsoError("Could not find user in Goobi database. Please contact your admin to add your SSO ID to the database.");
                    servletResponse.sendRedirect("/goobi/uii/logout.xhtml");
                    return;
                }
                userBean.setSsoError(null);
                user.lazyLoad();
                userBean.setMyBenutzer(user);
                userBean.setRoles(user.getAllUserRoles());
                userBean.setMyBenutzer(user);
                // add the user to the sessionform that holds information about all logged in users
                sessionForm.updateSessionUserName(servletRequest.getSession(), user);
            } else {
                if (!nonce.equals(jwt.getClaim("nonce").asString())) {
                    log.error("nonce does not match. Not logging user in");
                }
                if (!clientID.equals(jwt.getClaim("aud").asString())) {
                    log.error("clientID does not match aud. Not logging user in");
                }
            }
        } else {
            log.error("could not verify JWT");
        }
    } else {
        log.error(error);
    }
    servletResponse.sendRedirect("/goobi/index.xhtml");
}
Also used : User(org.goobi.beans.User) HttpSession(javax.servlet.http.HttpSession) LoginBean(org.goobi.managedbeans.LoginBean) ConfigurationHelper(de.sub.goobi.config.ConfigurationHelper) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Operation(io.swagger.v3.oas.annotations.Operation) ApiResponse(io.swagger.v3.oas.annotations.responses.ApiResponse)

Example 28 with Claim

use of com.auth0.jwt.Claim in project AuthGuard by AuthGuard.

the class JwtConfigParserTest method parseRsa512.

@Test
void parseRsa512() {
    final String publicKeyPath = "src/test/resources/rsa512-public.pem";
    final String privateKeyPath = "src/test/resources/rsa512-private.pem";
    final Algorithm algorithm = JwtConfigParser.parseAlgorithm("RSA512", publicKeyPath, privateKeyPath);
    final String jwt = JWT.create().withClaim("claim", "value").sign(algorithm);
    algorithm.verify(JWT.decode(jwt));
}
Also used : Algorithm(com.auth0.jwt.algorithms.Algorithm) Test(org.junit.jupiter.api.Test)

Example 29 with Claim

use of com.auth0.jwt.Claim 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 30 with Claim

use of com.auth0.jwt.Claim in project localstack-pro-samples by localstack.

the class Test method convert.

public void convert(@NonNull final String token) throws MalformedURLException {
    final URL kidStore = new URL(awsProperties.getCognito().getKidStoreUrl());
    final JwkProvider jwkProvider = new JwkProviderBuilder(kidStore).build();
    final DecodedJWT decodedJWT = JWT.decode(token);
    final AwsCognitoRSAKeyProvider awsCognitoRSAKeyProvider = new AwsCognitoRSAKeyProvider(jwkProvider);
    JWT.require(Algorithm.RSA256(awsCognitoRSAKeyProvider)).acceptLeeway(ACCEPT_LEEWAY_SECONDS).withClaim(TOKEN_USE, ACCESS).build().verify(decodedJWT);
    final Claim clientIdClaim = decodedJWT.getClaim(CLIENT_ID);
    final Claim userNameClaim = decodedJWT.getClaim(USER_NAME);
    final Claim scopeClaim = decodedJWT.getClaim(SCOPE);
    final List<String> roles = Arrays.stream(scopeClaim.asString().split(" ")).map(scope -> scope.substring(scope.lastIndexOf("/") + 1)).collect(Collectors.toList());
    System.out.println("" + clientIdClaim + " " + userNameClaim + " " + roles);
// return new InsureSignToken()
// .setClientId(clientIdClaim.asString())
// .setUserName(userNameClaim.asString())
// .setRoles(roles);
}
Also used : Claim(com.auth0.jwt.Claim) RSAKeyProvider(com.auth0.jwt.interfaces.RSAKeyProvider) JWT(com.auth0.jwt.JWT) Arrays(java.util.Arrays) List(java.util.List) JwkProvider(com.auth0.jwk.JwkProvider) MalformedURLException(java.net.MalformedURLException) URL(java.net.URL) Algorithm(com.auth0.jwt.Algorithm) Collectors(java.util.stream.Collectors) JwkProviderBuilder(com.auth0.jwk.JwkProviderBuilder) JwkProvider(com.auth0.jwk.JwkProvider) JwkProviderBuilder(com.auth0.jwk.JwkProviderBuilder) URL(java.net.URL) Claim(com.auth0.jwt.Claim)

Aggregations

Claim (com.auth0.jwt.interfaces.Claim)110 Test (org.junit.Test)67 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)62 JsonNode (com.fasterxml.jackson.databind.JsonNode)42 Algorithm (com.auth0.jwt.algorithms.Algorithm)24 Date (java.util.Date)24 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)21 RSAPublicKey (java.security.interfaces.RSAPublicKey)21 Test (org.junit.jupiter.api.Test)18 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)17 JWTVerifier (com.auth0.jwt.JWTVerifier)15 JwksTestKeySource (org.sdase.commons.server.auth.service.testsources.JwksTestKeySource)14 JsonObject (com.google.gson.JsonObject)10 HashMap (java.util.HashMap)9 UserPojo (com.auth0.jwt.UserPojo)8 IOException (java.io.IOException)8 Map (java.util.Map)8 TestingProcessManager (io.supertokens.test.TestingProcessManager)7 NullClaim (com.auth0.jwt.impl.NullClaim)5 JWT (com.auth0.jwt.JWT)4