Java Code Examples for org.gluu.oxauth.model.exception.InvalidJwtException

The following examples show how to use org.gluu.oxauth.model.exception.InvalidJwtException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: oxAuth   Source File: JwtClaimSet.java    License: MIT License 6 votes vote down vote up
public Map<String, List<String>> toMap() throws InvalidJwtException {
    Map<String, List<String>> map = new HashMap<String, java.util.List<String>>();

    try {
        for (Map.Entry<String, Object> claim : claims.entrySet()) {
            String key = claim.getKey();
            Object value = claim.getValue();

            List<String> values = new ArrayList<String>();
            if (value instanceof JSONArray) {
                JSONArray jsonArray = (JSONArray) value;
                for (int i = 0; i < jsonArray.length(); i++) {
                    values.add(jsonArray.getString(i));
                }
            } else if (value != null) {
                values.add(value.toString());
            }

            map.put(key, values);
        }
    } catch (JSONException e) {
        throw new InvalidJwtException(e);
    }

    return map;
}
 
Example 2
Source Project: oxd   Source File: ValidatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void tokenWithNAzpNotClientId_shouldNotValid() throws InvalidJwtException {
    //"aud": ["6b578a9b-7513-477a-9a7f-134-3b487caf8","another_aud"],
    //"azp":"Not_equal_to_client_id"
    final Jwt idToken = Jwt.parse("eyJraWQiOiJjZmFiMzRlYy0xNjhkLTQ4OTUtODRiOC0xZjAyNzgwNDkxYzciLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdF9oYXNoIjoiMnI1clZ2STdpMWxfcnNXZUV4bGRuUSIsImF1ZCI6WyI2YjU3OGE5Yi03NTEzLTQ3N2EtOWE3Zi0xMzQzYjQ4N2NhZjgiLCJhbm90aGVyX2F1ZCJdLCJhenAiOiJOb3RfZXF1YWxfdG9fY2xpZW50X2lkIiwic3ViIjoicy1fWmlyVnQ3Tk9EZG5XREFVR3JqVDJxVVp3SzZjWFRoYjlxVjk5di10ZyIsImF1dGhfdGltZSI6MTU2ODE4NTMyNywiaXNzIjoiaHR0cHM6Ly9kdW1teS1pc3N1ZXIub3JnIiwiZXhwIjoxOTY4MTg4OTMwLCJpYXQiOjE1NjgxODUzMzAsIm5vbmNlIjoiN3I0NnV0NmVtdTlnaTExZ244MDQ0dW02NDAiLCJveE9wZW5JRENvbm5lY3RWZXJzaW9uIjoib3BlbmlkY29ubmVjdC0xLjAifQ.Tnw-jF4p7VHgIE2_wcuP7WxRqtGFw2pmKltIri63hznYikYFC4frUZcJ44OKCt_tki2ZJY6EDhM1o9cPEz-_Vt-gsavfyDc711xlgNaPOBjGasdPvx5iilPLIogy4BXB4T3ROgqQpLQZf-00AQBBsrpZX5I2VJtLcyJL6_l3bKw");
    String clientId = "6b578a9b-7513-477a-9a7f-1343b487caf8";
    try {
        Validator.validateAudience(idToken, clientId);
        assertTrue(false);
    } catch (Exception e) {
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException)e;
            assertTrue(httpException.getCode().getCode().equals("invalid_id_token_bad_authorized_party"));
        }
    }
}
 
Example 3
Source Project: oxAuth   Source File: SoftwareStatement.java    License: MIT License 5 votes vote down vote up
protected JSONObject headerToJSONObject() throws InvalidJwtException {
    JwtHeader jwtHeader = new JwtHeader();

    jwtHeader.setAlgorithm(signatureAlgorithm);
    jwtHeader.setKeyId(keyId);

    return jwtHeader.toJsonObject();
}
 
Example 4
Source Project: oxAuth   Source File: JwtAuthorizationRequest.java    License: MIT License 5 votes vote down vote up
protected JSONObject headerToJSONObject() throws InvalidJwtException {
    JwtHeader jwtHeader = new JwtHeader();

    jwtHeader.setType(type);
    if (keyEncryptionAlgorithm != null && blockEncryptionAlgorithm != null) {
        jwtHeader.setAlgorithm(keyEncryptionAlgorithm);
        jwtHeader.setEncryptionMethod(blockEncryptionAlgorithm);
    } else {
        jwtHeader.setAlgorithm(signatureAlgorithm);
    }
    jwtHeader.setKeyId(keyId);

    return jwtHeader.toJsonObject();
}
 
Example 5
Source Project: oxAuth   Source File: JwtState.java    License: MIT License 5 votes vote down vote up
protected JSONObject headerToJSONObject() throws InvalidJwtException {
    JwtHeader jwtHeader = new JwtHeader();

    jwtHeader.setType(type);
    if (keyEncryptionAlgorithm != null && blockEncryptionAlgorithm != null) {
        jwtHeader.setAlgorithm(keyEncryptionAlgorithm);
        jwtHeader.setEncryptionMethod(blockEncryptionAlgorithm);
    } else {
        jwtHeader.setAlgorithm(signatureAlgorithm);
    }
    jwtHeader.setKeyId(keyId);

    return jwtHeader.toJsonObject();
}
 
Example 6
Source Project: oxAuth   Source File: SelectAccountHttpTest.java    License: MIT License 5 votes vote down vote up
private void assertIdToken(String idToken) throws InvalidJwtException {
    Jwt jwt = Jwt.parse(idToken);
    assertNotNull(jwt.getHeader().getClaimAsString(JwtHeaderName.TYPE));
    assertNotNull(jwt.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.ISSUER));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.AUDIENCE));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.EXPIRATION_TIME));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.ISSUED_AT));
}
 
Example 7
Source Project: oxAuth   Source File: AuthenticationFilter.java    License: MIT License 5 votes vote down vote up
private void processJwtAuth(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
                            FilterChain filterChain) {
    boolean authorized = false;

    try {
        if (servletRequest.getParameter("client_assertion") != null
                && servletRequest.getParameter("client_assertion_type") != null) {
            String clientId = servletRequest.getParameter("client_id");
            ClientAssertionType clientAssertionType = ClientAssertionType
                    .fromString(servletRequest.getParameter("client_assertion_type"));
            String encodedAssertion = servletRequest.getParameter("client_assertion");

            if (clientAssertionType == ClientAssertionType.JWT_BEARER) {
                ClientAssertion clientAssertion = new ClientAssertion(appConfiguration, cryptoProvider, clientId,
                        clientAssertionType, encodedAssertion);

                String username = clientAssertion.getSubjectIdentifier();
                String password = clientAssertion.getClientSecret();

                // Only authenticate if username doesn't match
                // Identity.username and user isn't authenticated
                if (!username.equals(identity.getCredentials().getUsername()) || !identity.isLoggedIn()) {
                    identity.getCredentials().setUsername(username);
                    identity.getCredentials().setPassword(password);

                    authenticator.authenticateClient(servletRequest, true);
                    authorized = true;
                }
            }
        }

        filterChain.doFilter(servletRequest, servletResponse);
    } catch (ServletException | IOException | InvalidJwtException ex) {
        log.info("JWT authentication failed: {}", ex);
    }

    if (!authorized) {
        sendError(servletResponse);
    }
}
 
Example 8
Source Project: oxAuth   Source File: UmaPCT.java    License: MIT License 5 votes vote down vote up
public void setClaims(JwtClaims claims) throws InvalidJwtException {
    if (claims != null) {
        claimValuesAsJson = claims.toJsonString();
    } else {
        claimValuesAsJson = null;
    }
}
 
Example 9
Source Project: oxAuth   Source File: UmaGatherContext.java    License: MIT License 5 votes vote down vote up
/**
 * Must not take any parameters
 */
public void persist() {
    try {
        pct.setClaims(claims);
    } catch (InvalidJwtException e) {
        getLog().error("Failed to persist claims", e);
    }

    sessionService.persist(session);
    pctService.merge(pct);
}
 
Example 10
Source Project: oxAuth   Source File: JsonWebResponse.java    License: MIT License 5 votes vote down vote up
public String asString() {
	try {
		return claims.toJsonString();
	} catch (InvalidJwtException ex) {
		ex.printStackTrace();
	}

	return "";
}
 
Example 11
Source Project: oxAuth   Source File: JwtClaimSet.java    License: MIT License 5 votes vote down vote up
public String toBase64JsonObject() throws InvalidJwtException {
    try {
        String jsonObjectString = toJsonString();
        byte[] jsonObjectBytes = jsonObjectString.getBytes(Util.UTF8_STRING_ENCODING);
        return Base64Util.base64urlencode(jsonObjectBytes);
    } catch (UnsupportedEncodingException e) {
        return null;
    }
}
 
Example 12
Source Project: oxAuth   Source File: JwtClaimSet.java    License: MIT License 5 votes vote down vote up
public String toJsonString() throws InvalidJwtException {
    JSONObject jsonObject = toJsonObject();
    String jsonObjectString = jsonObject.toString();
    jsonObjectString = jsonObjectString.replace("\\/", "/");

    return jsonObjectString;
}
 
Example 13
Source Project: oxAuth   Source File: Jwt.java    License: MIT License 5 votes vote down vote up
public String getSigningInput() throws InvalidJwtException {
    if (loaded) {
        return encodedHeader + "." + encodedClaims;
    } else {
        return header.toBase64JsonObject() + "." + claims.toBase64JsonObject();
    }
}
 
Example 14
Source Project: oxAuth   Source File: Jwt.java    License: MIT License 5 votes vote down vote up
public static Jwt parse(String encodedJwt) throws InvalidJwtException {
    if (StringUtils.isBlank(encodedJwt)) {
        return null;
    }

    String encodedHeader = null;
    String encodedClaims = null;
    String encodedSignature = null;

    String[] jwtParts = encodedJwt.split("\\.");
    if (jwtParts.length == 2) { // Signature Algorithm NONE
        encodedHeader = jwtParts[0];
        encodedClaims = jwtParts[1];
        encodedSignature = "";
    } else if (jwtParts.length == 3) {
        encodedHeader = jwtParts[0];
        encodedClaims = jwtParts[1];
        encodedSignature = jwtParts[2];
    } else {
        throw new InvalidJwtException("Invalid JWT format.");
    }

    Jwt jwt = new Jwt();
    jwt.setHeader(new JwtHeader(encodedHeader));
    jwt.setClaims(new JwtClaims(encodedClaims));
    jwt.setEncodedSignature(encodedSignature);
    jwt.encodedHeader = encodedHeader;
    jwt.encodedClaims = encodedClaims;
    jwt.loaded = true;

    return jwt;
}
 
Example 15
Source Project: oxAuth   Source File: Jwt.java    License: MIT License 5 votes vote down vote up
@Override
public String toString() {
    try {
        if (encodedSignature == null) {
            return getSigningInput() + ".";
        } else {
            return getSigningInput() + "." + encodedSignature;
        }
    } catch (InvalidJwtException e) {
        e.printStackTrace();
    }

    return "";
}
 
Example 16
Source Project: oxAuth   Source File: JweEncrypterImpl.java    License: MIT License 5 votes vote down vote up
@Override
public Jwe encrypt(Jwe jwe) throws InvalidJweException {
    try {
        JWEEncrypter encrypter = createJweEncrypter();

        if (jwe.getSignedJWTPayload() != null) {
            jwe.getHeader().setContentType(JwtType.JWT);
        }
        JWEObject jweObject = new JWEObject(JWEHeader.parse(jwe.getHeader().toJsonObject().toString()), createPayload(jwe));

        jweObject.encrypt(encrypter);
        String encryptedJwe = jweObject.serialize();

        String[] jweParts = encryptedJwe.split("\\.");
        if (jweParts.length != 5) {
            throw new InvalidJwtException("Invalid JWS format.");
        }

        String encodedHeader = jweParts[0];
        String encodedEncryptedKey = jweParts[1];
        String encodedInitializationVector = jweParts[2];
        String encodedCipherText = jweParts[3];
        String encodedIntegrityValue = jweParts[4];

        jwe.setEncodedHeader(encodedHeader);
        jwe.setEncodedEncryptedKey(encodedEncryptedKey);
        jwe.setEncodedInitializationVector(encodedInitializationVector);
        jwe.setEncodedCiphertext(encodedCipherText);
        jwe.setEncodedIntegrityValue(encodedIntegrityValue);
        jwe.setHeader(new JwtHeader(encodedHeader));

        return jwe;
    } catch (Exception e) {
        throw new InvalidJweException(e);
    }
}
 
Example 17
Source Project: oxd   Source File: RpGetRptTest.java    License: Apache License 2.0 5 votes vote down vote up
@Parameters({"host", "opHost", "redirectUrls", "rsProtect"})
@Test
public void rptAsJwt(String host, String opHost, String redirectUrls, String rsProtect) throws IOException, InvalidJwtException {

    ClientInterface client = Tester.newClient(host);

    final RegisterSiteParams params = new RegisterSiteParams();
    params.setOpHost(opHost);
    params.setRedirectUris(Lists.newArrayList(redirectUrls.split(" ")));
    params.setPostLogoutRedirectUris(Lists.newArrayList(redirectUrls.split(" ")));
    params.setClientFrontchannelLogoutUris(Lists.newArrayList(redirectUrls.split(" ")));
    params.setScope(Lists.newArrayList("openid", "uma_protection", "profile", "oxd"));
    params.setRptAsJwt(true);
    params.setGrantTypes(Lists.newArrayList(
            GrantType.AUTHORIZATION_CODE.getValue(),
            GrantType.OXAUTH_UMA_TICKET.getValue(),
            GrantType.CLIENT_CREDENTIALS.getValue()));

    final RegisterSiteResponse site = client.registerSite(params);
    assertNotNull(site);
    assertTrue(!Strings.isNullOrEmpty(site.getOxdId()));

    final RpGetRptResponse response = requestRpt(client, site, rsProtect);
    assertNotNull(response);

    Jwt jwt = Jwt.parse(response.getRpt());
    assertNotNull(jwt);
    assertEquals(site.getClientId(), jwt.getClaims().getClaimAsString("client_id"));
    assertTrue(jwt.getClaims().getClaimAsString("permissions").contains("resource_id"));
}
 
Example 18
Source Project: oxd   Source File: AccessTokenAsJwtTest.java    License: Apache License 2.0 5 votes vote down vote up
@Parameters({"host", "opHost", "redirectUrls", "postLogoutRedirectUrls"})
@Test
public void getClientToken(String host, String opHost, String redirectUrls, String postLogoutRedirectUrls) throws InvalidJwtException {
    final RegisterSiteParams params = new RegisterSiteParams();
    params.setOpHost(opHost);
    params.setRedirectUris(Lists.newArrayList(redirectUrls.split(" ")));
    params.setPostLogoutRedirectUris(Lists.newArrayList(postLogoutRedirectUrls.split(" ")));
    params.setScope(Lists.newArrayList("openid", "uma_protection", "profile"));
    params.setAccessTokenAsJwt(true);
    params.setGrantTypes(Lists.newArrayList(
            GrantType.AUTHORIZATION_CODE.getValue(),
            GrantType.CLIENT_CREDENTIALS.getValue()));

    final RegisterSiteResponse resp = org.gluu.oxd.server.Tester.newClient(host).registerSite(params);
    assertResponse(resp);

    final GetClientTokenParams tokenParams = new GetClientTokenParams();
    tokenParams.setOpHost(opHost);
    tokenParams.setScope(Lists.newArrayList("openid"));
    tokenParams.setClientId(resp.getClientId());
    tokenParams.setClientSecret(resp.getClientSecret());

    GetClientTokenResponse tokenResponse = org.gluu.oxd.server.Tester.newClient(host).getClientToken(tokenParams);

    assertNotNull(tokenResponse);
    notEmpty(tokenResponse.getAccessToken());

    final Jwt parse = Jwt.parse(tokenResponse.getAccessToken());
    assertNotNull(parse);
    System.out.println("access token as JWT: " + tokenResponse.getAccessToken() + ", claims: " + parse.getClaims());
}
 
Example 19
Source Project: oxd   Source File: ValidatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void tokenWithMultiAudAndAzp_shouldBeValid() throws InvalidJwtException {
    //"aud": ["6b578a9b-7513-477a-9a7f-1343b487caf8","another_aud"],
    //"azp":"6b578a9b-7513-477a-9a7f-1343b487caf8"
    final Jwt idToken = Jwt.parse("eyJraWQiOiJjZmFiMzRlYy0xNjhkLTQ4OTUtODRiOC0xZjAyNzgwNDkxYzciLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdF9oYXNoIjoiMnI1clZ2STdpMWxfcnNXZUV4bGRuUSIsImF1ZCI6WyI2YjU3OGE5Yi03NTEzLTQ3N2EtOWE3Zi0xMzQzYjQ4N2NhZjgiLCJhbm90aGVyX2F1ZCJdLCJhenAiOiI2YjU3OGE5Yi03NTEzLTQ3N2EtOWE3Zi0xMzQzYjQ4N2NhZjgiLCJzdWIiOiJzLV9aaXJWdDdOT0RkbldEQVVHcmpUMnFVWndLNmNYVGhiOXFWOTl2LXRnIiwiYXV0aF90aW1lIjoxNTY4MTg1MzI3LCJpc3MiOiJodHRwczovL2R1bW15LWlzc3Vlci5vcmciLCJleHAiOjE5NjgxODg5MzAsImlhdCI6MTU2ODE4NTMzMCwibm9uY2UiOiI3cjQ2dXQ2ZW11OWdpMTFnbjgwNDR1bTY0MCIsIm94T3BlbklEQ29ubmVjdFZlcnNpb24iOiJvcGVuaWRjb25uZWN0LTEuMCJ9.Q1WsYrrMx4Uo7ZT5X840yuPljdRM5AU1otNAlc7-XcCUWB2yzdHZ5ptNdcGUEKr3bHLN4f-YyBC4n6Yea60eFxTkjXKGpGJESRU690xJ_OHb69DzHXiRnbtBRcHRMUgra5CBC4WNqyTRc0SBJFGOVuNAceNyVLSP7zPXgGNQHcA");
    String clientId = "6b578a9b-7513-477a-9a7f-1343b487caf8";
    try {
        Validator.validateAudience(idToken, clientId);
    } catch (Exception e) {
        assertFalse(e instanceof HttpException);
    }
}
 
Example 20
Source Project: oxd   Source File: ValidatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void tokenWithSingleAudArrayAndNoAzp_shouldBeValid() throws InvalidJwtException {
    //"aud": ["6b578a9b-7513-477a-9a7f-1343b487caf8"],
    final Jwt idToken = Jwt.parse("eyJraWQiOiJjZmFiMzRlYy0xNjhkLTQ4OTUtODRiOC0xZjAyNzgwNDkxYzciLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdF9oYXNoIjoiMnI1clZ2STdpMWxfcnNXZUV4bGRuUSIsImF1ZCI6WyI2YjU3OGE5Yi03NTEzLTQ3N2EtOWE3Zi0xMzQzYjQ4N2NhZjgiXSwic3ViIjoicy1fWmlyVnQ3Tk9EZG5XREFVR3JqVDJxVVp3SzZjWFRoYjlxVjk5di10ZyIsImF1dGhfdGltZSI6MTU2ODE4NTMyNywiaXNzIjoiaHR0cHM6Ly9kdW1teS1pc3N1ZXIub3JnIiwiZXhwIjoxOTY4MTg4OTMwLCJpYXQiOjE1NjgxODUzMzAsIm5vbmNlIjoiN3I0NnV0NmVtdTlnaTExZ244MDQ0dW02NDAiLCJveE9wZW5JRENvbm5lY3RWZXJzaW9uIjoib3BlbmlkY29ubmVjdC0xLjAifQ.cP6DGPkYYnzDTHrH04F4Q48cPqH2T4R4RjGJmLr5QGA1pUYOOxvLj8Ak0EqmzV_83Zy0wgvyzFCv0xdi06BguUgnM4u6LL8V0hLzrdHIwJHvz5L5Gqbvs5Vg61CpP409lo0sHUN08zfN_WU3EWXK6JlSvFtE59jWSJWBF5pmLX4");
    String clientId = "6b578a9b-7513-477a-9a7f-1343b487caf8";
    try {
        Validator.validateAudience(idToken, clientId);
    } catch (Exception e) {
        assertFalse(e instanceof HttpException);
    }
}
 
Example 21
Source Project: oxd   Source File: ValidatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void tokenWithSingleAudStringAndNoAzp_shouldBeValid() throws InvalidJwtException {
    //"aud": "6b578a9b-7513-477a-9a7f-1343b487caf8",
    final Jwt idToken = Jwt.parse("eyJraWQiOiJjZmFiMzRlYy0xNjhkLTQ4OTUtODRiOC0xZjAyNzgwNDkxYzciLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdF9oYXNoIjoiMnI1clZ2STdpMWxfcnNXZUV4bGRuUSIsImF1ZCI6IjZiNTc4YTliLTc1MTMtNDc3YS05YTdmLTEzNDNiNDg3Y2FmOCIsInN1YiI6InMtX1ppclZ0N05PRGRuV0RBVUdyalQycVVad0s2Y1hUaGI5cVY5OXYtdGciLCJhdXRoX3RpbWUiOjE1NjgxODUzMjcsImlzcyI6Imh0dHBzOi8vZHVtbXktaXNzdWVyLm9yZyIsImV4cCI6MTk2ODE4ODkzMCwiaWF0IjoxNTY4MTg1MzMwLCJub25jZSI6IjdyNDZ1dDZlbXU5Z2kxMWduODA0NHVtNjQwIiwib3hPcGVuSURDb25uZWN0VmVyc2lvbiI6Im9wZW5pZGNvbm5lY3QtMS4wIn0.PqnRiAhXqdeTbW1_JdRl6rLDMn36ists9Eq1n_2vOKYjGs_VxxkcdQfCt93KfC3WqEObhjlKDzwp6YUXi_7Wqta58ftUz0FU2jB7np3mq5m8lY_hKVhoZJMvxzMbCkiH-8jwtq9MZKEw3qyrwQEHQ0l21tograWD80gRedaQuD4");
    String clientId = "6b578a9b-7513-477a-9a7f-1343b487caf8";
    try {
        Validator.validateAudience(idToken, clientId);
    } catch (Exception e) {
        assertFalse(e instanceof HttpException);
    }
}
 
Example 22
Source Project: oxd   Source File: ValidatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void tokenWithAudArrayStringWithOneElement_shouldBeValid() throws InvalidJwtException {
    //"aud": "[\"6b578a9b-7513-477a-9a7f-1343b487caf8\"]",
    final Jwt idToken = Jwt.parse("eyJraWQiOiJjZmFiMzRlYy0xNjhkLTQ4OTUtODRiOC0xZjAyNzgwNDkxYzciLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdF9oYXNoIjoiMnI1clZ2STdpMWxfcnNXZUV4bGRuUSIsImF1ZCI6IltcIjZiNTc4YTliLTc1MTMtNDc3YS05YTdmLTEzNDNiNDg3Y2FmOFwiXSIsInN1YiI6InMtX1ppclZ0N05PRGRuV0RBVUdyalQycVVad0s2Y1hUaGI5cVY5OXYtdGciLCJhdXRoX3RpbWUiOjE1NjgxODUzMjcsImlzcyI6Imh0dHBzOi8vZHVtbXktaXNzdWVyLm9yZyIsImV4cCI6MTk2ODE4ODkzMCwiaWF0IjoxNTY4MTg1MzMwLCJub25jZSI6IjdyNDZ1dDZlbXU5Z2kxMWduODA0NHVtNjQwIiwib3hPcGVuSURDb25uZWN0VmVyc2lvbiI6Im9wZW5pZGNvbm5lY3QtMS4wIn0.bFgbYtgt5OA2hdwAXXCwaVMUYprArsGoURJgaA0d-YfsDYu8HU9zVDraDhflSc2Wg9uMv4RAKqEfldDwLIRIocGk5XwjyeOHFAWAlDMeDSPUAWy7d7oNGwPrRNZu37RUT1ncRS9ZAIsOhtJjflUTD0J12DeD-wT_V6Jpv8jn3Mo");
    String clientId = "6b578a9b-7513-477a-9a7f-1343b487caf8";
    try {
        Validator.validateAudience(idToken, clientId);
    } catch (Exception e) {
        assertFalse(e instanceof HttpException);
    }
}
 
Example 23
Source Project: oxd   Source File: ValidatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void tokenWithAudArrayStringWithMultiElements_shouldBeValid() throws InvalidJwtException {
    //"aud": "[\"6b578a9b-7513-477a-9a7f-1343b487caf8\",\"another_element\"]",
    final Jwt idToken = Jwt.parse("eyJraWQiOiJjZmFiMzRlYy0xNjhkLTQ4OTUtODRiOC0xZjAyNzgwNDkxYzciLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdF9oYXNoIjoiMnI1clZ2STdpMWxfcnNXZUV4bGRuUSIsImF1ZCI6IltcIjZiNTc4YTliLTc1MTMtNDc3YS05YTdmLTEzNDNiNDg3Y2FmOFwiLFwiYW5vdGhlcl9lbGVtZW50XCJdIiwic3ViIjoicy1fWmlyVnQ3Tk9EZG5XREFVR3JqVDJxVVp3SzZjWFRoYjlxVjk5di10ZyIsImF1dGhfdGltZSI6MTU2ODE4NTMyNywiaXNzIjoiaHR0cHM6Ly9kdW1teS1pc3N1ZXIub3JnIiwiZXhwIjoxOTY4MTg4OTMwLCJpYXQiOjE1NjgxODUzMzAsIm5vbmNlIjoiN3I0NnV0NmVtdTlnaTExZ244MDQ0dW02NDAiLCJveE9wZW5JRENvbm5lY3RWZXJzaW9uIjoib3BlbmlkY29ubmVjdC0xLjAifQ.Z185fBjN4B6ghJaF7Szvvwq2_aNK8xnBdJWY_jZtSrb4DMqB8kXkEF9c11eIldt2fY3lj3cEPUIBjvW9-Bye-ClfGgqZ7eXGCXOEQ3pNdTV0YDSJDMjYOSTAnmeccx8hUsqKbSd0JoZUzaDWZgLYxXX1GodV_V_Nx_Xr3rWGGrc");
    String clientId = "6b578a9b-7513-477a-9a7f-1343b487caf8";
    try {
        Validator.validateAudience(idToken, clientId);
    } catch (Exception e) {
        assertFalse(e instanceof HttpException);
    }
}
 
Example 24
Source Project: oxTrust   Source File: Authenticator.java    License: MIT License 4 votes vote down vote up
private String requestAccessToken(String oxAuthHost, String authorizationCode, String sessionState, String scopes,
		String clientID, String clientPassword) {
	OpenIdConfigurationResponse openIdConfiguration = openIdService.getOpenIdConfiguration();
	// 1. Request access token using the authorization code.
	TokenClient tokenClient1 = new TokenClient(openIdConfiguration.getTokenEndpoint());

	log.info("Sending request to token endpoint");
	String redirectURL = appConfiguration.getLoginRedirectUrl();
	log.info("redirectURI : " + redirectURL);
	TokenResponse tokenResponse = tokenClient1.execAuthorizationCode(authorizationCode, redirectURL, clientID,
			clientPassword);

	log.debug(" tokenResponse : " + tokenResponse);
	if (tokenResponse == null) {
		log.error("Get empty token response. User rcan't log into application");
		return OxTrustConstants.RESULT_NO_PERMISSIONS;
	}

	log.debug(" tokenResponse.getErrorType() : " + tokenResponse.getErrorType());

	String accessToken = tokenResponse.getAccessToken();
	log.debug(" accessToken : " + accessToken);

	String idToken = tokenResponse.getIdToken();
	log.debug(" idToken : " + idToken);

	if (idToken == null) {
		log.error("Failed to get id_token");
		return OxTrustConstants.RESULT_NO_PERMISSIONS;
	}

	log.info("Session validation successful. User is logged in");
	UserInfoClient userInfoClient = new UserInfoClient(openIdConfiguration.getUserInfoEndpoint());
	UserInfoResponse userInfoResponse = userInfoClient.execUserInfo(accessToken);
	if (userInfoResponse == null) {
		log.error("Get empty token response. User can't log into application");
		return OxTrustConstants.RESULT_NO_PERMISSIONS;
	}

	// Parse JWT
	Jwt jwt;
	try {
		jwt = Jwt.parse(idToken);
	} catch (InvalidJwtException ex) {
		log.error("Failed to parse id_token");
		return OxTrustConstants.RESULT_NO_PERMISSIONS;
	}

	// Check nonce
	String nonceResponse = (String) jwt.getClaims().getClaim(JwtClaimName.NONCE);
	String nonceSession = (String) identity.getSessionMap().get(OxTrustConstants.OXAUTH_NONCE);
	if (!StringHelper.equals(nonceSession, nonceResponse)) {
		log.error("User info response :  nonce is not matching.");
		return OxTrustConstants.RESULT_NO_PERMISSIONS;
	}

	// Determine uid
	List<String> uidValues = userInfoResponse.getClaims().get(JwtClaimName.USER_NAME);
	if ((uidValues == null) || (uidValues.size() == 0)) {
		log.error("User info response doesn't contains uid claim");
		return OxTrustConstants.RESULT_NO_PERMISSIONS;
	}
	// Check requested authentication method
	if (identity.getSessionMap().containsKey(OxTrustConstants.OXAUTH_ACR_VALUES)) {
		String requestAcrValues = (String) identity.getSessionMap().get(OxTrustConstants.OXAUTH_ACR_VALUES);
		String issuer = openIdConfiguration.getIssuer();
		String responseIssuer = (String) jwt.getClaims().getClaim(JwtClaimName.ISSUER);
		if (issuer == null || responseIssuer == null || !issuer.equals(responseIssuer)) {
			log.error("User info response :  Issuer.");
			return OxTrustConstants.RESULT_NO_PERMISSIONS;
		}

		List<String> acrValues = jwt.getClaims()
				.getClaimAsStringList(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE);
		if ((acrValues == null) || (acrValues.size() == 0) || !acrValues.contains(requestAcrValues)) {
			log.error("User info response doesn't contains acr claim");
			return OxTrustConstants.RESULT_NO_PERMISSIONS;
		}
		if (!acrValues.contains(requestAcrValues)) {
			log.error("User info response contains acr='{}' claim but expected acr='{}'", acrValues,
					requestAcrValues);
			return OxTrustConstants.RESULT_NO_PERMISSIONS;
		}
	}
	OauthData oauthData = identity.getOauthData();
	oauthData.setHost(oxAuthHost);
	oauthData.setUserUid(uidValues.get(0));
	oauthData.setAccessToken(accessToken);
	oauthData.setAccessTokenExpirationInSeconds(tokenResponse.getExpiresIn());
	oauthData.setScopes(scopes);
	oauthData.setIdToken(idToken);
	oauthData.setSessionState(sessionState);
	identity.setWorkingParameter(OxTrustConstants.OXAUTH_SSO_SESSION_STATE, Boolean.FALSE);
	log.info("user uid:" + oauthData.getUserUid());

	String result = authenticate();

	return result;
}
 
Example 25
Source Project: oxAuth   Source File: ClientAssertion.java    License: MIT License 4 votes vote down vote up
private boolean load(AppConfiguration appConfiguration, AbstractCryptoProvider cryptoProvider, String clientId, ClientAssertionType clientAssertionType, String encodedAssertion)
        throws Exception {
    boolean result;

    if (clientAssertionType == ClientAssertionType.JWT_BEARER) {
        if (StringUtils.isNotBlank(encodedAssertion)) {
            jwt = Jwt.parse(encodedAssertion);

            // TODO: Store jti this value to check for duplicates

            // Validate clientId
            String issuer = jwt.getClaims().getClaimAsString(JwtClaimName.ISSUER);
            String subject = jwt.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER);
            List<String> audience = jwt.getClaims().getClaimAsStringList(JwtClaimName.AUDIENCE);
            Date expirationTime = jwt.getClaims().getClaimAsDate(JwtClaimName.EXPIRATION_TIME);
            //SignatureAlgorithm algorithm = SignatureAlgorithm.fromName(jwt.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM));
            if ((clientId == null && StringUtils.isNotBlank(issuer) && StringUtils.isNotBlank(subject) && issuer.equals(subject))
                    || (StringUtils.isNotBlank(clientId) && StringUtils.isNotBlank(issuer)
                    && StringUtils.isNotBlank(subject) && clientId.equals(issuer) && issuer.equals(subject))) {

                // Validate audience
                String tokenUrl = appConfiguration.getTokenEndpoint();
                String cibaAuthUrl = appConfiguration.getBackchannelAuthenticationEndpoint();
                if (audience != null && (audience.contains(appConfiguration.getIssuer()) || audience.contains(tokenUrl) || audience.contains(cibaAuthUrl))) {

                    // Validate expiration
                    if (expirationTime.after(new Date())) {
                        ClientService clientService = CdiUtil.bean(ClientService.class);
                        Client client = clientService.getClient(subject);

                        // Validate client
                        if (client != null) {
                            JwtType jwtType = JwtType.fromString(jwt.getHeader().getClaimAsString(JwtHeaderName.TYPE));
                            AuthenticationMethod authenticationMethod = client.getAuthenticationMethod();
                            SignatureAlgorithm signatureAlgorithm = jwt.getHeader().getSignatureAlgorithm();

                            if (jwtType == null && signatureAlgorithm != null) {
                                jwtType = signatureAlgorithm.getJwtType();
                            }

                            if (jwtType != null && signatureAlgorithm != null && signatureAlgorithm.getFamily() != null &&
                                    ((authenticationMethod == AuthenticationMethod.CLIENT_SECRET_JWT && AlgorithmFamily.HMAC.equals(signatureAlgorithm.getFamily()))
                                            || (authenticationMethod == AuthenticationMethod.PRIVATE_KEY_JWT && (AlgorithmFamily.RSA.equals(signatureAlgorithm.getFamily()) || AlgorithmFamily.EC.equals(signatureAlgorithm.getFamily()))))) {
                                if (client.getTokenEndpointAuthSigningAlg() == null || SignatureAlgorithm.fromString(client.getTokenEndpointAuthSigningAlg()).equals(signatureAlgorithm)) {
                                    clientSecret = clientService.decryptSecret(client.getClientSecret());

                                    // Validate the crypto segment
                                    String keyId = jwt.getHeader().getKeyId();
                                    JSONObject jwks = Strings.isNullOrEmpty(client.getJwks()) ?
                                            JwtUtil.getJSONWebKeys(client.getJwksUri()) :
                                            new JSONObject(client.getJwks());
                                    String sharedSecret = clientService.decryptSecret(client.getClientSecret());
                                    boolean validSignature = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(),
                                            keyId, jwks, sharedSecret, signatureAlgorithm);

                                    if (validSignature) {
                                        result = true;
                                    } else {
                                        throw new InvalidJwtException("Invalid cryptographic segment");
                                    }
                                } else {
                                    throw new InvalidJwtException("Invalid signing algorithm");
                                }
                            } else {
                                throw new InvalidJwtException("Invalid authentication method");
                            }
                        } else {
                            throw new InvalidJwtException("Invalid client");
                        }
                    } else {
                        throw new InvalidJwtException("JWT has expired");
                    }
                } else {
                    throw new InvalidJwtException("Invalid audience: " + audience);
                }
            } else {
                throw new InvalidJwtException("Invalid clientId");
            }
        } else {
            throw new InvalidJwtException("The Client Assertion is null or empty");
        }
    } else {
        throw new InvalidJwtException("Invalid Client Assertion Type");
    }

    return result;
}
 
Example 26
Source Project: oxAuth   Source File: CrossEncryptionTest.java    License: MIT License 4 votes vote down vote up
private void decryptAndValidateSignatureWithGluu(String jweString) throws ParseException, JOSEException, InvalidJweException, JSONException, InvalidJwtException {
    JWK jwk = JWK.parse(recipientJwkJson);
    RSAPrivateKey rsaPrivateKey = ((RSAKey) jwk).toRSAPrivateKey();

    JweDecrypterImpl decrypter = new JweDecrypterImpl(rsaPrivateKey);

    decrypter.setKeyEncryptionAlgorithm(KeyEncryptionAlgorithm.RSA_OAEP);
    decrypter.setBlockEncryptionAlgorithm(BlockEncryptionAlgorithm.A128GCM);

    final Jwe jwe = decrypter.decrypt(jweString);
    assertEquals(JwtType.JWT, jwe.getHeader().getContentType());

    final Jwt jwt = jwe.getSignedJWTPayload();

    final RSAPublicKey senderPublicKey = RSAKeyFactory.valueOf(getSenderWebKey()).getPublicKey();
    Assert.assertTrue(new RSASigner(SignatureAlgorithm.RS256, senderPublicKey).validate(jwt));

    System.out.println("Gluu decrypt and nested jwt signature verification succeed: " + jwt.getClaims().toJsonString());
}
 
Example 27
Source Project: oxAuth   Source File: JwtClaims.java    License: MIT License 4 votes vote down vote up
public JwtClaims(String base64JsonObject) throws InvalidJwtException {
    super(base64JsonObject);
}
 
Example 28
Source Project: oxAuth   Source File: JwtClaimSet.java    License: MIT License 4 votes vote down vote up
public JwtClaimSet(String base64JsonObject) throws InvalidJwtException {
    this();
    load(base64JsonObject);
}
 
Example 29
Source Project: oxAuth   Source File: JwtHeader.java    License: MIT License 4 votes vote down vote up
public JwtHeader(String base64JsonObject) throws InvalidJwtException {
    super(base64JsonObject);
}
 
Example 30
Source Project: oxAuth   Source File: AbstractJwsSigner.java    License: MIT License 4 votes vote down vote up
@Override
public Jwt sign(Jwt jwt) throws InvalidJwtException, SignatureException {
    String signature = generateSignature(jwt.getSigningInput());
    jwt.setEncodedSignature(signature);
    return jwt;
}