Search in sources :

Example 36 with Token

use of com.auth0.json.mgmt.Token in project java-jwt by auth0.

the class JWTVerifierTest method shouldThrowOnInvalidIssuedAtIfPresent.

@Test
public void shouldThrowOnInvalidIssuedAtIfPresent() throws Exception {
    exception.expect(InvalidClaimException.class);
    exception.expectMessage(startsWith("The Token can't be used before"));
    Clock clock = mock(Clock.class);
    when(clock.getToday()).thenReturn(new Date(DATE_TOKEN_MS_VALUE - 1000));
    String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE0Nzc1OTJ9.0WJky9eLN7kuxLyZlmbcXRL3Wy8hLoNCEk5CCl2M4lo";
    JWTVerifier.BaseVerification verification = (JWTVerifier.BaseVerification) JWTVerifier.init(Algorithm.HMAC256("secret"));
    verification.build(clock).verify(token);
}
Also used : Clock(com.auth0.jwt.interfaces.Clock) Date(java.util.Date) Test(org.junit.Test)

Example 37 with Token

use of com.auth0.json.mgmt.Token in project myinfo-connector-java by singpass.

the class MyInfoConnector method getMyInfoPersonData.

/**
 * <p>
 * Get MyInfo Person Data
 * </p>
 * <p>
 * This function takes in all the required variables, invoke the
 * getAccessToken API to generate the access token. The access token is then
 * use to invoke the person API to get the Person data.
 * </p>
 *
 * @param authCode
 *            the authorisation code
 * @param txnNo
 *            the transaction no required in person call
 * @param state
 *            the state required in token call
 * @param publicCert
 *            the public cert
 * @param privateKey
 *            the private key
 * @param clientAppId
 *            the client id
 * @param clientAppPwd
 *            the client password
 * @param redirectUri
 *            the redirect url
 * @param attributes
 *            the attributes
 * @param env
 *            the environment
 * @param tokenUrl
 *            the token url
 * @param personUrl
 *            the person url
 * @param proxyTokenURL
 *            user provided proxy url
 * @param proxyPersonURL
 *            user provided proxy url
 * @param useProxy
 *            indicate the use of proxy url
 * @return the person's data in json format.
 * @see <a href=
 *      "https://www.ndi-api.gov.sg/library/trusted-data/myinfo/implementation-myinfo-data"></a>
 * @since 1.0
 * @throws MyInfoException
 */
protected static String getMyInfoPersonData(String authCode, String txnNo, String state, Certificate publicCert, Key privateKey, String clientAppId, String clientAppPwd, String redirectUri, String attributes, String env, String tokenURL, String personURL, String proxyTokenURL, String proxyPersonURL, String useProxy) throws MyInfoException {
    String result = null;
    String jsonResponse = null;
    RSAPublicKey pubKey = CertUtil.getPublicKey(publicCert);
    // Get access token
    String token = MyInfoConnector.getAccessToken(authCode, tokenURL, clientAppId, clientAppPwd, redirectUri, env, privateKey, state, proxyTokenURL, useProxy);
    HashMap<String, String> tokenList = new Gson().fromJson(token, new TypeToken<HashMap<String, String>>() {
    }.getType());
    DecodedJWT tokenJWT = MyInfoSecurityHelper.verifyToken(tokenList.get(ApplicationConstant.ACCESS_TOKEN), pubKey);
    // Get person
    result = MyInfoConnector.getPersonData(tokenJWT.getSubject(), tokenList.get(ApplicationConstant.ACCESS_TOKEN), txnNo, personURL, clientAppId, attributes, env, privateKey, proxyPersonURL, useProxy);
    if (!env.equalsIgnoreCase(ApplicationConstant.SANDBOX)) {
        try {
            String payload = MyInfoSecurityHelper.getPayload(result, privateKey);
            DecodedJWT personJWT = MyInfoSecurityHelper.verifyToken(payload, pubKey);
            // Convert byte[] to String
            byte[] base64Decode = Base64.getDecoder().decode(personJWT.getPayload());
            jsonResponse = new String(base64Decode);
        } catch (Exception e) {
            throw new MyInfoException();
        }
    } else {
        jsonResponse = result;
    }
    return jsonResponse;
}
Also used : RSAPublicKey(java.security.interfaces.RSAPublicKey) TypeToken(com.google.gson.reflect.TypeToken) Gson(com.google.gson.Gson) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) IOException(java.io.IOException)

Example 38 with Token

use of com.auth0.json.mgmt.Token in project kemenu-web by afdezcl.

the class RefreshTokenIntegrationTest method aCustomerCouldRefreshAToken.

@Test
void aCustomerCouldRefreshAToken() {
    HttpHeaders headers = webTestClient.post().uri("/public/refresh").body(Mono.just(RefreshTokenRequestHelper.from(generateRefreshToken())), RefreshTokenRequest.class).exchange().expectStatus().isOk().expectHeader().exists("Authorization").expectHeader().exists("JWT-Refresh-Token").expectBody().returnResult().getResponseHeaders();
    String newAccessToken = headers.get("Authorization").get(0);
    String newRefreshToken = headers.get("JWT-Refresh-Token").get(0);
    DecodedJWT decodedAccessToken = jwtService.decodeAccessToken(newAccessToken);
    DecodedJWT decodedRefreshToken = jwtService.decodeRefreshToken(newRefreshToken);
    assertEquals(randomCustomer.getEmail(), decodedAccessToken.getSubject());
    assertEquals(randomCustomer.getEmail(), decodedRefreshToken.getSubject());
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) KemenuIntegrationTest(com.kemenu.kemenu_backend.common.KemenuIntegrationTest) Test(org.junit.jupiter.api.Test)

Example 39 with Token

use of com.auth0.json.mgmt.Token in project mapsmessaging_server by Maps-Messaging.

the class AwsJwtLoginModule method login.

@Override
public boolean login() throws LoginException {
    // prompt for a user name and password
    if (callbackHandler == null) {
        throw new LoginException("Error: no CallbackHandler available to garner authentication information from the user");
    }
    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("user name: ");
    callbacks[1] = new PasswordCallback("password: ", false);
    try {
        callbackHandler.handle(callbacks);
        username = ((NameCallback) callbacks[0]).getName();
        char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
        if (tmpPassword == null) {
            tmpPassword = new char[0];
        }
        String token = new String(tmpPassword);
        ((PasswordCallback) callbacks[1]).clearPassword();
        // Password should be a valid JWT
        RSAKeyProvider keyProvider = new AwsCognitoRSAKeyProvider(region, poolId);
        Algorithm algorithm = Algorithm.RSA256(keyProvider);
        JWTVerifier jwtVerifier = JWT.require(algorithm).withAudience(clientId).build();
        jwtVerifier.verify(token);
        return true;
    } catch (IOException ioe) {
        throw new LoginException(ioe.toString());
    } catch (UnsupportedCallbackException uce) {
        throw new LoginException("Error: " + uce.getCallback().toString() + " not available to garner authentication information " + "from the user");
    }
}
Also used : RSAKeyProvider(com.auth0.jwt.interfaces.RSAKeyProvider) IOException(java.io.IOException) Algorithm(com.auth0.jwt.algorithms.Algorithm) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) LoginException(javax.security.auth.login.LoginException) PasswordCallback(javax.security.auth.callback.PasswordCallback) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) JWTVerifier(com.auth0.jwt.JWTVerifier)

Example 40 with Token

use of com.auth0.json.mgmt.Token in project blogSpringBoot by lurenha.

the class TokenUtil method verify.

/**
 * 签名验证
 *
 * @param token
 * @return
 */
public static boolean verify(String token) {
    try {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("peng").build();
        DecodedJWT jwt = verifier.verify(token);
        // System.out.println("过期时间:      " + jwt.getExpiresAt());
        return true;
    } catch (Exception e) {
        return false;
    }
}
Also used : JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) JWTDecodeException(com.auth0.jwt.exceptions.JWTDecodeException)

Aggregations

DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)276 Algorithm (com.auth0.jwt.algorithms.Algorithm)147 Test (org.junit.Test)120 JWTVerifier (com.auth0.jwt.JWTVerifier)97 Date (java.util.Date)78 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)62 IOException (java.io.IOException)59 Claim (com.auth0.jwt.interfaces.Claim)49 HashMap (java.util.HashMap)40 VoidRequest (com.auth0.net.VoidRequest)31 RSAPublicKey (java.security.interfaces.RSAPublicKey)31 Test (org.junit.jupiter.api.Test)30 JWTDecodeException (com.auth0.jwt.exceptions.JWTDecodeException)28 JWTCreator (com.auth0.jwt.JWTCreator)21 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)21 JWT (com.auth0.jwt.JWT)20 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)19 UnsupportedEncodingException (java.io.UnsupportedEncodingException)18 Instant (java.time.Instant)18 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)17