use of org.springframework.security.access.AccessDeniedException in project midpoint by Evolveum.
the class SecurityEnforcerImpl method decide.
/**
* Spring security method. It is practically applicable only for simple cases.
*/
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
if (object instanceof MethodInvocation) {
MethodInvocation methodInvocation = (MethodInvocation) object;
// TODO
} else if (object instanceof FilterInvocation) {
FilterInvocation filterInvocation = (FilterInvocation) object;
// TODO
} else {
SecurityUtil.logSecurityDeny(object, ": Unknown type of secure object");
throw new IllegalArgumentException("Unknown type of secure object");
}
Object principalObject = authentication.getPrincipal();
if (!(principalObject instanceof MidPointPrincipal)) {
if (authentication.getPrincipal() instanceof String && "anonymousUser".equals(principalObject)) {
SecurityUtil.logSecurityDeny(object, ": Not logged in");
throw new InsufficientAuthenticationException("Not logged in.");
}
throw new IllegalArgumentException("Expected that spring security principal will be of type " + MidPointPrincipal.class.getName() + " but it was " + principalObject.getClass());
}
Collection<String> configActions = SecurityUtil.getActions(configAttributes);
for (String configAction : configActions) {
boolean isAuthorized;
try {
isAuthorized = isAuthorized(configAction, null, null, null, null, null);
} catch (SchemaException e) {
throw new SystemException(e.getMessage(), e);
}
if (isAuthorized) {
return;
}
}
SecurityUtil.logSecurityDeny(object, ": Not authorized", null, configActions);
// Better message is logged.
throw new AccessDeniedException("Not authorized");
}
use of org.springframework.security.access.AccessDeniedException in project midpoint by Evolveum.
the class AuthenticationEvaluatorImpl method authenticateUserPreAuthenticated.
@Override
public PreAuthenticatedAuthenticationToken authenticateUserPreAuthenticated(ConnectionEnvironment connEnv, String enteredUsername) {
MidPointPrincipal principal = getAndCheckPrincipal(connEnv, enteredUsername, true);
// Authorizations
if (!hasAnyAuthorization(principal)) {
recordAuthenticationFailure(principal, connEnv, "no authorizations");
throw new AccessDeniedException("web.security.provider.access.denied");
}
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, null, principal.getAuthorities());
recordAuthenticationSuccess(principal, connEnv);
return token;
}
use of org.springframework.security.access.AccessDeniedException in project midpoint by Evolveum.
the class MidpointRestAuthenticator method handleRequest.
public void handleRequest(AuthorizationPolicy policy, Message m, ContainerRequestContext requestCtx) {
if (policy == null) {
RestServiceUtil.createAbortMessage(requestCtx);
return;
}
T authenticationContext = createAuthenticationContext(policy, requestCtx);
if (authenticationContext == null) {
return;
}
String enteredUsername = authenticationContext.getUsername();
if (enteredUsername == null) {
RestServiceUtil.createAbortMessage(requestCtx);
return;
}
LOGGER.trace("Authenticating username '{}' to REST service", enteredUsername);
// We need to create task before attempting authentication. Task ID is also a session ID.
Task task = taskManager.createTaskInstance(ModelRestService.OPERATION_REST_SERVICE);
task.setChannel(SchemaConstants.CHANNEL_REST_URI);
ConnectionEnvironment connEnv = ConnectionEnvironment.create(SchemaConstants.CHANNEL_REST_URI);
connEnv.setSessionIdOverride(task.getTaskIdentifier());
UsernamePasswordAuthenticationToken token;
try {
token = getAuthenticationEvaluator().authenticate(connEnv, authenticationContext);
} catch (UsernameNotFoundException | BadCredentialsException e) {
LOGGER.trace("Exception while authenticating username '{}' to REST service: {}", enteredUsername, e.getMessage(), e);
requestCtx.abortWith(Response.status(Status.UNAUTHORIZED).header("WWW-Authenticate", "Basic authentication failed. Cannot authenticate user.").build());
return;
} catch (DisabledException | LockedException | CredentialsExpiredException | AccessDeniedException | AuthenticationCredentialsNotFoundException | AuthenticationServiceException e) {
LOGGER.trace("Exception while authenticating username '{}' to REST service: {}", enteredUsername, e.getMessage(), e);
requestCtx.abortWith(Response.status(Status.FORBIDDEN).build());
return;
}
UserType user = ((MidPointPrincipal) token.getPrincipal()).getUser();
task.setOwner(user.asPrismObject());
// m.put(RestServiceUtil.MESSAGE_PROPERTY_TASK_NAME, task);
if (!authorizeUser(user, null, enteredUsername, connEnv, requestCtx)) {
return;
}
String oid = requestCtx.getHeaderString("Switch-To-Principal");
OperationResult result = task.getResult();
if (StringUtils.isNotBlank(oid)) {
try {
PrismObject<UserType> authorizedUser = model.getObject(UserType.class, oid, null, task, result);
task.setOwner(authorizedUser);
if (!authorizeUser(AuthorizationConstants.AUTZ_REST_PROXY_URL, user, authorizedUser, enteredUsername, connEnv, requestCtx)) {
return;
}
if (!authorizeUser(authorizedUser.asObjectable(), null, authorizedUser.getName().getOrig(), connEnv, requestCtx)) {
return;
}
} catch (ObjectNotFoundException | SchemaException | SecurityViolationException | CommunicationException | ConfigurationException | ExpressionEvaluationException e) {
LOGGER.trace("Exception while authenticating user identified with '{}' to REST service: {}", oid, e.getMessage(), e);
requestCtx.abortWith(Response.status(Status.UNAUTHORIZED).header("WWW-Authenticate", "Proxy Authentication failed. Cannot authenticate user.").build());
return;
}
}
m.put(RestServiceUtil.MESSAGE_PROPERTY_TASK_NAME, task);
LOGGER.trace("Authorized to use REST service ({})", user);
}
use of org.springframework.security.access.AccessDeniedException in project midpoint by Evolveum.
the class MidPointGuiAuthorizationEvaluator method decide.
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
if (!(object instanceof FilterInvocation)) {
return;
}
FilterInvocation filterInvocation = (FilterInvocation) object;
Collection<ConfigAttribute> guiConfigAttr = new ArrayList<>();
for (PageUrlMapping urlMapping : PageUrlMapping.values()) {
addSecurityConfig(filterInvocation, guiConfigAttr, urlMapping.getUrl(), urlMapping.getAction());
}
Map<String, DisplayableValue<String>[]> actions = DescriptorLoader.getActions();
for (Map.Entry<String, DisplayableValue<String>[]> entry : actions.entrySet()) {
addSecurityConfig(filterInvocation, guiConfigAttr, entry.getKey(), entry.getValue());
}
if (configAttributes == null || guiConfigAttr.isEmpty()) {
return;
}
Collection<ConfigAttribute> configAttributesToUse = guiConfigAttr;
if (guiConfigAttr.isEmpty()) {
configAttributesToUse = configAttributes;
}
try {
securityEnforcer.decide(authentication, object, configAttributesToUse);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("DECIDE: authentication={}, object={}, configAttributesToUse={}: OK", authentication, object, configAttributesToUse);
}
} catch (AccessDeniedException | InsufficientAuthenticationException e) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("DECIDE: authentication={}, object={}, configAttributesToUse={}: {}", authentication, object, configAttributesToUse, e);
}
throw e;
}
}
use of org.springframework.security.access.AccessDeniedException in project dhis2-core by dhis2.
the class AddUserAction method execute.
// -------------------------------------------------------------------------
// Action implementation
// -------------------------------------------------------------------------
@Override
public String execute() throws Exception {
if (!userService.canAddOrUpdateUser(ugSelected)) {
throw new AccessDeniedException("You cannot add this user");
}
User currentUser = currentUserService.getCurrentUser();
// ---------------------------------------------------------------------
// User credentials and user
// ---------------------------------------------------------------------
UserCredentials userCredentials = new UserCredentials();
User user = new User();
userCredentials.setUserInfo(user);
user.setUserCredentials(userCredentials);
userCredentials.setUsername(StringUtils.trimToNull(username));
userCredentials.setExternalAuth(externalAuth);
userCredentials.setOpenId(StringUtils.trimToNull(openId));
userCredentials.setLdapId(StringUtils.trimToNull(ldapId));
if (ACCOUNT_ACTION_INVITE.equals(accountAction)) {
userCredentials.setUsername(StringUtils.trimToNull(inviteUsername));
userCredentials.setInvitation(true);
user.setEmail(StringUtils.trimToNull(inviteEmail));
securityService.prepareUserForInvite(user);
} else {
user.setSurname(StringUtils.trimToNull(surname));
user.setFirstName(StringUtils.trimToNull(firstName));
user.setEmail(StringUtils.trimToNull(email));
user.setPhoneNumber(StringUtils.trimToNull(phoneNumber));
userService.encodeAndSetPassword(userCredentials, StringUtils.trimToNull(rawPassword));
}
if (jsonAttributeValues != null) {
attributeService.updateAttributeValues(user, jsonAttributeValues);
}
// ---------------------------------------------------------------------
// Organisation units
// ---------------------------------------------------------------------
Set<OrganisationUnit> dataCaptureOrgUnits = new HashSet<>(selectionManager.getSelectedOrganisationUnits());
user.updateOrganisationUnits(dataCaptureOrgUnits);
Set<OrganisationUnit> dataViewOrgUnits = new HashSet<>(selectionTreeManager.getReloadedSelectedOrganisationUnits());
user.setDataViewOrganisationUnits(dataViewOrgUnits);
if (dataViewOrgUnits.size() == 0 && currentUser.getDataViewOrganisationUnits().size() != 0) {
user.setDataViewOrganisationUnits(new HashSet<>(currentUser.getDataViewOrganisationUnits()));
}
// ---------------------------------------------------------------------
// User roles
// ---------------------------------------------------------------------
Set<UserAuthorityGroup> userAuthorityGroups = new HashSet<>();
for (String id : urSelected) {
userAuthorityGroups.add(userService.getUserAuthorityGroup(id));
}
userService.canIssueFilter(userAuthorityGroups);
userCredentials.setUserAuthorityGroups(userAuthorityGroups);
// ---------------------------------------------------------------------
// Dimension constraints. Note that any new user must inherit dimension
// constraints if any from the current user.
// ---------------------------------------------------------------------
userCredentials.setCogsDimensionConstraints(new HashSet<>(currentUser.getUserCredentials().getCogsDimensionConstraints()));
userCredentials.setCatDimensionConstraints(new HashSet<>(currentUser.getUserCredentials().getCatDimensionConstraints()));
for (String id : dcSelected) {
CategoryOptionGroupSet cogs = categoryService.getCategoryOptionGroupSet(id);
if (cogs != null) {
userCredentials.getCogsDimensionConstraints().add(cogs);
continue;
}
DataElementCategory cat = categoryService.getDataElementCategory(id);
if (cat != null) {
userCredentials.getCatDimensionConstraints().add(cat);
continue;
}
}
// ---------------------------------------------------------------------
// Add User
// ---------------------------------------------------------------------
userService.addUser(user);
userService.addUserCredentials(userCredentials);
// ---------------------------------------------------------------------
// User settings
// ---------------------------------------------------------------------
userSettingService.saveUserSetting(UserSettingKey.UI_LOCALE, LocaleUtils.getLocale(localeUi), user);
userSettingService.saveUserSetting(UserSettingKey.DB_LOCALE, LocaleUtils.getLocale(localeDb), user);
if (ACCOUNT_ACTION_INVITE.equals(accountAction)) {
RestoreOptions restoreOptions = inviteUsername == null || inviteUsername.isEmpty() ? RestoreOptions.INVITE_WITH_USERNAME_CHOICE : RestoreOptions.INVITE_WITH_DEFINED_USERNAME;
securityService.sendRestoreMessage(userCredentials, getRootPath(), restoreOptions);
}
for (String id : ugSelected) {
UserGroup userGroup = userGroupService.getUserGroup(id);
userGroup.addUser(user);
userGroupService.updateUserGroup(userGroup);
}
if (ouwtSelected != null && manager.search(OrganisationUnit.class, ouwtSelected) != null) {
selectionManager.setSelectedOrganisationUnits(Lists.newArrayList(manager.search(OrganisationUnit.class, ouwtSelected)));
} else {
selectionManager.setSelectedOrganisationUnits(currentUser.getOrganisationUnits());
}
return SUCCESS;
}
Aggregations