Search in sources :

Example 11 with UnauthorizedClientException

use of org.forgerock.oauth2.core.exceptions.UnauthorizedClientException in project OpenAM by OpenRock.

the class OpenAMTokenStore method appendRequestedIdTokenClaims.

//See spec section 5.5. - add claims to id_token based on 'claims' parameter in the access token
private void appendRequestedIdTokenClaims(OAuth2Request request, OAuth2ProviderSettings providerSettings, OpenAMOpenIdConnectToken oidcToken) throws ServerException, NotFoundException, InvalidClientException {
    AccessToken accessToken = request.getToken(AccessToken.class);
    String claims;
    if (accessToken != null) {
        claims = (String) accessToken.toMap().get(OAuth2Constants.Custom.CLAIMS);
    } else {
        claims = request.getParameter(OAuth2Constants.Custom.CLAIMS);
    }
    if (claims != null) {
        try {
            JSONObject claimsObject = new JSONObject(claims);
            JSONObject idTokenClaimsRequest = claimsObject.getJSONObject(OAuth2Constants.JWTTokenParams.ID_TOKEN);
            Map<String, Object> userInfo = providerSettings.getUserInfo(accessToken, request).getValues();
            Iterator<String> it = idTokenClaimsRequest.keys();
            while (it.hasNext()) {
                String keyName = it.next();
                if (userInfo.containsKey(keyName)) {
                    oidcToken.put(keyName, userInfo.get(keyName));
                }
            }
        } catch (UnauthorizedClientException e) {
            throw failureFactory.getException(request, e.getMessage());
        } catch (JSONException e) {
        //if claims object not found, fall through
        }
    }
}
Also used : JSONObject(org.json.JSONObject) AccessToken(org.forgerock.oauth2.core.AccessToken) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject)

Example 12 with UnauthorizedClientException

use of org.forgerock.oauth2.core.exceptions.UnauthorizedClientException in project OpenAM by OpenRock.

the class OpenAMClientDAO method delete.

/**
     * {@inheritDoc}
     */
public void delete(String clientId, OAuth2Request request) throws UnauthorizedClientException {
    try {
        //get the AMIdentity
        final SSOToken token = AccessController.doPrivileged(AdminTokenAction.getInstance());
        final String realm = request.getParameter(OAuth2Constants.Custom.REALM);
        AMIdentityRepository repo = idRepoFactory.create(realm, token);
        AMIdentity theID = null;
        IdSearchControl idsc = new IdSearchControl();
        idsc.setRecursive(true);
        idsc.setAllReturnAttributes(true);
        // search for the identity
        Set<AMIdentity> results;
        idsc.setMaxResults(0);
        IdSearchResults searchResults = repo.searchIdentities(IdType.AGENTONLY, clientId, idsc);
        results = searchResults.getSearchResults();
        if (results == null || results.size() != 1) {
            logger.error("OpenAMClientDAO.delete(): No client profile or more than one profile found.");
            throw new UnauthorizedClientException("Not able to get client from OpenAM");
        }
        theID = results.iterator().next();
        //if the client is deactivated return null
        if (!theID.isActive()) {
            theID = null;
        }
        //delete the AMIdentity
        Set<AMIdentity> identities = new HashSet<AMIdentity>();
        identities.add(theID);
        repo.deleteIdentities(identities);
    } catch (SSOException e) {
        logger.error("OpenAMClientDAO.delete(): Unable to delete client", e);
        throw new UnauthorizedClientException();
    } catch (IdRepoException e) {
        logger.error("OpenAMClientDAO.delete(): Unable to delete client", e);
        throw new UnauthorizedClientException();
    }
}
Also used : SSOToken(com.iplanet.sso.SSOToken) IdSearchResults(com.sun.identity.idm.IdSearchResults) AMIdentity(com.sun.identity.idm.AMIdentity) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) AMIdentityRepository(com.sun.identity.idm.AMIdentityRepository) IdSearchControl(com.sun.identity.idm.IdSearchControl) IdRepoException(com.sun.identity.idm.IdRepoException) SSOException(com.iplanet.sso.SSOException) HashSet(java.util.HashSet)

Example 13 with UnauthorizedClientException

use of org.forgerock.oauth2.core.exceptions.UnauthorizedClientException in project OpenAM by OpenRock.

the class IdentityManager method getResourceOwnerIdentity.

/**
     * Gets a resource owner's identity.
     *
     * @param username The resource owner's username.
     * @param realm The resource owner's realm.
     * @return The resource owner's identity.
     * @throws UnauthorizedClientException If the resource owner's identity cannot be found.
     */
public AMIdentity getResourceOwnerIdentity(String username, final String realm) throws UnauthorizedClientException {
    final SSOToken token = AccessController.doPrivileged(AdminTokenAction.getInstance());
    final AMIdentity amIdentity;
    try {
        final AMIdentityRepository amIdRepo = new AMIdentityRepository(token, realm);
        final IdSearchControl idsc = new IdSearchControl();
        idsc.setRecursive(true);
        idsc.setAllReturnAttributes(true);
        // search for the identity
        final Set<AMIdentity> results = new HashSet<AMIdentity>();
        idsc.setMaxResults(0);
        IdSearchResults searchResults = amIdRepo.searchIdentities(IdType.USER, username, idsc);
        if (searchResults != null && !searchResults.getResultAttributes().isEmpty()) {
            results.addAll(searchResults.getSearchResults());
        } else {
            OAuth2ProviderSettings settings = providerSettingsFactory.get(new OAuth2Request() {

                public <T> T getRequest() {
                    throw new UnsupportedOperationException("Realm parameter only OAuth2Request");
                }

                public <T> T getParameter(String name) {
                    if ("realm".equals(name)) {
                        return (T) realm;
                    }
                    throw new UnsupportedOperationException("Realm parameter only OAuth2Request");
                }

                public JsonValue getBody() {
                    throw new UnsupportedOperationException("Realm parameter only OAuth2Request");
                }

                @Override
                public Locale getLocale() {
                    throw new UnsupportedOperationException();
                }
            });
            final Map<String, Set<String>> avPairs = toAvPairMap(settings.getResourceOwnerAuthenticatedAttributes(), username);
            idsc.setSearchModifiers(IdSearchOpModifier.OR, avPairs);
            searchResults = amIdRepo.searchIdentities(IdType.USER, "*", idsc);
            if (searchResults != null) {
                results.addAll(searchResults.getSearchResults());
            }
        }
        if (results.size() != 1) {
            logger.error("No user profile or more than one profile found.");
            throw new UnauthorizedClientException("Not able to get user from OpenAM");
        }
        amIdentity = results.iterator().next();
        //if the client is deactivated return null
        if (amIdentity.isActive()) {
            return amIdentity;
        } else {
            return null;
        }
    } catch (Exception e) {
        logger.error("Unable to get client AMIdentity: ", e);
        throw new UnauthorizedClientException("Not able to get client from OpenAM");
    }
}
Also used : Locale(java.util.Locale) SSOToken(com.iplanet.sso.SSOToken) Set(java.util.Set) HashSet(java.util.HashSet) IdSearchResults(com.sun.identity.idm.IdSearchResults) JsonValue(org.forgerock.json.JsonValue) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) AMIdentity(com.sun.identity.idm.AMIdentity) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) AMIdentityRepository(com.sun.identity.idm.AMIdentityRepository) IdSearchControl(com.sun.identity.idm.IdSearchControl) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings) HashSet(java.util.HashSet)

Example 14 with UnauthorizedClientException

use of org.forgerock.oauth2.core.exceptions.UnauthorizedClientException in project OpenAM by OpenRock.

the class TokenResource method queryCollection.

@Override
public Promise<QueryResponse, ResourceException> queryCollection(Context context, QueryRequest queryRequest, QueryResourceHandler handler) {
    try {
        JsonValue response;
        Collection<QueryFilter<CoreTokenField>> query = new ArrayList<QueryFilter<CoreTokenField>>();
        //get uid of submitter
        AMIdentity uid;
        try {
            uid = getUid(context);
            if (!uid.equals(adminUserId)) {
                query.add(QueryFilter.equalTo(USERNAME_FIELD, uid.getName()));
                query.add(QueryFilter.equalTo(REALM_FIELD, DNMapper.orgNameToRealmName(uid.getRealm())));
            }
        } catch (Exception e) {
            if (debug.errorEnabled()) {
                debug.error("TokenResource :: QUERY : Unable to query collection as no UID discovered " + "for requesting user.");
            }
            return new PermanentException(401, "Unauthorized", e).asPromise();
        }
        String id = queryRequest.getQueryId();
        String queryString;
        if (id.equals("access_token")) {
            queryString = "tokenName=access_token";
        } else {
            queryString = id;
        }
        String[] constraints = queryString.split(",");
        boolean userNamePresent = false;
        for (String constraint : constraints) {
            String[] params = constraint.split("=");
            if (params.length == 2) {
                if (OAuthTokenField.USER_NAME.getOAuthField().equals(params[0])) {
                    userNamePresent = true;
                }
                query.add(QueryFilter.equalTo(getOAuth2TokenField(params[0]), params[1]));
            }
        }
        if (adminUserId.equals(uid)) {
            if (!userNamePresent) {
                return new BadRequestException("userName field MUST be set in _queryId").asPromise();
            }
        } else if (userNamePresent) {
            return new BadRequestException("userName field MUST NOT be set in _queryId").asPromise();
        }
        response = tokenStore.query(QueryFilter.and(query));
        return handleResponse(handler, response, context);
    } catch (UnauthorizedClientException e) {
        debug.error("TokenResource :: QUERY : Unable to query collection as the client is not authorized.", e);
        return new PermanentException(401, e.getMessage(), e).asPromise();
    } catch (CoreTokenException e) {
        debug.error("TokenResource :: QUERY : Unable to query collection as the token store is not available.", e);
        return new ServiceUnavailableException(e.getMessage(), e).asPromise();
    } catch (InternalServerErrorException e) {
        debug.error("TokenResource :: QUERY : Unable to query collection as writing the response failed.", e);
        return e.asPromise();
    } catch (NotFoundException e) {
        debug.error("TokenResource :: QUERY : Unable to query collection as realm does not have OAuth 2 provider.", e);
        return e.asPromise();
    }
}
Also used : JsonValue(org.forgerock.json.JsonValue) ArrayList(java.util.ArrayList) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) NotFoundException(org.forgerock.json.resource.NotFoundException) CoreTokenField(org.forgerock.openam.tokens.CoreTokenField) ServiceUnavailableException(org.forgerock.json.resource.ServiceUnavailableException) PermanentException(org.forgerock.json.resource.PermanentException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) ServiceUnavailableException(org.forgerock.json.resource.ServiceUnavailableException) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) SSOException(com.iplanet.sso.SSOException) NotFoundException(org.forgerock.json.resource.NotFoundException) BadRequestException(org.forgerock.json.resource.BadRequestException) IdRepoException(com.sun.identity.idm.IdRepoException) SMSException(com.sun.identity.sm.SMSException) ResourceException(org.forgerock.json.resource.ResourceException) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) QueryFilter(org.forgerock.util.query.QueryFilter) AMIdentity(com.sun.identity.idm.AMIdentity) PermanentException(org.forgerock.json.resource.PermanentException) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) BadRequestException(org.forgerock.json.resource.BadRequestException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException)

Example 15 with UnauthorizedClientException

use of org.forgerock.oauth2.core.exceptions.UnauthorizedClientException in project OpenAM by OpenRock.

the class TokenResource method readInstance.

@Override
public Promise<ResourceResponse, ResourceException> readInstance(Context context, String resourceId, ReadRequest request) {
    try {
        AMIdentity uid = getUid(context);
        JsonValue response;
        ResourceResponse resource;
        try {
            response = tokenStore.read(resourceId);
        } catch (CoreTokenException e) {
            if (debug.errorEnabled()) {
                debug.error("TokenResource :: READ : No token found with ID, " + resourceId);
            }
            throw new NotFoundException("Could not find valid token with given ID", e);
        }
        if (response == null) {
            if (debug.errorEnabled()) {
                debug.error("TokenResource :: READ : No token found with ID, " + resourceId);
            }
            throw new NotFoundException("Could not find valid token with given ID");
        }
        JsonValue expireTimeValue = response.get(OAuth2Constants.CoreTokenParams.EXPIRE_TIME);
        long expireTime;
        if (expireTimeValue.isNumber()) {
            expireTime = expireTimeValue.asLong();
        } else {
            Set<String> expireTimeSet = (Set<String>) expireTimeValue.getObject();
            expireTime = Long.parseLong(expireTimeSet.iterator().next());
        }
        if (System.currentTimeMillis() > expireTime) {
            throw new NotFoundException("Could not find valid token with given ID");
        }
        String grantType = getAttributeValue(response, GRANT_TYPE);
        if (grantType != null && grantType.equalsIgnoreCase(OAuth2Constants.TokenEndpoint.CLIENT_CREDENTIALS)) {
            resource = newResourceResponse(OAuth2Constants.Params.ID, String.valueOf(System.currentTimeMillis()), response);
            return newResultPromise(resource);
        } else {
            String realm = getAttributeValue(response, REALM);
            String username = getAttributeValue(response, USERNAME);
            if (username == null || username.isEmpty()) {
                if (debug.errorEnabled()) {
                    debug.error("TokenResource :: READ : No token found with ID, " + resourceId);
                }
                throw new NotFoundException("Could not find valid token with given ID");
            }
            AMIdentity uid2 = identityManager.getResourceOwnerIdentity(username, realm);
            if (uid.equals(adminUserId) || uid.equals(uid2)) {
                resource = newResourceResponse(OAuth2Constants.Params.ID, String.valueOf(System.currentTimeMillis()), response);
                return newResultPromise(resource);
            } else {
                if (debug.errorEnabled()) {
                    debug.error("TokenResource :: READ : Only the resource owner or an administrator may perform " + "a read on the token with ID, " + resourceId + ".");
                }
                throw new PermanentException(401, "Unauthorized", null);
            }
        }
    } catch (ResourceException e) {
        return e.asPromise();
    } catch (SSOException e) {
        debug.error("TokenResource :: READ : Unable to query collection as the IdRepo " + "failed to return a valid user.", e);
        return new PermanentException(401, "Unauthorized", e).asPromise();
    } catch (IdRepoException e) {
        debug.error("TokenResource :: READ : Unable to query collection as the IdRepo " + "failed to return a valid user.", e);
        return new PermanentException(401, "Unauthorized", e).asPromise();
    } catch (UnauthorizedClientException e) {
        debug.error("TokenResource :: READ : Unable to query collection as the client is not authorized.", e);
        return new PermanentException(401, "Unauthorized", e).asPromise();
    }
}
Also used : Set(java.util.Set) JsonValue(org.forgerock.json.JsonValue) IdRepoException(com.sun.identity.idm.IdRepoException) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) NotFoundException(org.forgerock.json.resource.NotFoundException) SSOException(com.iplanet.sso.SSOException) ResourceResponse(org.forgerock.json.resource.ResourceResponse) AMIdentity(com.sun.identity.idm.AMIdentity) PermanentException(org.forgerock.json.resource.PermanentException) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) ResourceException(org.forgerock.json.resource.ResourceException)

Aggregations

UnauthorizedClientException (org.forgerock.oauth2.core.exceptions.UnauthorizedClientException)14 AMIdentity (com.sun.identity.idm.AMIdentity)10 SSOException (com.iplanet.sso.SSOException)8 IdRepoException (com.sun.identity.idm.IdRepoException)7 SSOToken (com.iplanet.sso.SSOToken)5 HashSet (java.util.HashSet)5 Set (java.util.Set)5 JsonValue (org.forgerock.json.JsonValue)5 AMIdentityRepository (com.sun.identity.idm.AMIdentityRepository)4 IdSearchControl (com.sun.identity.idm.IdSearchControl)4 IdSearchResults (com.sun.identity.idm.IdSearchResults)4 HashMap (java.util.HashMap)4 NotFoundException (org.forgerock.json.resource.NotFoundException)3 PermanentException (org.forgerock.json.resource.PermanentException)3 ResourceException (org.forgerock.json.resource.ResourceException)3 CoreTokenException (org.forgerock.openam.cts.exceptions.CoreTokenException)3 JSONObject (org.json.JSONObject)3 Locale (java.util.Locale)2 Map (java.util.Map)2 ServiceUnavailableException (org.forgerock.json.resource.ServiceUnavailableException)2