Search in sources :

Example 21 with IdRepoException

use of com.sun.identity.idm.IdRepoException in project OpenAM by OpenRock.

the class WSSReplayPasswd method onLoginSuccess.

/** 
     * Post processing on successful authentication.
     * @param requestParamsMap contains HttpServletRequest parameters
     * @param request HttpServlet  request
     * @param response HttpServlet response
     * @param ssoToken user's session
     * @throws AuthenticationException if there is an error while setting
     * the session paswword property
     */
public void onLoginSuccess(Map requestParamsMap, HttpServletRequest request, HttpServletResponse response, SSOToken ssoToken) throws AuthenticationException {
    try {
        if (!useHashedPassword) {
            String userpasswd = request.getParameter(PASSWORD_TOKEN);
            if (userpasswd != null) {
                ssoToken.setProperty("EncryptedUserPassword", Crypt.encrypt(userpasswd));
            }
        } else {
            String userName = ssoToken.getPrincipal().getName();
            String universalID = ssoToken.getProperty("sun.am.UniversalIdentifier");
            if (debug.messageEnabled()) {
                debug.message("WSSReplayPassword:Authenticated user : " + userName);
                debug.message("WSSReplayPassword:Authenticated UUID : " + universalID);
            }
            AMIdentity amId = new AMIdentity(getAdminToken(), universalID);
            Set tmp = amId.getAttribute("userPassword");
            if (tmp != null && !tmp.isEmpty()) {
                String userPassword = (String) tmp.iterator().next();
                ssoToken.setProperty("HashedUserPassword", userPassword);
            }
        }
    } catch (SSOException sse) {
        debug.warning("WSSReplayPasswd.onLoginSuccess: " + "sso exception", sse);
    } catch (IdRepoException ire) {
        if (debug.warningEnabled()) {
            debug.warning("WSSReplayPassword.onLoginSuccess: ", ire);
        }
    }
}
Also used : Set(java.util.Set) AMIdentity(com.sun.identity.idm.AMIdentity) IdRepoException(com.sun.identity.idm.IdRepoException) SSOException(com.iplanet.sso.SSOException)

Example 22 with IdRepoException

use of com.sun.identity.idm.IdRepoException in project OpenAM by OpenRock.

the class ClientResource method createInstance.

public Promise<ResourceResponse, ResourceException> createInstance(Context context, CreateRequest createRequest) {
    String principal = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
    Map<String, String> responseVal = new HashMap<String, String>();
    try {
        if (serviceSchema == null || serviceSchemaManager == null) {
            if (debug.errorEnabled()) {
                debug.error("ClientResource :: CREATE by " + principal + ": No serviceSchema available.");
            }
            throw new PermanentException(ResourceException.INTERNAL_ERROR, "", null);
        }
        Map<String, ArrayList<String>> client = (Map<String, ArrayList<String>>) createRequest.getContent().getObject();
        String realm = null;
        if (client == null || client.isEmpty()) {
            if (debug.errorEnabled()) {
                debug.error("ClientResource :: CREATE by " + principal + ": No client definition.");
            }
            throw new PermanentException(ResourceException.BAD_REQUEST, "Missing client definition", null);
        }
        //check for id
        String id = createRequest.getNewResourceId();
        if (client.containsKey(OAuth2Constants.OAuth2Client.CLIENT_ID)) {
            ArrayList<String> idList = client.remove(OAuth2Constants.OAuth2Client.CLIENT_ID);
            if (idList != null && !idList.isEmpty()) {
                id = idList.iterator().next();
            }
        }
        if (id == null || id.isEmpty()) {
            debug.error("ClientResource :: CREATE by " + principal + ": No client ID.");
            throw new PermanentException(ResourceException.BAD_REQUEST, "Missing client id", null);
        }
        //get realm
        if (client.containsKey(OAuth2Constants.OAuth2Client.REALM)) {
            ArrayList<String> realmList = client.remove(OAuth2Constants.OAuth2Client.REALM);
            if (realmList != null && !realmList.isEmpty()) {
                realm = realmList.iterator().next();
            }
        }
        //check for required parameters
        if (!client.containsKey(OAuth2Constants.OAuth2Client.USERPASSWORD) || client.get(OAuth2Constants.OAuth2Client.USERPASSWORD).iterator().next().isEmpty()) {
            if (debug.errorEnabled()) {
                debug.error("ClientResource :: CREATE by " + principal + ": " + "Resource ID: " + id + ": No user password.");
            }
            throw new PermanentException(ResourceException.BAD_REQUEST, "Missing user password", null);
        }
        if (client.containsKey(OAuth2Constants.OAuth2Client.CLIENT_TYPE)) {
            String type = client.get(OAuth2Constants.OAuth2Client.CLIENT_TYPE).iterator().next();
            if (!(type.equals("Confidential") || type.equals("Public"))) {
                debug.error("ClientResource :: CREATE by " + principal + ": " + "Resource ID: " + id + ": No client type.");
                throw new PermanentException(ResourceException.BAD_REQUEST, "Missing client type", null);
            }
        } else {
            debug.error("ClientResource :: CREATE by" + principal + ": " + "Resource ID: " + id + ": No client type.");
            throw new PermanentException(ResourceException.BAD_REQUEST, "Missing client type", null);
        }
        Map<String, Set<String>> attrs = new HashMap<String, Set<String>>();
        for (Map.Entry mapEntry : client.entrySet()) {
            List<String> list = (ArrayList) mapEntry.getValue();
            Set<String> set = new HashSet<String>();
            if (isSingle((String) mapEntry.getKey())) {
                set.add((String) ((ArrayList) mapEntry.getValue()).get(0));
            } else {
                for (int i = 0; i < list.size(); i++) {
                    set.add("[" + i + "]=" + list.get(i));
                }
            }
            attrs.put((String) mapEntry.getKey(), set);
        }
        Set<String> temp = new HashSet<String>();
        temp.add("OAuth2Client");
        attrs.put("AgentType", temp);
        temp = new HashSet<String>();
        temp.add("Active");
        attrs.put("sunIdentityServerDeviceStatus", temp);
        manager.createIdentity(realm, id, attrs);
        responseVal.put("success", "true");
        JsonValue response = new JsonValue(responseVal);
        ResourceResponse resource = newResourceResponse("results", String.valueOf(System.currentTimeMillis()), response);
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "CREATED_CLIENT", responseVal.toString() };
            auditLogger.logAccessMessage("CREATED_CLIENT", obs, null);
        }
        return newResultPromise(resource);
    } catch (IdRepoException e) {
        responseVal.put("success", "false");
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "FAILED_CREATE_CLIENT", responseVal.toString() };
            auditLogger.logErrorMessage("FAILED_CREATE_CLIENT", obs, null);
        }
        if (debug.errorEnabled()) {
            debug.error("ClientResource :: CREATE by " + principal + ": Unable to create client due to " + "IdRepo exception.", e);
        }
        return new InternalServerErrorException("Unable to create client", e).asPromise();
    } catch (SSOException e) {
        responseVal.put("success", "false");
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "FAILED_CREATE_CLIENT", responseVal.toString() };
            auditLogger.logErrorMessage("FAILED_CREATE_CLIENT", obs, null);
        }
        if (debug.errorEnabled()) {
            debug.error("ClientResource :: CREATE by " + principal + ": Unable to create client due to " + "SSO exception.", e);
        }
        return new InternalServerErrorException("Unable to create client", e).asPromise();
    } catch (PermanentException e) {
        responseVal.put("success", "false");
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "FAILED_CREATE_CLIENT", responseVal.toString() };
            auditLogger.logErrorMessage("FAILED_CREATE_CLIENT", obs, null);
        }
        if (debug.errorEnabled()) {
            debug.error("ClientResource :: CREATE by " + principal + ": Unable to create client due to exception.", e);
        }
        return e.asPromise();
    } catch (org.forgerock.json.resource.BadRequestException e) {
        responseVal.put("success", "false");
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "FAILED_CREATE_CLIENT", responseVal.toString() };
            auditLogger.logErrorMessage("FAILED_CREATE_CLIENT", obs, null);
        }
        debug.error("ClientResource :: CREATE : Unable to create client due to Bad Request.", e);
        return e.asPromise();
    }
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SSOException(com.iplanet.sso.SSOException) PermanentException(org.forgerock.json.resource.PermanentException) HashSet(java.util.HashSet) JsonValue(org.forgerock.json.JsonValue) IdRepoException(com.sun.identity.idm.IdRepoException) Responses.newResourceResponse(org.forgerock.json.resource.Responses.newResourceResponse) ResourceResponse(org.forgerock.json.resource.ResourceResponse) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 23 with IdRepoException

use of com.sun.identity.idm.IdRepoException in project OpenAM by OpenRock.

the class TokenResource method deleteToken.

/**
     * Deletes the token with the provided token id.
     *
     * @param context The context.
     * @param tokenId The token id.
     * @param deleteRefreshToken Whether to delete associated refresh token, if token id is for an access token.
     * @return {@code Void} if the token has been deleted.
     */
private Promise<Void, ResourceException> deleteToken(Context context, String tokenId, boolean deleteRefreshToken) {
    try {
        AMIdentity uid = getUid(context);
        JsonValue token = tokenStore.read(tokenId);
        if (token == null) {
            if (debug.errorEnabled()) {
                debug.error("TokenResource :: DELETE : No token with ID, " + tokenId + " found to delete");
            }
            throw new NotFoundException("Token Not Found", null);
        }
        String username = getAttributeValue(token, USERNAME);
        if (username == null || username.isEmpty()) {
            if (debug.errorEnabled()) {
                debug.error("TokenResource :: DELETE : No username associated with " + "token with ID, " + tokenId + ".");
            }
            throw new PermanentException(HttpURLConnection.HTTP_NOT_FOUND, "Not Found", null);
        }
        String grantType = getAttributeValue(token, GRANT_TYPE);
        if (grantType != null && grantType.equalsIgnoreCase(CLIENT_CREDENTIALS)) {
            if (deleteRefreshToken) {
                deleteAccessTokensRefreshToken(token);
            }
            tokenStore.delete(tokenId);
        } else {
            String realm = getAttributeValue(token, REALM);
            AMIdentity uid2 = identityManager.getResourceOwnerIdentity(username, realm);
            if (uid.equals(uid2) || uid.equals(adminUserId)) {
                if (deleteRefreshToken) {
                    deleteAccessTokensRefreshToken(token);
                }
                tokenStore.delete(tokenId);
            } else {
                if (debug.errorEnabled()) {
                    debug.error("TokenResource :: DELETE : Only the resource owner or an administrator may perform " + "a delete on the token with ID, " + tokenId + ".");
                }
                throw new PermanentException(401, "Unauthorized", null);
            }
        }
        return newResultPromise(null);
    } catch (CoreTokenException e) {
        return new ServiceUnavailableException(e.getMessage(), e).asPromise();
    } catch (ResourceException e) {
        return e.asPromise();
    } catch (SSOException e) {
        debug.error("TokenResource :: DELETE : Unable to retrieve identity of the requesting user. Unauthorized.");
        return new PermanentException(401, "Unauthorized", e).asPromise();
    } catch (IdRepoException e) {
        debug.error("TokenResource :: DELETE : Unable to retrieve identity of the requesting user. Unauthorized.");
        return new PermanentException(401, "Unauthorized", e).asPromise();
    } catch (UnauthorizedClientException e) {
        debug.error("TokenResource :: DELETE : Requesting user is unauthorized.");
        return new PermanentException(401, "Unauthorized", e).asPromise();
    }
}
Also used : AMIdentity(com.sun.identity.idm.AMIdentity) PermanentException(org.forgerock.json.resource.PermanentException) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) JsonValue(org.forgerock.json.JsonValue) IdRepoException(com.sun.identity.idm.IdRepoException) NotFoundException(org.forgerock.json.resource.NotFoundException) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) ResourceException(org.forgerock.json.resource.ResourceException) SSOException(com.iplanet.sso.SSOException) ServiceUnavailableException(org.forgerock.json.resource.ServiceUnavailableException)

Example 24 with IdRepoException

use of com.sun.identity.idm.IdRepoException in project OpenAM by OpenRock.

the class UmaPolicyServiceImpl method resolveUIDToUsername.

private JsonValue resolveUIDToUsername(JsonValue policy) {
    for (JsonValue permission : policy.get("permissions")) {
        try {
            String username = new AMIdentity(null, permission.get("subject").asString()).getName();
            permission.put("subject", username);
        } catch (IdRepoException e) {
        //Cannot happen in this use case
        }
    }
    return policy;
}
Also used : AMIdentity(com.sun.identity.idm.AMIdentity) JsonValue(org.forgerock.json.JsonValue) IdRepoException(com.sun.identity.idm.IdRepoException)

Example 25 with IdRepoException

use of com.sun.identity.idm.IdRepoException in project OpenAM by OpenRock.

the class IdentityServicesImpl method search.

/**
     * Searches the identity repository to find all identities that match the search criteria.
     *
     * @param crestQuery A CREST Query object which will contain either a _queryId or a _queryFilter.
     * @param searchModifiers The search modifiers
     * @param admin Your SSO token.
     * @return a list of matching identifiers.
     * @throws ResourceException
     */
public List<String> search(CrestQuery crestQuery, Map<String, Set<String>> searchModifiers, SSOToken admin) throws ResourceException {
    List<String> rv = new ArrayList<>();
    try {
        String realm = "/";
        String objectType = "User";
        if (searchModifiers != null) {
            realm = attractValues("realm", searchModifiers, "/");
            objectType = attractValues("objecttype", searchModifiers, "User");
        }
        AMIdentityRepository repo = getRepo(admin, realm);
        IdType idType = getIdType(objectType);
        if (idType != null) {
            List<AMIdentity> objList = fetchAMIdentities(idType, crestQuery, false, repo, searchModifiers);
            if (objList != null && !objList.isEmpty()) {
                List<String> names = getNames(realm, idType, objList);
                if (!names.isEmpty()) {
                    for (String name : names) {
                        rv.add(name);
                    }
                }
            }
        } else {
            debug.error("IdentityServicesImpl:search unsupported IdType" + objectType);
            throw new BadRequestException("search unsupported IdType: " + objectType);
        }
    } catch (IdRepoException e) {
        debug.error("IdentityServicesImpl:search", e);
        throw new InternalServerErrorException(e.getMessage());
    } catch (SSOException e) {
        debug.error("IdentityServicesImpl:search", e);
        throw new InternalServerErrorException(e.getMessage());
    } catch (ObjectNotFound e) {
        debug.error("IdentityServicesImpl:search", e);
        throw new NotFoundException(e.getMessage());
    }
    return rv;
}
Also used : ArrayList(java.util.ArrayList) IdRepoException(com.sun.identity.idm.IdRepoException) NotFoundException(org.forgerock.json.resource.NotFoundException) SSOException(com.iplanet.sso.SSOException) IdType(com.sun.identity.idm.IdType) ObjectNotFound(com.sun.identity.idsvcs.ObjectNotFound) AMIdentity(com.sun.identity.idm.AMIdentity) AMIdentityRepository(com.sun.identity.idm.AMIdentityRepository) BadRequestException(org.forgerock.json.resource.BadRequestException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException)

Aggregations

IdRepoException (com.sun.identity.idm.IdRepoException)403 SSOException (com.iplanet.sso.SSOException)275 Set (java.util.Set)224 AMIdentity (com.sun.identity.idm.AMIdentity)221 HashSet (java.util.HashSet)183 Map (java.util.Map)121 Iterator (java.util.Iterator)118 SSOToken (com.iplanet.sso.SSOToken)112 HashMap (java.util.HashMap)110 SMSException (com.sun.identity.sm.SMSException)103 AMIdentityRepository (com.sun.identity.idm.AMIdentityRepository)96 CaseInsensitiveHashSet (com.sun.identity.common.CaseInsensitiveHashSet)67 AMConsoleException (com.sun.identity.console.base.model.AMConsoleException)58 IdType (com.sun.identity.idm.IdType)57 CaseInsensitiveHashMap (com.sun.identity.common.CaseInsensitiveHashMap)51 CLIException (com.sun.identity.cli.CLIException)48 IOutput (com.sun.identity.cli.IOutput)45 IdSearchResults (com.sun.identity.idm.IdSearchResults)44 IdSearchControl (com.sun.identity.idm.IdSearchControl)39 IdRepoUnsupportedOpException (com.sun.identity.idm.IdRepoUnsupportedOpException)35