use of org.springframework.security.core.GrantedAuthority in project coffeenet-starter by coffeenet.
the class HumanCoffeeNetUserTest method isAdmin.
@Test
public void isAdmin() {
List<GrantedAuthority> authorities = singletonList(new SimpleGrantedAuthority("ROLE_COFFEENET-ADMIN"));
HumanCoffeeNetUser sut = new HumanCoffeeNetUser("username", "email@coffeenet", authorities);
assertThat(sut.isCoffeeNetAdmin(), is(true));
}
use of org.springframework.security.core.GrantedAuthority in project midpoint by Evolveum.
the class SecurityEnforcerImpl method isAuthorizedInternal.
private <O extends ObjectType, T extends ObjectType> boolean isAuthorizedInternal(MidPointPrincipal midPointPrincipal, String operationUrl, AuthorizationPhaseType phase, PrismObject<O> object, ObjectDelta<O> delta, PrismObject<T> target, OwnerResolver ownerResolver) throws SchemaException {
if (AuthorizationConstants.AUTZ_NO_ACCESS_URL.equals(operationUrl)) {
return false;
}
if (phase == null) {
throw new IllegalArgumentException("No phase");
}
boolean allow = false;
LOGGER.trace("AUTZ: evaluating authorization principal={}, op={}, phase={}, object={}, delta={}, target={}", midPointPrincipal, operationUrl, phase, object, delta, target);
final Collection<ItemPath> allowedItems = new ArrayList<>();
Collection<Authorization> authorities = getAuthorities(midPointPrincipal);
if (authorities != null) {
for (GrantedAuthority authority : authorities) {
if (authority instanceof Authorization) {
Authorization autz = (Authorization) authority;
String autzHumanReadableDesc = autz.getHumanReadableDesc();
LOGGER.trace("Evaluating {}", autzHumanReadableDesc);
// action
if (!autz.getAction().contains(operationUrl) && !autz.getAction().contains(AuthorizationConstants.AUTZ_ALL_URL)) {
LOGGER.trace(" {} not applicable for operation {}", autzHumanReadableDesc, operationUrl);
continue;
}
// phase
if (autz.getPhase() == null) {
LOGGER.trace(" {} is applicable for all phases (continuing evaluation)", autzHumanReadableDesc);
} else {
if (autz.getPhase() != phase) {
LOGGER.trace(" {} is not applicable for phases {} (breaking evaluation)", autzHumanReadableDesc, phase);
continue;
} else {
LOGGER.trace(" {} is applicable for phases {} (continuing evaluation)", autzHumanReadableDesc, phase);
}
}
// object
if (isApplicable(autz.getObject(), object, midPointPrincipal, ownerResolver, "object", autzHumanReadableDesc)) {
LOGGER.trace(" {} applicable for object {} (continuing evaluation)", autzHumanReadableDesc, object);
} else {
LOGGER.trace(" {} not applicable for object {}, none of the object specifications match (breaking evaluation)", autzHumanReadableDesc, object);
continue;
}
// target
if (isApplicable(autz.getTarget(), target, midPointPrincipal, ownerResolver, "target", autzHumanReadableDesc)) {
LOGGER.trace(" {} applicable for target {} (continuing evaluation)", autzHumanReadableDesc, object);
} else {
LOGGER.trace(" {} not applicable for target {}, none of the target specifications match (breaking evaluation)", autzHumanReadableDesc, object);
continue;
}
// authority is applicable to this situation. now we can process the decision.
AuthorizationDecisionType decision = autz.getDecision();
if (decision == null || decision == AuthorizationDecisionType.ALLOW) {
// if there is more than one role which specify
// different authz (e.g one role specify allow for whole
// objet, the other role specify allow only for some
// attributes. this ended with allow for whole object (MID-2018)
Collection<ItemPath> allowed = getItems(autz);
if (allow && allowedItems.isEmpty()) {
LOGGER.trace(" {}: ALLOW operation {} (but continue evaluation)", autzHumanReadableDesc, operationUrl);
} else if (allow && allowed.isEmpty()) {
allowedItems.clear();
} else {
allowedItems.addAll(allowed);
}
LOGGER.trace(" {}: ALLOW operation {} (but continue evaluation)", autzHumanReadableDesc, operationUrl);
allow = true;
// Do NOT break here. Other authorization statements may still deny the operation
} else {
// item
if (isApplicableItem(autz, object, delta)) {
LOGGER.trace(" {}: Deny authorization applicable for items (continuing evaluation)", autzHumanReadableDesc);
} else {
LOGGER.trace(" {} not applicable for items (breaking evaluation)", autzHumanReadableDesc);
continue;
}
LOGGER.trace(" {}: DENY operation {}", autzHumanReadableDesc, operationUrl);
allow = false;
// Break right here. Deny cannot be overridden by allow. This decision cannot be changed.
break;
}
} else {
LOGGER.warn("Unknown authority type {} in user {}", authority.getClass(), getUsername(midPointPrincipal));
}
}
}
if (allow) {
// Still check allowedItems. We may still deny the operation.
if (allowedItems.isEmpty()) {
// This means all items are allowed. No need to check anything
LOGGER.trace(" Empty list of allowed items, operation allowed");
} else {
if (delta != null) {
allow = processAuthorizationDelta(delta, allowedItems);
} else if (object != null) {
allow = processAuthorizationObject(object, allowedItems);
}
}
}
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("AUTZ result: principal={}, operation={}: {}", midPointPrincipal, operationUrl, allow);
}
return allow;
}
use of org.springframework.security.core.GrantedAuthority in project midpoint by Evolveum.
the class SecurityEnforcerImpl method getAuthorities.
private Collection<Authorization> getAuthorities(MidPointPrincipal principal) {
if (principal == null) {
// Anonymous access, possibly with elevated privileges
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Collection<Authorization> authorizations = new ArrayList<>();
if (authentication != null) {
for (GrantedAuthority authority : authentication.getAuthorities()) {
if (authority instanceof Authorization) {
authorizations.add((Authorization) authority);
}
}
}
return authorizations;
} else {
return principal.getAuthorities();
}
}
use of org.springframework.security.core.GrantedAuthority in project midpoint by Evolveum.
the class SecurityEnforcerImpl method preProcessObjectFilterInternal.
private <T extends ObjectType, O extends ObjectType> ObjectFilter preProcessObjectFilterInternal(MidPointPrincipal principal, String operationUrl, AuthorizationPhaseType phase, boolean includeNullPhase, Class<T> objectType, PrismObject<O> object, boolean includeSpecial, ObjectFilter origFilter, String desc) throws SchemaException {
Collection<Authorization> authorities = getAuthorities(principal);
ObjectFilter securityFilterAllow = null;
ObjectFilter securityFilterDeny = null;
QueryItemsSpec queryItemsSpec = new QueryItemsSpec();
// MID-3916
queryItemsSpec.addRequiredItems(origFilter);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace(" Initial query items spec {}", queryItemsSpec.shortDump());
}
boolean hasAllowAll = false;
if (authorities != null) {
for (GrantedAuthority authority : authorities) {
if (authority instanceof Authorization) {
Authorization autz = (Authorization) authority;
String autzHumanReadableDesc = autz.getHumanReadableDesc();
LOGGER.trace("Evaluating {}", autzHumanReadableDesc);
// action
if (!autz.getAction().contains(operationUrl) && !autz.getAction().contains(AuthorizationConstants.AUTZ_ALL_URL)) {
LOGGER.trace(" Authorization not applicable for operation {}", operationUrl);
continue;
}
// phase
if (autz.getPhase() == phase || (includeNullPhase && autz.getPhase() == null)) {
LOGGER.trace(" Authorization is applicable for phases {} (continuing evaluation)", phase);
} else {
LOGGER.trace(" Authorization is not applicable for phase {}", phase);
continue;
}
// object or target
String objectTargetSpec;
ObjectFilter autzObjSecurityFilter = null;
List<OwnedObjectSelectorType> objectSpecTypes;
if (object == null) {
// object not present. Therefore we are looking for object here
objectSpecTypes = autz.getObject();
objectTargetSpec = "object";
} else {
// object present. Therefore we are looking for target
objectSpecTypes = autz.getTarget();
objectTargetSpec = "target";
// .. but we need to decide whether this authorization is applicable to the object
if (isApplicable(autz.getObject(), object, principal, null, "object", autzHumanReadableDesc)) {
LOGGER.trace(" Authorization is applicable for object {}", object);
} else {
LOGGER.trace(" Authorization is not applicable for object {}", object);
continue;
}
}
boolean applicable = true;
if (objectSpecTypes == null || objectSpecTypes.isEmpty()) {
LOGGER.trace(" No {} specification in authorization (authorization is universaly applicable)", objectTargetSpec);
autzObjSecurityFilter = AllFilter.createAll();
} else {
applicable = false;
for (OwnedObjectSelectorType objectSpecType : objectSpecTypes) {
ObjectFilter objSpecSecurityFilter = null;
TypeFilter objSpecTypeFilter = null;
SearchFilterType specFilterType = objectSpecType.getFilter();
ObjectReferenceType specOrgRef = objectSpecType.getOrgRef();
OrgRelationObjectSpecificationType specOrgRelation = objectSpecType.getOrgRelation();
RoleRelationObjectSpecificationType specRoleRelation = objectSpecType.getRoleRelation();
QName specTypeQName = objectSpecType.getType();
PrismObjectDefinition<T> objectDefinition = null;
// Type
if (specTypeQName != null) {
specTypeQName = prismContext.getSchemaRegistry().qualifyTypeName(specTypeQName);
PrismObjectDefinition<?> specObjectDef = prismContext.getSchemaRegistry().findObjectDefinitionByType(specTypeQName);
if (specObjectDef == null) {
throw new SchemaException("Unknown object type " + specTypeQName + " in " + autzHumanReadableDesc);
}
Class<?> specObjectClass = specObjectDef.getCompileTimeClass();
if (!objectType.isAssignableFrom(specObjectClass)) {
LOGGER.trace(" Authorization not applicable for object because of type mismatch, authorization {}, query {}", new Object[] { specObjectClass, objectType });
continue;
} else {
LOGGER.trace(" Authorization is applicable for object because of type match, authorization {}, query {}", new Object[] { specObjectClass, objectType });
// The spec type is a subclass of requested type. So it might be returned from the search.
// We need to use type filter.
objSpecTypeFilter = TypeFilter.createType(specTypeQName, null);
// and now we have a more specific object definition to use later in filter processing
objectDefinition = (PrismObjectDefinition<T>) specObjectDef;
}
}
// Owner
if (objectSpecType.getOwner() != null) {
if (objectDefinition == null) {
objectDefinition = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(objectType);
}
// TODO: MID-3899
if (AbstractRoleType.class.isAssignableFrom(objectType)) {
objSpecSecurityFilter = applyOwnerFilterOwnerRef(new ItemPath(AbstractRoleType.F_OWNER_REF), objSpecSecurityFilter, principal, objectDefinition);
} else if (TaskType.class.isAssignableFrom(objectType)) {
objSpecSecurityFilter = applyOwnerFilterOwnerRef(new ItemPath(TaskType.F_OWNER_REF), objSpecSecurityFilter, principal, objectDefinition);
} else {
LOGGER.trace(" Authorization not applicable for object because it has owner specification (this is not applicable for search)");
continue;
}
}
// // Delegator
// if (objectSpecType.getDelegator() != null) {
// if (objectDefinition == null) {
// objectDefinition = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(objectType);
// }
// // TODO: MID-3899
// if (UserType.class.isAssignableFrom(objectType)) { TODO
// objSpecSecurityFilter = applyOwnerFilterOwnerRef(new ItemPath(AbstractRoleType.F_OWNER_REF), objSpecSecurityFilter, principal, objectDefinition);
// } else if (TaskType.class.isAssignableFrom(objectType)) {
// objSpecSecurityFilter = applyOwnerFilterOwnerRef(new ItemPath(TaskType.F_OWNER_REF), objSpecSecurityFilter, principal, objectDefinition);
// } else {
// LOGGER.trace(" Authorization not applicable for object because it has owner specification (this is not applicable for search)");
// continue;
// }
// }
applicable = true;
// Special
List<SpecialObjectSpecificationType> specSpecial = objectSpecType.getSpecial();
if (specSpecial != null && !specSpecial.isEmpty()) {
if (!includeSpecial) {
LOGGER.trace(" Skipping authorization, because specials are present: {}", specSpecial);
applicable = false;
}
if (specFilterType != null || specOrgRef != null || specOrgRelation != null || specRoleRelation != null) {
throw new SchemaException("Both filter/org/role and special object specification specified in authorization");
}
ObjectFilter specialFilter = null;
for (SpecialObjectSpecificationType special : specSpecial) {
if (special == SpecialObjectSpecificationType.SELF) {
String principalOid = principal.getOid();
specialFilter = ObjectQueryUtil.filterOr(specialFilter, InOidFilter.createInOid(principalOid));
} else {
throw new SchemaException("Unsupported special object specification specified in authorization: " + special);
}
}
objSpecSecurityFilter = specTypeQName != null ? TypeFilter.createType(specTypeQName, specialFilter) : specialFilter;
} else {
LOGGER.trace(" specials empty: {}", specSpecial);
}
// Filter
if (specFilterType != null) {
if (objectDefinition == null) {
objectDefinition = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(objectType);
}
ObjectFilter specFilter = QueryJaxbConvertor.createObjectFilter(objectDefinition, specFilterType, prismContext);
if (specFilter != null) {
ObjectQueryUtil.assertNotRaw(specFilter, "Filter in authorization object has undefined items. Maybe a 'type' specification is missing in the authorization?");
ObjectQueryUtil.assertPropertyOnly(specFilter, "Filter in authorization object is not property-only filter");
}
LOGGER.trace(" applying property filter {}", specFilter);
objSpecSecurityFilter = ObjectQueryUtil.filterAnd(objSpecSecurityFilter, specFilter);
} else {
LOGGER.trace(" filter empty");
}
// Org
if (specOrgRef != null) {
ObjectFilter orgFilter = QueryBuilder.queryFor(ObjectType.class, prismContext).isChildOf(specOrgRef.getOid()).buildFilter();
objSpecSecurityFilter = ObjectQueryUtil.filterAnd(objSpecSecurityFilter, orgFilter);
LOGGER.trace(" applying org filter {}", orgFilter);
} else {
LOGGER.trace(" org empty");
}
// orgRelation
if (specOrgRelation != null) {
ObjectFilter objSpecOrgRelationFilter = null;
QName subjectRelation = specOrgRelation.getSubjectRelation();
for (ObjectReferenceType subjectParentOrgRef : principal.getUser().getParentOrgRef()) {
if (MiscSchemaUtil.compareRelation(subjectRelation, subjectParentOrgRef.getRelation())) {
S_FilterEntryOrEmpty q = QueryBuilder.queryFor(ObjectType.class, prismContext);
S_AtomicFilterExit q2;
if (specOrgRelation.getScope() == null || specOrgRelation.getScope() == OrgScopeType.ALL_DESCENDANTS) {
q2 = q.isChildOf(subjectParentOrgRef.getOid());
} else if (specOrgRelation.getScope() == OrgScopeType.DIRECT_DESCENDANTS) {
q2 = q.isDirectChildOf(subjectParentOrgRef.getOid());
} else if (specOrgRelation.getScope() == OrgScopeType.ALL_ANCESTORS) {
q2 = q.isParentOf(subjectParentOrgRef.getOid());
} else {
throw new UnsupportedOperationException("Unknown orgRelation scope " + specOrgRelation.getScope());
}
if (BooleanUtils.isTrue(specOrgRelation.isIncludeReferenceOrg())) {
q2 = q2.or().id(subjectParentOrgRef.getOid());
}
objSpecOrgRelationFilter = ObjectQueryUtil.filterOr(objSpecOrgRelationFilter, q2.buildFilter());
}
}
if (objSpecOrgRelationFilter == null) {
objSpecOrgRelationFilter = NoneFilter.createNone();
}
objSpecSecurityFilter = ObjectQueryUtil.filterAnd(objSpecSecurityFilter, objSpecOrgRelationFilter);
LOGGER.trace(" applying orgRelation filter {}", objSpecOrgRelationFilter);
} else {
LOGGER.trace(" orgRelation empty");
}
// roleRelation
if (specRoleRelation != null) {
ObjectFilter objSpecRoleRelationFilter = processRoleRelationFilter(principal, autz, specRoleRelation, queryItemsSpec, origFilter);
if (objSpecRoleRelationFilter == null) {
if (autz.maySkipOnSearch()) {
LOGGER.trace(" not applying roleRelation filter because it is not efficient and maySkipOnSearch is set", objSpecRoleRelationFilter);
applicable = false;
} else {
objSpecRoleRelationFilter = NoneFilter.createNone();
}
}
if (objSpecRoleRelationFilter != null) {
objSpecSecurityFilter = ObjectQueryUtil.filterAnd(objSpecSecurityFilter, objSpecRoleRelationFilter);
LOGGER.trace(" applying roleRelation filter {}", objSpecRoleRelationFilter);
}
} else {
LOGGER.trace(" roleRelation empty");
}
if (objSpecTypeFilter != null) {
objSpecTypeFilter.setFilter(objSpecSecurityFilter);
objSpecSecurityFilter = objSpecTypeFilter;
}
traceFilter("objSpecSecurityFilter", objectSpecType, objSpecSecurityFilter);
autzObjSecurityFilter = ObjectQueryUtil.filterOr(autzObjSecurityFilter, objSpecSecurityFilter);
}
}
traceFilter("autzObjSecurityFilter", autz, autzObjSecurityFilter);
if (applicable) {
autzObjSecurityFilter = ObjectQueryUtil.simplify(autzObjSecurityFilter);
// authority is applicable to this situation. now we can process the decision.
AuthorizationDecisionType decision = autz.getDecision();
if (decision == null || decision == AuthorizationDecisionType.ALLOW) {
// allow
if (ObjectQueryUtil.isAll(autzObjSecurityFilter)) {
// this is "allow all" authorization.
hasAllowAll = true;
} else {
securityFilterAllow = ObjectQueryUtil.filterOr(securityFilterAllow, autzObjSecurityFilter);
}
if (!ObjectQueryUtil.isNone(autzObjSecurityFilter)) {
queryItemsSpec.addAllowedItems(autz);
}
} else {
// deny
if (autz.getItem() != null && !autz.getItem().isEmpty()) {
// This is a tricky situation. We have deny authorization, but it only denies access to
// some items. Therefore we need to find the objects and then filter out the items.
// Therefore do not add this authorization into the filter.
} else {
if (ObjectQueryUtil.isAll(autzObjSecurityFilter)) {
// This is "deny all". We cannot have anything stronger than that.
// There is no point in continuing the evaluation.
LOGGER.trace("AUTZ {}: principal={}, operation={}: deny all", desc, new Object[] { getUsername(principal), operationUrl });
NoneFilter secFilter = NoneFilter.createNone();
traceFilter("secFilter", null, secFilter);
return secFilter;
}
securityFilterDeny = ObjectQueryUtil.filterOr(securityFilterDeny, autzObjSecurityFilter);
}
}
}
traceFilter("securityFilterAllow", autz, securityFilterAllow);
traceFilter("securityFilterDeny", autz, securityFilterDeny);
} else {
LOGGER.warn("Unknown authority type {} in user {}", authority.getClass(), getUsername(principal));
}
}
}
traceFilter("securityFilterAllow", null, securityFilterAllow);
traceFilter("securityFilterDeny", null, securityFilterDeny);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace(" Final items: {}", queryItemsSpec.shortDump());
}
List<ItemPath> unsatisfiedItems = queryItemsSpec.evaluateUnsatisfierItems();
if (!unsatisfiedItems.isEmpty()) {
LOGGER.trace("AUTZ {}: principal={}, operation={}: deny because items {} are not allowed", desc, getUsername(principal), operationUrl, unsatisfiedItems);
NoneFilter secFilter = NoneFilter.createNone();
traceFilter("secFilter", null, secFilter);
return secFilter;
}
ObjectFilter origWithAllowFilter;
if (hasAllowAll) {
origWithAllowFilter = origFilter;
} else if (securityFilterAllow == null) {
// Nothing has been allowed. This means default deny.
LOGGER.trace("AUTZ {}: principal={}, operation={}: default deny", desc, getUsername(principal), operationUrl);
NoneFilter secFilter = NoneFilter.createNone();
traceFilter("secFilter", null, secFilter);
return secFilter;
} else {
origWithAllowFilter = ObjectQueryUtil.filterAnd(origFilter, securityFilterAllow);
}
if (securityFilterDeny == null) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("AUTZ {}: principal={}, operation={}: allow:\n{}", desc, getUsername(principal), operationUrl, origWithAllowFilter == null ? "null" : origWithAllowFilter.debugDump());
}
traceFilter("origWithAllowFilter", null, origWithAllowFilter);
return origWithAllowFilter;
} else {
ObjectFilter secFilter = ObjectQueryUtil.filterAnd(origWithAllowFilter, NotFilter.createNot(securityFilterDeny));
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("AUTZ {}: principal={}, operation={}: allow (with deny clauses):\n{}", desc, getUsername(principal), operationUrl, secFilter == null ? "null" : secFilter.debugDump());
}
traceFilter("secFilter", null, secFilter);
return secFilter;
}
}
use of org.springframework.security.core.GrantedAuthority in project dhis2-core by dhis2.
the class DhisConvenienceTest method saveAndInjectUserSecurityContext.
protected void saveAndInjectUserSecurityContext(User user) {
userService.addUser(user);
userService.addUserCredentials(user.getUserCredentials());
List<GrantedAuthority> grantedAuthorities = user.getUserCredentials().getAllAuthorities().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
UserDetails userDetails = new org.springframework.security.core.userdetails.User(user.getUserCredentials().getUsername(), user.getUserCredentials().getPassword(), grantedAuthorities);
Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, "", grantedAuthorities);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
Aggregations