Search in sources :

Example 46 with JWT

use of com.auth0.android.jwt.JWT in project spring-learning by moon-zhou.

the class JwtUtil method sign.

/**
 * 生成签名,15分钟后过期
 *
 * @param username
 * @param userId
 * @return
 */
public static String sign(String username, String userId, String password) {
    // 过期时间
    Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
    // 私钥及加密算法
    Algorithm algorithm = Algorithm.HMAC256(password);
    // 设置头信息
    HashMap<String, Object> header = new HashMap<>(2);
    header.put("typ", "JWT");
    header.put("alg", "HS256");
    // 附带username和userID生成签名
    return JWT.create().withHeader(header).withClaim("userId", userId).withClaim("username", username).withExpiresAt(date).sign(algorithm);
}
Also used : HashMap(java.util.HashMap) Algorithm(com.auth0.jwt.algorithms.Algorithm) Date(java.util.Date)

Example 47 with JWT

use of com.auth0.android.jwt.JWT in project spring-learning by moon-zhou.

the class JWTTest method testJWTVerify.

/**
 * 验证JWT生成的token
 *
 * 为了方便测试,定义了类变量,整体用例可直接执行
 */
@Test
public void testJWTVerify() {
    final JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SIGN)).build();
    final DecodedJWT decodedJWT = jwtVerifier.verify(token);
    int decodeUserId = decodedJWT.getClaim(USER_ID).asInt();
    String decodeUserName = decodedJWT.getClaim(USER_NAME).asString();
    System.out.println("用户Id:" + decodeUserId);
    System.out.println("用户名:" + decodeUserName);
    System.out.println("过期时间:" + decodedJWT.getExpiresAt());
    Assertions.assertEquals(userId, decodeUserId);
    Assertions.assertEquals(userName, decodeUserName);
}
Also used : JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Test(org.junit.jupiter.api.Test)

Example 48 with JWT

use of com.auth0.android.jwt.JWT 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 49 with JWT

use of com.auth0.android.jwt.JWT 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 50 with JWT

use of com.auth0.android.jwt.JWT in project einstein-bot-sdk-java by forcedotcom.

the class JwtBearerOAuth method getToken.

@Override
public String getToken() {
    Optional<String> token = cache.flatMap(c -> c.get(getCacheKey()));
    if (token.isPresent()) {
        logger.debug("Found cached OAuth token.");
        return token.get();
    }
    logger.debug("Did not find OAuth token in cache. Will retrieve from OAuth server.");
    Instant now = Instant.now();
    String jwt = null;
    try {
        Map<String, Object> headers = new HashMap<String, Object>();
        headers.put("alg", "RS256");
        Algorithm algorithm = Algorithm.RSA256(null, (RSAPrivateKey) privateKey);
        jwt = JWT.create().withHeader(headers).withAudience(loginEndpoint).withExpiresAt(Date.from(now.plus(jwtExpiryMinutes, ChronoUnit.MINUTES))).withIssuer(connectedAppId).withSubject(userId).sign(algorithm);
        logger.debug("Generated jwt: {} ", jwt);
    } catch (JWTCreationException exception) {
        // Invalid Signing configuration / Couldn't convert Claims.
        throw new RuntimeException(exception);
    }
    String response = webClient.post().uri("/services/oauth2/token").header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).body(BodyInserters.fromFormData("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer").with("assertion", jwt)).retrieve().bodyToMono(String.class).block();
    String oAuthToken = null;
    try {
        ObjectNode node = new ObjectMapper().readValue(response, ObjectNode.class);
        oAuthToken = node.get("access_token").asText();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
    IntrospectionResult iResult = introspector.introspect(oAuthToken);
    if (!iResult.isActive()) {
        throw new RuntimeException("OAuth token is not active.");
    }
    Instant expiry = Instant.ofEpochSecond(iResult.getExp());
    long ttl = Math.max(0, Instant.now().until(expiry, ChronoUnit.SECONDS) - 300);
    if (cache.isPresent()) {
        cache.get().set(getCacheKey(), oAuthToken, ttl);
    }
    return oAuthToken;
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) HashMap(java.util.HashMap) Instant(java.time.Instant) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTCreationException(com.auth0.jwt.exceptions.JWTCreationException) OAuthResponseException(com.salesforce.einsteinbot.sdk.exception.OAuthResponseException) JWTCreationException(com.auth0.jwt.exceptions.JWTCreationException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)305 Test (org.junit.Test)217 Algorithm (com.auth0.jwt.algorithms.Algorithm)110 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)82 JWTVerifier (com.auth0.jwt.JWTVerifier)79 IOException (java.io.IOException)60 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)54 ECDSAAlgorithmTest (com.auth0.jwt.algorithms.ECDSAAlgorithmTest)53 Date (java.util.Date)50 Claim (com.auth0.jwt.interfaces.Claim)36 RSAPublicKey (java.security.interfaces.RSAPublicKey)34 ECPublicKey (java.security.interfaces.ECPublicKey)27 ECDSAKeyProvider (com.auth0.jwt.interfaces.ECDSAKeyProvider)26 HashMap (java.util.HashMap)25 JWTDecodeException (com.auth0.jwt.exceptions.JWTDecodeException)20 Instant (java.time.Instant)20 JsonObject (com.google.gson.JsonObject)19 ServletException (javax.servlet.ServletException)19 JWT (com.auth0.jwt.JWT)18 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)18