Search in sources :

Example 1 with InvalidJwtException

use of org.xdi.oxauth.model.exception.InvalidJwtException in project oxAuth by GluuFederation.

the class UserInfoRestWebServiceEmbeddedTest method requestUserInfoHS512Step3.

@Parameters({ "userInfoPath" })
@Test(dependsOnMethods = "requestUserInfoHS512Step2")
public void requestUserInfoHS512Step3(final String userInfoPath) throws Exception {
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + userInfoPath).request();
    request.header("Authorization", "Bearer " + accessToken7);
    request.header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
    UserInfoRequest userInfoRequest = new UserInfoRequest(null);
    Response response = request.post(Entity.form(new MultivaluedHashMap<String, String>(userInfoRequest.getParameters())));
    String entity = response.readEntity(String.class);
    showResponse("requestUserInfoHS512Step3", response, entity);
    assertEquals(response.getStatus(), 200, "Unexpected response code.");
    assertTrue(response.getHeaderString("Cache-Control") != null && response.getHeaderString("Cache-Control").equals("no-store, private"), "Unexpected result: " + response.getHeaderString("Cache-Control"));
    assertTrue(response.getHeaderString("Pragma") != null && response.getHeaderString("Pragma").equals("no-cache"), "Unexpected result: " + response.getHeaderString("Pragma"));
    assertNotNull(entity, "Unexpected result: " + entity);
    try {
        Jwt jwt = Jwt.parse(entity);
        assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER));
        assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.NAME));
        assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.EMAIL));
        assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.PICTURE));
    } catch (InvalidJwtException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
Also used : RegisterResponse(org.xdi.oxauth.client.RegisterResponse) Response(javax.ws.rs.core.Response) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) InvalidJwtException(org.xdi.oxauth.model.exception.InvalidJwtException) Jwt(org.xdi.oxauth.model.jwt.Jwt) Builder(javax.ws.rs.client.Invocation.Builder) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) UserInfoRequest(org.xdi.oxauth.client.UserInfoRequest) URISyntaxException(java.net.URISyntaxException) InvalidJwtException(org.xdi.oxauth.model.exception.InvalidJwtException) JSONException(org.codehaus.jettison.json.JSONException) Parameters(org.testng.annotations.Parameters) Test(org.testng.annotations.Test) BaseTest(org.xdi.oxauth.BaseTest)

Example 2 with InvalidJwtException

use of org.xdi.oxauth.model.exception.InvalidJwtException in project oxAuth by GluuFederation.

the class AbstractJweEncrypter method encrypt.

@Override
public Jwe encrypt(Jwe jwe) throws InvalidJweException {
    try {
        jwe.setEncodedHeader(jwe.getHeader().toBase64JsonObject());
        byte[] contentMasterKey = new byte[blockEncryptionAlgorithm.getCmkLength() / 8];
        SecureRandom random = new SecureRandom();
        random.nextBytes(contentMasterKey);
        String encodedEncryptedKey = generateEncryptedKey(contentMasterKey);
        jwe.setEncodedEncryptedKey(encodedEncryptedKey);
        byte[] initializationVector = new byte[blockEncryptionAlgorithm.getInitVectorLength() / 8];
        random.nextBytes(initializationVector);
        String encodedInitializationVector = Base64Util.base64urlencode(initializationVector);
        jwe.setEncodedInitializationVector(encodedInitializationVector);
        Pair<String, String> result = generateCipherTextAndIntegrityValue(contentMasterKey, initializationVector, jwe.getAdditionalAuthenticatedData().getBytes(Util.UTF8_STRING_ENCODING), jwe.getClaims().toBase64JsonObject().getBytes(Util.UTF8_STRING_ENCODING));
        jwe.setEncodedCiphertext(result.getFirst());
        jwe.setEncodedIntegrityValue(result.getSecond());
        return jwe;
    } catch (InvalidJwtException e) {
        throw new InvalidJweException(e);
    } catch (UnsupportedEncodingException e) {
        throw new InvalidJweException(e);
    }
}
Also used : InvalidJwtException(org.xdi.oxauth.model.exception.InvalidJwtException) SecureRandom(java.security.SecureRandom) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InvalidJweException(org.xdi.oxauth.model.exception.InvalidJweException)

Example 3 with InvalidJwtException

use of org.xdi.oxauth.model.exception.InvalidJwtException in project oxAuth by GluuFederation.

the class JwtClaimSet method load.

public void load(String base64JsonObject) throws InvalidJwtException {
    try {
        String jsonObjectString = new String(Base64Util.base64urldecode(base64JsonObject), Util.UTF8_STRING_ENCODING);
        load(new JSONObject(jsonObjectString));
    } catch (UnsupportedEncodingException e) {
        throw new InvalidJwtException(e);
    } catch (JSONException e) {
        throw new InvalidJwtException(e);
    } catch (Exception e) {
        throw new InvalidJwtException(e);
    }
}
Also used : InvalidJwtException(org.xdi.oxauth.model.exception.InvalidJwtException) JSONObject(org.codehaus.jettison.json.JSONObject) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JSONException(org.codehaus.jettison.json.JSONException) JSONException(org.codehaus.jettison.json.JSONException) InvalidJwtException(org.xdi.oxauth.model.exception.InvalidJwtException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 4 with InvalidJwtException

use of org.xdi.oxauth.model.exception.InvalidJwtException in project oxAuth by GluuFederation.

the class JwtClaimSet method toMap.

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;
}
Also used : InvalidJwtException(org.xdi.oxauth.model.exception.InvalidJwtException) JSONArray(org.codehaus.jettison.json.JSONArray) JSONException(org.codehaus.jettison.json.JSONException) java.util(java.util) JSONObject(org.codehaus.jettison.json.JSONObject)

Example 5 with InvalidJwtException

use of org.xdi.oxauth.model.exception.InvalidJwtException in project oxAuth by GluuFederation.

the class UserInfoRestWebServiceImpl method requestUserInfo.

public Response requestUserInfo(String accessToken, String authorization, HttpServletRequest request, SecurityContext securityContext) {
    if (authorization != null && !authorization.isEmpty() && authorization.startsWith("Bearer ")) {
        accessToken = authorization.substring(7);
    }
    log.debug("Attempting to request User Info, Access token = {}, Is Secure = {}", accessToken, securityContext.isSecure());
    Response.ResponseBuilder builder = Response.ok();
    OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(request), Action.USER_INFO);
    try {
        if (!UserInfoParamsValidator.validateParams(accessToken)) {
            builder = Response.status(400);
            builder.entity(errorResponseFactory.getErrorAsJson(UserInfoErrorResponseType.INVALID_REQUEST));
        } else {
            AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(accessToken);
            if (authorizationGrant == null) {
                builder = Response.status(400);
                builder.entity(errorResponseFactory.getErrorAsJson(UserInfoErrorResponseType.INVALID_TOKEN));
            } else if (authorizationGrant.getAuthorizationGrantType() == AuthorizationGrantType.CLIENT_CREDENTIALS) {
                builder = Response.status(403);
                builder.entity(errorResponseFactory.getErrorAsJson(UserInfoErrorResponseType.INSUFFICIENT_SCOPE));
            } else if (!authorizationGrant.getScopes().contains(DefaultScope.OPEN_ID.toString()) && !authorizationGrant.getScopes().contains(DefaultScope.PROFILE.toString())) {
                builder = Response.status(403);
                builder.entity(errorResponseFactory.getErrorAsJson(UserInfoErrorResponseType.INSUFFICIENT_SCOPE));
                oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, false);
            } else {
                oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, true);
                CacheControl cacheControl = new CacheControl();
                cacheControl.setPrivate(true);
                cacheControl.setNoTransform(false);
                cacheControl.setNoStore(true);
                builder.cacheControl(cacheControl);
                builder.header("Pragma", "no-cache");
                User currentUser = authorizationGrant.getUser();
                try {
                    currentUser = userService.getUserByDn(authorizationGrant.getUserDn());
                } catch (EntryPersistenceException ex) {
                    log.warn("Failed to reload user entry: '{}'", authorizationGrant.getUserDn());
                }
                if (authorizationGrant.getClient() != null && authorizationGrant.getClient().getUserInfoEncryptedResponseAlg() != null && authorizationGrant.getClient().getUserInfoEncryptedResponseEnc() != null) {
                    KeyEncryptionAlgorithm keyEncryptionAlgorithm = KeyEncryptionAlgorithm.fromName(authorizationGrant.getClient().getUserInfoEncryptedResponseAlg());
                    BlockEncryptionAlgorithm blockEncryptionAlgorithm = BlockEncryptionAlgorithm.fromName(authorizationGrant.getClient().getUserInfoEncryptedResponseEnc());
                    builder.type("application/jwt");
                    builder.entity(getJweResponse(keyEncryptionAlgorithm, blockEncryptionAlgorithm, currentUser, authorizationGrant, authorizationGrant.getScopes()));
                } else if (authorizationGrant.getClient() != null && authorizationGrant.getClient().getUserInfoSignedResponseAlg() != null) {
                    SignatureAlgorithm algorithm = SignatureAlgorithm.fromString(authorizationGrant.getClient().getUserInfoSignedResponseAlg());
                    builder.type("application/jwt");
                    builder.entity(getJwtResponse(algorithm, currentUser, authorizationGrant, authorizationGrant.getScopes()));
                } else {
                    builder.type((MediaType.APPLICATION_JSON + ";charset=UTF-8"));
                    builder.entity(getJSonResponse(currentUser, authorizationGrant, authorizationGrant.getScopes()));
                }
            }
        }
    } catch (StringEncrypter.EncryptionException e) {
        // 500
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
        log.error(e.getMessage(), e);
    } catch (InvalidJwtException e) {
        // 500
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
        log.error(e.getMessage(), e);
    } catch (SignatureException e) {
        // 500
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
        log.error(e.getMessage(), e);
    } catch (InvalidClaimException e) {
        // 500
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
        log.error(e.getMessage(), e);
    } catch (Exception e) {
        // 500
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
        log.error(e.getMessage(), e);
    }
    applicationAuditLogger.sendMessage(oAuth2AuditLog);
    return builder.build();
}
Also used : InvalidJwtException(org.xdi.oxauth.model.exception.InvalidJwtException) OAuth2AuditLog(org.xdi.oxauth.model.audit.OAuth2AuditLog) EntryPersistenceException(org.gluu.site.ldap.persistence.exception.EntryPersistenceException) SignatureAlgorithm(org.xdi.oxauth.model.crypto.signature.SignatureAlgorithm) SignatureException(java.security.SignatureException) InvalidClaimException(org.xdi.oxauth.model.exception.InvalidClaimException) StringEncrypter(org.xdi.util.security.StringEncrypter) InvalidJwtException(org.xdi.oxauth.model.exception.InvalidJwtException) SignatureException(java.security.SignatureException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InvalidClaimException(org.xdi.oxauth.model.exception.InvalidClaimException) EntryPersistenceException(org.gluu.site.ldap.persistence.exception.EntryPersistenceException) InvalidJweException(org.xdi.oxauth.model.exception.InvalidJweException) BlockEncryptionAlgorithm(org.xdi.oxauth.model.crypto.encryption.BlockEncryptionAlgorithm) JsonWebResponse(org.xdi.oxauth.model.token.JsonWebResponse) Response(javax.ws.rs.core.Response) KeyEncryptionAlgorithm(org.xdi.oxauth.model.crypto.encryption.KeyEncryptionAlgorithm) CacheControl(javax.ws.rs.core.CacheControl)

Aggregations

InvalidJwtException (org.xdi.oxauth.model.exception.InvalidJwtException)17 JSONException (org.codehaus.jettison.json.JSONException)7 UnsupportedEncodingException (java.io.UnsupportedEncodingException)6 URISyntaxException (java.net.URISyntaxException)5 Response (javax.ws.rs.core.Response)5 InvalidJweException (org.xdi.oxauth.model.exception.InvalidJweException)5 Jwt (org.xdi.oxauth.model.jwt.Jwt)5 SignatureException (java.security.SignatureException)4 Builder (javax.ws.rs.client.Invocation.Builder)4 JSONObject (org.codehaus.jettison.json.JSONObject)4 ResteasyClientBuilder (org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder)4 Parameters (org.testng.annotations.Parameters)4 Test (org.testng.annotations.Test)4 BaseTest (org.xdi.oxauth.BaseTest)4 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)3 RegisterResponse (org.xdi.oxauth.client.RegisterResponse)3 UserInfoRequest (org.xdi.oxauth.client.UserInfoRequest)3 OAuth2AuditLog (org.xdi.oxauth.model.audit.OAuth2AuditLog)3 URI (java.net.URI)2 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)2