use of org.forgerock.json.resource.ForbiddenException in project OpenAM by OpenRock.
the class TokenGenerationService method validateAssertionSubjectSession.
private SSOToken validateAssertionSubjectSession(TokenGenerationServiceInvocationState invocationState) throws ForbiddenException {
SSOToken subjectToken;
SSOTokenManager tokenManager;
try {
tokenManager = SSOTokenManager.getInstance();
subjectToken = tokenManager.createSSOToken(invocationState.getSsoTokenString());
} catch (SSOException e) {
logger.debug("Exception caught creating the SSO token from the token string, almost certainly " + "because token string does not correspond to a valid session: " + e);
throw new ForbiddenException(e.toString(), e);
}
if (!tokenManager.isValidToken(subjectToken)) {
throw new ForbiddenException("SSO token string does not correspond to a valid SSOToken");
}
try {
AMIdentity subjectIdentity = IdUtils.getIdentity(subjectToken);
String invocationRealm = invocationState.getRealm();
String subjectSessionRealm = DNMapper.orgNameToRealmName(subjectIdentity.getRealm());
logger.debug("TokenGenerationService:validateAssertionSubjectSession subjectRealm " + subjectSessionRealm + " invocation realm: " + invocationRealm);
if (!invocationRealm.equalsIgnoreCase(subjectSessionRealm)) {
logger.error("TokenGenerationService:validateAssertionSubjectSession realms do not match: Subject realm : " + subjectSessionRealm + " invocation realm: " + invocationRealm);
throw new ForbiddenException("SSO token subject realm does not match invocation realm");
}
} catch (SSOException | IdRepoException e) {
logger.error("TokenGenerationService:validateAssertionSubjectSession error while validating identity : " + e);
throw new ForbiddenException(e.toString(), e);
}
return subjectToken;
}
use of org.forgerock.json.resource.ForbiddenException in project OpenAM by OpenRock.
the class UmaPolicyServiceImpl method updatePolicy.
/**
* {@inheritDoc}
*/
@Override
public //TODO need to check if need to delete backend policies
Promise<UmaPolicy, ResourceException> updatePolicy(//TODO need to check if need to delete backend policies
final Context context, //TODO need to check if need to delete backend policies
final String resourceSetId, JsonValue policy) {
final UmaPolicy updatedUmaPolicy;
final ResourceSetDescription resourceSet;
try {
resourceSet = getResourceSet(getRealm(context), resourceSetId);
updatedUmaPolicy = UmaPolicy.valueOf(resourceSet, resolveUsernameToUID(context, policy));
boolean canShare = canUserShareResourceSet(resourceSet.getResourceOwnerId(), contextHelper.getUserId(context), resourceSet.getClientId(), getRealm(context), resourceSet.getId(), updatedUmaPolicy.getScopes());
if (!canShare) {
return new ForbiddenException().asPromise();
}
validateScopes(resourceSet, updatedUmaPolicy.getScopes());
} catch (ResourceException e) {
return e.asPromise();
}
return internalReadPolicy(context, resourceSetId).thenAsync(beforeResourceSharedModified(updatedUmaPolicy)).thenOnResult(new ResultHandler<UmaPolicy>() {
@Override
public void handleResult(UmaPolicy currentUmaPolicy) {
Set<String> modifiedScopes = new HashSet<>(updatedUmaPolicy.getScopes());
modifiedScopes.retainAll(currentUmaPolicy.getScopes());
Set<String> removedScopes = new HashSet<>(currentUmaPolicy.getScopes());
removedScopes.removeAll(modifiedScopes);
for (JsonValue policy : currentUmaPolicy.asUnderlyingPolicies(contextHelper.getUserId(context))) {
for (String scope : removedScopes) {
if (policy.get("actionValues").isDefined(scope)) {
policyResourceDelegate.queryPolicies(context, Requests.newQueryRequest("").setQueryFilter(QueryFilter.and(QueryFilter.equalTo(new JsonPointer("createdBy"), contextHelper.getUserUid(context)), QueryFilter.equalTo(new JsonPointer("name"), policy.get("name").asString())))).thenAsync(new DeleteOldPolicyFunction(context));
}
}
}
}
}).thenOnResult(new ResultHandler<UmaPolicy>() {
@Override
public void handleResult(UmaPolicy currentUmaPolicy) {
Set<String> modifiedScopes = new HashSet<>(currentUmaPolicy.getScopes());
modifiedScopes.retainAll(updatedUmaPolicy.getScopes());
Set<String> deletedScopes = new HashSet<>(updatedUmaPolicy.getScopes());
deletedScopes.removeAll(modifiedScopes);
for (JsonValue policy : updatedUmaPolicy.asUnderlyingPolicies(contextHelper.getUserId(context))) {
for (String scope : deletedScopes) {
if (policy.get("actionValues").isDefined(scope)) {
policyResourceDelegate.createPolicies(context, singleton(policy));
}
}
}
}
}).thenOnResult(new ResultHandler<UmaPolicy>() {
@Override
public void handleResult(UmaPolicy currentUmaPolicy) {
String uid = contextHelper.getUserId(context);
Set<String> underlyingPolicyIds = new HashSet<>(currentUmaPolicy.getUnderlyingPolicyIds());
Set<JsonValue> newUnderlyingPolicies = updatedUmaPolicy.asUnderlyingPolicies(uid);
for (JsonValue value : newUnderlyingPolicies) {
underlyingPolicyIds.remove(value.get("name").asString());
}
policyResourceDelegate.deletePolicies(context, underlyingPolicyIds);
}
}).thenAsync(new UpdatePolicyGraphStatesFunction<UmaPolicy>(resourceSet, context)).thenAsync(new UpdateUmaPolicyFunction(context, updatedUmaPolicy, resourceSetId, resourceSet));
}
use of org.forgerock.json.resource.ForbiddenException in project OpenAM by OpenRock.
the class UmaPolicyServiceImpl method createPolicy.
/**
* {@inheritDoc}
*/
@Override
public Promise<UmaPolicy, ResourceException> createPolicy(final Context context, JsonValue policy) {
final UmaPolicy umaPolicy;
final ResourceSetDescription resourceSet;
final String userId = contextHelper.getUserId(context);
String realm = getRealm(context);
try {
String policyId = UmaPolicy.idOf(policy);
resourceSet = getResourceSet(realm, policyId);
umaPolicy = UmaPolicy.valueOf(resourceSet, resolveUsernameToUID(context, policy));
boolean canShare = canUserShareResourceSet(resourceSet.getResourceOwnerId(), userId, resourceSet.getClientId(), realm, resourceSet.getId(), umaPolicy.getScopes());
if (!canShare) {
return new ForbiddenException().asPromise();
}
validateScopes(resourceSet, umaPolicy.getScopes());
verifyPolicyDoesNotAlreadyExist(context, resourceSet);
} catch (ResourceException e) {
return e.asPromise();
}
return beforeResourceShared(umaPolicy).thenAsync(new AsyncFunction<UmaPolicy, List<ResourceResponse>, ResourceException>() {
@Override
public Promise<List<ResourceResponse>, ResourceException> apply(UmaPolicy umaPolicy) {
return policyResourceDelegate.createPolicies(context, umaPolicy.asUnderlyingPolicies(userId));
}
}).thenAlways(afterResourceShared(umaPolicy)).thenAsync(new UpdatePolicyGraphStatesFunction<List<ResourceResponse>>(resourceSet, context)).thenAsync(new AuditAndProduceUmaPolicyFunction(resourceSet, context));
}
use of org.forgerock.json.resource.ForbiddenException in project OpenAM by OpenRock.
the class IdentityServicesImpl method create.
/**
* Creates a new {@code AMIdentity} in the identity repository with the
* details specified in {@code identity}.
*
* @param identity The identity details.
* @param admin The admin token.
* @throws ResourceException If a problem occurs.
*/
public void create(IdentityDetails identity, SSOToken admin) throws ResourceException {
Reject.ifNull(identity, admin);
// Obtain identity details & verify
String idName = identity.getName();
String idType = identity.getType();
String realm = identity.getRealm();
if (StringUtils.isEmpty(idName)) {
// TODO: add a message to the exception
throw new BadRequestException("Identity name not provided");
}
if (StringUtils.isEmpty(idType)) {
idType = "user";
}
if (realm == null) {
realm = "/";
}
try {
// Obtain IdRepo to create validate IdType & operations
IdType objectIdType = getIdType(idType);
AMIdentityRepository repo = getRepo(admin, realm);
if (!isOperationSupported(repo, objectIdType, IdOperation.CREATE)) {
// TODO: add message to exception
throw new UnsupportedOperationException("Unsupported: Type: " + idType + " Operation: CREATE");
}
// Obtain creation attributes
Map<String, Set<String>> idAttrs = asMap(identity.getAttributes());
// Create the identity, special case of Agents to merge
// and validate the attributes
AMIdentity amIdentity;
if (isTypeAgent(objectIdType)) {
createAgent(idAttrs, objectIdType, idType, idName, realm, admin);
} else {
// Create other identites like User, Group, Role, etc.
amIdentity = repo.createIdentity(objectIdType, idName, idAttrs);
// Process roles, groups & memberships
if (IdType.USER.equals(objectIdType)) {
Set<String> roles = asSet(identity.getRoleList());
if (roles != null && !roles.isEmpty()) {
if (!isOperationSupported(repo, IdType.ROLE, IdOperation.EDIT)) {
// TODO: localize message
throw new UnsupportedOperationException("Unsupported: Type: " + IdType.ROLE + " Operation: EDIT");
}
for (String roleName : roles) {
AMIdentity role = fetchAMIdentity(repo, IdType.ROLE, roleName, false);
if (role != null) {
role.addMember(amIdentity);
role.store();
}
}
}
Set<String> groups = asSet(identity.getGroupList());
if (groups != null && !groups.isEmpty()) {
if (!isOperationSupported(repo, IdType.GROUP, IdOperation.EDIT)) {
// TODO: localize message
throw new UnsupportedOperationException("Unsupported: Type: " + IdType.GROUP + " Operation: EDIT");
}
for (String groupName : groups) {
AMIdentity group = fetchAMIdentity(repo, IdType.GROUP, groupName, false);
if (group != null) {
group.addMember(amIdentity);
group.store();
}
}
}
}
if (IdType.GROUP.equals(objectIdType) || IdType.ROLE.equals(objectIdType)) {
Set<String> members = asSet(identity.getMemberList());
if (members != null) {
if (IdType.GROUP.equals(objectIdType) && !isOperationSupported(repo, IdType.GROUP, IdOperation.EDIT)) {
throw new ForbiddenException("Token is not authorized");
}
if (IdType.ROLE.equals(objectIdType) && !isOperationSupported(repo, IdType.ROLE, IdOperation.EDIT)) {
throw new ForbiddenException("Token is not authorized");
}
for (String memberName : members) {
AMIdentity user = fetchAMIdentity(repo, IdType.USER, memberName, false);
if (user != null) {
amIdentity.addMember(user);
}
}
amIdentity.store();
}
}
}
} catch (IdRepoDuplicateObjectException ex) {
throw new ConflictException("Resource already exists", ex);
} catch (IdRepoException e) {
debug.error("IdentityServicesImpl:create", e);
if (IdRepoErrorCode.ACCESS_DENIED.equals(e.getErrorCode())) {
throw new ForbiddenException(e.getMessage());
} else if (e.getLdapErrorIntCode() == LDAPConstants.LDAP_CONSTRAINT_VIOLATION) {
debug.error(e.getMessage(), e);
throw new BadRequestException();
} else {
throw new NotFoundException(e.getMessage());
}
} catch (SSOException | SMSException | ConfigurationException | MalformedURLException | UnsupportedOperationException e) {
debug.error("IdentityServicesImpl:create", e);
throw new NotFoundException(e.getMessage());
} catch (ObjectNotFound e) {
debug.error("IdentityServicesImpl:create", e);
throw new NotFoundException(e.getMessage());
}
}
use of org.forgerock.json.resource.ForbiddenException in project OpenAM by OpenRock.
the class IdentityServicesImpl method update.
/**
* Updates an {@code AMIdentity} in the identity repository with the
* details specified in {@code identity}.
*
* @param identity The updated identity details.
* @param admin The admin token.
* @throws ResourceException If a problem occurs.
*/
public void update(IdentityDetails identity, SSOToken admin) throws ResourceException {
String idName = identity.getName();
String idType = identity.getType();
String realm = identity.getRealm();
if (StringUtils.isEmpty(idName)) {
// TODO: add a message to the exception
throw new BadRequestException("");
}
if (StringUtils.isEmpty(idType)) {
idType = "user";
}
if (realm == null) {
realm = "";
}
try {
IdType objectIdType = getIdType(idType);
AMIdentityRepository repo = getRepo(admin, realm);
if (!isOperationSupported(repo, objectIdType, IdOperation.EDIT)) {
// TODO: add message to exception
throw new ForbiddenException("");
}
AMIdentity amIdentity = getAMIdentity(admin, repo, idType, idName);
if (amIdentity == null) {
String msg = "Object \'" + idName + "\' of type \'" + idType + "\' not found.'";
throw new NotFoundException(msg);
}
if (isSpecialUser(amIdentity)) {
throw new ForbiddenException("Cannot update attributes for this user.");
}
Map<String, Set<String>> attrs = asMap(identity.getAttributes());
if (attrs != null && !attrs.isEmpty()) {
Map<String, Set<String>> idAttrs = new HashMap<>();
Set<String> removeAttrs = new HashSet<>();
for (Map.Entry<String, Set<String>> entry : attrs.entrySet()) {
String attrName = entry.getKey();
Set<String> attrValues = entry.getValue();
if (attrValues != null && !attrValues.isEmpty()) {
// attribute to add or modify
idAttrs.put(attrName, attrValues);
} else {
// attribute to remove
removeAttrs.add(attrName);
}
}
boolean storeNeeded = false;
if (!idAttrs.isEmpty()) {
amIdentity.setAttributes(idAttrs);
storeNeeded = true;
}
if (!removeAttrs.isEmpty()) {
amIdentity.removeAttributes(removeAttrs);
storeNeeded = true;
}
if (storeNeeded) {
amIdentity.store();
}
}
if (IdType.USER.equals(objectIdType)) {
Set<String> roles = asSet(identity.getRoleList());
if (!roles.isEmpty()) {
setMemberships(repo, amIdentity, roles, IdType.ROLE);
}
Set<String> groups = asSet(identity.getGroupList());
if (!groups.isEmpty()) {
setMemberships(repo, amIdentity, groups, IdType.GROUP);
}
}
if (IdType.GROUP.equals(objectIdType) || IdType.ROLE.equals(objectIdType)) {
Set<String> members = asSet(identity.getMemberList());
if (!members.isEmpty()) {
setMembers(repo, amIdentity, members, IdType.USER);
}
}
} catch (IdRepoException ex) {
debug.error("IdentityServicesImpl:update", ex);
if (IdRepoErrorCode.LDAP_EXCEPTION.equals(ex.getErrorCode())) {
throw new InternalServerErrorException(ex.getConstraintViolationDetails());
} else if (LDAPConstants.LDAP_INVALID_SYNTAX.equals(ex.getLDAPErrorCode())) {
throw new BadRequestException("Unrecognized or invalid syntax for an attribute.");
} else if (IdRepoErrorCode.ILLEGAL_ARGUMENTS.equals(ex.getErrorCode())) {
throw new BadRequestException(ex);
}
throw RESOURCE_MAPPING_HANDLER.handleError(ex);
} catch (SSOException ex) {
debug.error("IdentityServicesImpl:update", ex);
throw new BadRequestException(ex.getMessage());
} catch (ObjectNotFound e) {
debug.error("IdentityServicesImpl:update", e);
throw new NotFoundException(e.getMessage());
}
}
Aggregations