use of org.forgerock.openam.rest.RealmContext in project OpenAM by OpenRock.
the class UmaPolicyServiceImplTest method createContextForLoggedInUser.
private Context createContextForLoggedInUser(String userShortName) throws SSOException {
SubjectContext subjectContext = mock(SSOTokenContext.class);
SSOToken ssoToken = mock(SSOToken.class);
Principal principal = mock(Principal.class);
given(subjectContext.getCallerSSOToken()).willReturn(ssoToken);
given(ssoToken.getProperty(Constants.UNIVERSAL_IDENTIFIER)).willReturn("id=" + userShortName + ",ou=REALM,dc=forgerock,dc=org");
given(ssoToken.getPrincipal()).willReturn(principal);
given(principal.getName()).willReturn(userShortName);
return ClientContext.newInternalClientContext(new RealmContext(subjectContext));
}
use of org.forgerock.openam.rest.RealmContext in project OpenAM by OpenRock.
the class UmaResourceSetRegistrationHook method createAdminContext.
/**
* Used to create a context for deleting policies. If this is being called, we know that the user has the right
* to delete the policies.
* @param realm The realm to delete the policies in.
* @param resourceOwnerId The owner of the ResourceSet that the policies are for.
* @return The generated context.
*/
private Context createAdminContext(String realm, String resourceOwnerId) {
RealmContext realmContext = new RealmContext(new RootContext());
realmContext.setSubRealm(realm, realm);
SubjectContext subjectContext = new AdminSubjectContext(logger, sessionCache, realmContext);
Map<String, String> templateVariables = new HashMap<>();
templateVariables.put("user", resourceOwnerId);
UriRouterContext routerContext = new UriRouterContext(subjectContext, "", "", templateVariables);
return routerContext;
}
use of org.forgerock.openam.rest.RealmContext in project OpenAM by OpenRock.
the class IdentityResourceV2 method updateInstance.
/**
* {@inheritDoc}
*/
@Override
public Promise<ResourceResponse, ResourceException> updateInstance(final Context context, final String resourceId, final UpdateRequest request) {
RealmContext realmContext = context.asContext(RealmContext.class);
final String realm = realmContext.getResolvedRealm();
final JsonValue jVal = request.getContent();
final String rev = request.getRevision();
IdentityDetails dtls, newDtls;
ResourceResponse resource;
try {
SSOToken token = getSSOToken(getCookieFromServerContext(context));
// Retrieve details about user to be updated
dtls = identityServices.read(resourceId, getIdentityServicesAttributes(realm, objectType), token);
// Continue modifying the identity if read success
boolean isUpdatingHisOwnPassword = SystemProperties.getAsBoolean(Constants.CASE_SENSITIVE_UUID) ? token.getProperty(ISAuthConstants.USER_ID).equals(resourceId) : token.getProperty(ISAuthConstants.USER_ID).equalsIgnoreCase(resourceId);
// If the user wants to modify his password, he should use a different action.
if (isUpdatingHisOwnPassword) {
for (String key : jVal.keys()) {
if (USER_PASSWORD.equalsIgnoreCase(key)) {
return new BadRequestException("Cannot update user password via PUT. " + "Use POST with _action=changePassword or _action=forgotPassword.").asPromise();
}
}
}
newDtls = jsonValueToIdentityDetails(objectType, jVal, realm);
if (newDtls.getAttributes() == null || newDtls.getAttributes().length < 1) {
throw new BadRequestException("Illegal arguments: One or more required arguments is null or empty");
}
if (newDtls.getName() != null && !resourceId.equalsIgnoreCase(newDtls.getName())) {
throw new BadRequestException("id in path does not match id in request body");
}
newDtls.setName(resourceId);
UserAttributeInfo userAttributeInfo = configHandler.getConfig(realm, UserAttributeInfoBuilder.class);
// Handle attribute change when password is required
// Get restSecurity for this realm
RestSecurity restSecurity = restSecurityProvider.get(realm);
// Make sure user is not admin and check to see if we are requiring a password to change any attributes
Set<String> protectedUserAttributes = new HashSet<>();
protectedUserAttributes.addAll(restSecurity.getProtectedUserAttributes());
protectedUserAttributes.addAll(userAttributeInfo.getProtectedUpdateAttributes());
if (!protectedUserAttributes.isEmpty() && !isAdmin(context)) {
boolean hasReauthenticated = false;
for (String protectedAttr : protectedUserAttributes) {
JsonValue jValAttr = jVal.get(protectedAttr);
if (!jValAttr.isNull()) {
// If attribute is not available set newAttr variable to empty string for use in comparison
String newAttr = (jValAttr.isString()) ? jValAttr.asString() : "";
// Get the value of current attribute
String currentAttr = "";
Map<String, Set<String>> attrs = asMap(dtls.getAttributes());
for (Map.Entry<String, Set<String>> attribute : attrs.entrySet()) {
String attributeName = attribute.getKey();
if (protectedAttr.equalsIgnoreCase(attributeName)) {
currentAttr = attribute.getValue().iterator().next();
}
}
// Compare newAttr and currentAttr
if (!currentAttr.equals(newAttr) && !hasReauthenticated) {
// check header to make sure that password is there then check to see if it's correct
String strCurrentPass = RestUtils.getMimeHeaderValue(context, CURRENT_PASSWORD);
if (strCurrentPass != null && !strCurrentPass.isEmpty() && checkValidPassword(resourceId, strCurrentPass.toCharArray(), realm)) {
//set a boolean value so we know reauth has been done
hasReauthenticated = true;
//continue will allow attribute(s) change(s)
} else {
throw new BadRequestException("Must provide a valid confirmation password to change " + "protected attribute (" + protectedAttr + ") from '" + currentAttr + "' to '" + newAttr + "'");
}
}
}
}
}
// update resource with new details
identityServices.update(newDtls, token);
String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
debug.message("IdentityResource.updateInstance :: UPDATE of resourceId={} in realm={} performed " + "by principalName={}", resourceId, realm, principalName);
// read updated identity back to client
IdentityDetails checkIdent = identityServices.read(dtls.getName(), getIdentityServicesAttributes(realm, objectType), token);
return newResultPromise(this.identityResourceV1.buildResourceResponse(resourceId, context, checkIdent));
} catch (final ObjectNotFound onf) {
debug.error("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={} : Could not find the " + "resource", resourceId, onf);
return new NotFoundException("Could not find the resource [ " + resourceId + " ] to update", onf).asPromise();
} catch (final NeedMoreCredentials needMoreCredentials) {
debug.error("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={} : Token is not authorized", resourceId, needMoreCredentials);
return new ForbiddenException("Token is not authorized", needMoreCredentials).asPromise();
} catch (final TokenExpired tokenExpired) {
debug.error("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={} : Unauthorized", resourceId, tokenExpired);
return new PermanentException(401, "Unauthorized", null).asPromise();
} catch (final AccessDenied accessDenied) {
debug.error("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={} : Access denied", resourceId, accessDenied);
return new ForbiddenException(accessDenied.getMessage(), accessDenied).asPromise();
} catch (final GeneralFailure generalFailure) {
debug.error("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={}", resourceId, generalFailure);
return new BadRequestException(generalFailure.getMessage(), generalFailure).asPromise();
} catch (BadRequestException bre) {
debug.error("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={}", resourceId, bre);
return bre.asPromise();
} catch (NotFoundException e) {
debug.warning("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={} : Could not find the " + "resource", resourceId, e);
return new NotFoundException("Could not find the resource [ " + resourceId + " ] to update", e).asPromise();
} catch (ResourceException re) {
debug.warning("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={} ", resourceId, re);
return re.asPromise();
} catch (final Exception e) {
debug.error("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={}", resourceId, e);
return new NotFoundException(e.getMessage(), e).asPromise();
}
}
use of org.forgerock.openam.rest.RealmContext in project OpenAM by OpenRock.
the class IdentityResourceV2 method actionCollection.
/**
* {@inheritDoc}
*/
@Override
public Promise<ActionResponse, ResourceException> actionCollection(Context context, ActionRequest request) {
RealmContext realmContext = context.asContext(RealmContext.class);
final String realm = realmContext.getResolvedRealm();
RestSecurity restSecurity = restSecurityProvider.get(realm);
final String action = request.getAction();
if (action.equalsIgnoreCase("idFromSession")) {
return idFromSession(context);
} else if (action.equalsIgnoreCase("register")) {
return createRegistrationEmail(context, request, realm, restSecurity);
} else if (action.equalsIgnoreCase("confirm")) {
return confirmationIdCheck(request, realm);
} else if (action.equalsIgnoreCase("anonymousCreate")) {
return anonymousCreate(context, request, realm, restSecurity);
} else if (action.equalsIgnoreCase("forgotPassword")) {
return generateNewPasswordEmail(context, request, realm, restSecurity);
} else if (action.equalsIgnoreCase("forgotPasswordReset")) {
return anonymousUpdate(context, request, realm);
} else if (action.equalsIgnoreCase("validateGoto")) {
return validateGoto(context, request);
} else {
// for now this is the only case coming in, so fail if otherwise
return RestUtils.generateUnsupportedOperation();
}
}
use of org.forgerock.openam.rest.RealmContext in project OpenAM by OpenRock.
the class RealmResource method queryCollection.
/**
* Returns names of all realms included in the subtree rooted by the realm indicated
* in the query url.
*
* Names are unsorted and given as full paths.
*
* Filtering, sorting, and paging of results is not supported.
*
* {@inheritDoc}
*/
@Override
public Promise<QueryResponse, ResourceException> queryCollection(Context context, QueryRequest request, QueryResourceHandler handler) {
final String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
final RealmContext realmContext = context.asContext(RealmContext.class);
final String realmPath = realmContext.getResolvedRealm();
try {
final SSOTokenManager mgr = SSOTokenManager.getInstance();
final SSOToken ssoToken = mgr.createSSOToken(getCookieFromServerContext(context));
final OrganizationConfigManager ocm = new OrganizationConfigManager(ssoToken, realmPath);
final List<String> realmsInSubTree = new ArrayList<String>();
realmsInSubTree.add(realmPath);
for (final Object subRealmRelativePath : ocm.getSubOrganizationNames("*", true)) {
if (realmPath.endsWith("/")) {
realmsInSubTree.add(realmPath + subRealmRelativePath);
} else {
realmsInSubTree.add(realmPath + "/" + subRealmRelativePath);
}
}
debug.message("RealmResource :: QUERY : performed by " + principalName);
for (final Object realmName : realmsInSubTree) {
JsonValue val = new JsonValue(realmName);
ResourceResponse resource = newResourceResponse((String) realmName, "0", val);
handler.handleResource(resource);
}
return newResultPromise(newQueryResponse());
} catch (SSOException ex) {
debug.error("RealmResource :: QUERY by " + principalName + " failed : " + ex);
return new ForbiddenException().asPromise();
} catch (SMSException ex) {
debug.error("RealmResource :: QUERY by " + principalName + " failed :" + ex);
switch(ex.getExceptionCode()) {
case STATUS_NO_PERMISSION:
// This exception will be thrown if permission to read realms from SMS has not been delegated
return new ForbiddenException().asPromise();
default:
return new InternalServerErrorException().asPromise();
}
}
}
Aggregations