Search in sources :

Example 16 with ConfigAttribute

use of org.springframework.security.access.ConfigAttribute in project spring-security-oauth by spring-projects.

the class ScopeVoter method vote.

public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
    int result = ACCESS_ABSTAIN;
    if (!(authentication instanceof OAuth2Authentication)) {
        return result;
    }
    for (ConfigAttribute attribute : attributes) {
        if (denyAccess.equals(attribute.getAttribute())) {
            return ACCESS_DENIED;
        }
    }
    OAuth2Request clientAuthentication = ((OAuth2Authentication) authentication).getOAuth2Request();
    for (ConfigAttribute attribute : attributes) {
        if (this.supports(attribute)) {
            result = ACCESS_DENIED;
            Set<String> scopes = clientAuthentication.getScope();
            for (String scope : scopes) {
                if (attribute.getAttribute().toUpperCase().equals((scopePrefix + scope).toUpperCase())) {
                    return ACCESS_GRANTED;
                }
            }
            if (result == ACCESS_DENIED && throwException) {
                InsufficientScopeException failure = new InsufficientScopeException("Insufficient scope for this resource", Collections.singleton(attribute.getAttribute().substring(scopePrefix.length())));
                throw new AccessDeniedException(failure.getMessage(), failure);
            }
        }
    }
    return result;
}
Also used : InsufficientScopeException(org.springframework.security.oauth2.common.exceptions.InsufficientScopeException) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) AccessDeniedException(org.springframework.security.access.AccessDeniedException) ConfigAttribute(org.springframework.security.access.ConfigAttribute) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication)

Example 17 with ConfigAttribute

use of org.springframework.security.access.ConfigAttribute in project spring-security by spring-projects.

the class MethodSecurityMetadataSourceBeanDefinitionParser method parseInternal.

public AbstractBeanDefinition parseInternal(Element elt, ParserContext pc) {
    // Parse the included methods
    List<Element> methods = DomUtils.getChildElementsByTagName(elt, Elements.PROTECT);
    Map<String, List<ConfigAttribute>> mappings = new LinkedHashMap<String, List<ConfigAttribute>>();
    for (Element protectmethodElt : methods) {
        String[] tokens = StringUtils.commaDelimitedListToStringArray(protectmethodElt.getAttribute(ATT_ACCESS));
        String methodName = protectmethodElt.getAttribute(ATT_METHOD);
        mappings.put(methodName, SecurityConfig.createList(tokens));
    }
    RootBeanDefinition metadataSource = new RootBeanDefinition(MapBasedMethodSecurityMetadataSource.class);
    metadataSource.getConstructorArgumentValues().addGenericArgumentValue(mappings);
    return metadataSource;
}
Also used : ConfigAttribute(org.springframework.security.access.ConfigAttribute) Element(org.w3c.dom.Element) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) List(java.util.List) LinkedHashMap(java.util.LinkedHashMap)

Example 18 with ConfigAttribute

use of org.springframework.security.access.ConfigAttribute in project spring-security by spring-projects.

the class ExpressionBasedMessageSecurityMetadataSourceFactory method createExpressionMessageMetadataSource.

/**
	 * Create a {@link MessageSecurityMetadataSource} that uses {@link MessageMatcher}
	 * mapped to Spring Expressions. Each entry is considered in order and only the first
	 * match is used.
	 *
	 * For example:
	 *
	 * <pre>
	 *     LinkedHashMap&lt;MessageMatcher&lt;?&gt;,String&gt; matcherToExpression = new LinkedHashMap&lt;MessageMatcher&lt;Object&gt;,String&gt;();
	 *     matcherToExpression.put(new SimDestinationMessageMatcher("/public/**"), "permitAll");
	 *     matcherToExpression.put(new SimDestinationMessageMatcher("/admin/**"), "hasRole('ROLE_ADMIN')");
	 *     matcherToExpression.put(new SimDestinationMessageMatcher("/**"), "authenticated");
	 *
	 *     MessageSecurityMetadataSource metadataSource = createExpressionMessageMetadataSource(matcherToExpression);
	 * </pre>
	 *
	 * <p>
	 * If our destination is "/public/hello", it would match on "/public/**" and on "/**".
	 * However, only "/public/**" would be used since it is the first entry. That means
	 * that a destination of "/public/hello" will be mapped to "permitAll".
	 * </p>
	 *
	 * <p>
	 * For a complete listing of expressions see {@link MessageSecurityExpressionRoot}
	 * </p>
	 *
	 * @param matcherToExpression an ordered mapping of {@link MessageMatcher} to Strings
	 * that are turned into an Expression using
	 * {@link DefaultMessageSecurityExpressionHandler#getExpressionParser()}
	 * @param handler the {@link SecurityExpressionHandler} to use
	 * @return the {@link MessageSecurityMetadataSource} to use. Cannot be null.
	 */
public static MessageSecurityMetadataSource createExpressionMessageMetadataSource(LinkedHashMap<MessageMatcher<?>, String> matcherToExpression, SecurityExpressionHandler<Message<Object>> handler) {
    LinkedHashMap<MessageMatcher<?>, Collection<ConfigAttribute>> matcherToAttrs = new LinkedHashMap<MessageMatcher<?>, Collection<ConfigAttribute>>();
    for (Map.Entry<MessageMatcher<?>, String> entry : matcherToExpression.entrySet()) {
        MessageMatcher<?> matcher = entry.getKey();
        String rawExpression = entry.getValue();
        Expression expression = handler.getExpressionParser().parseExpression(rawExpression);
        ConfigAttribute attribute = new MessageExpressionConfigAttribute(expression);
        matcherToAttrs.put(matcher, Arrays.asList(attribute));
    }
    return new DefaultMessageSecurityMetadataSource(matcherToAttrs);
}
Also used : MessageMatcher(org.springframework.security.messaging.util.matcher.MessageMatcher) ConfigAttribute(org.springframework.security.access.ConfigAttribute) Expression(org.springframework.expression.Expression) Collection(java.util.Collection) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) DefaultMessageSecurityMetadataSource(org.springframework.security.messaging.access.intercept.DefaultMessageSecurityMetadataSource) LinkedHashMap(java.util.LinkedHashMap)

Example 19 with ConfigAttribute

use of org.springframework.security.access.ConfigAttribute in project spring-security by spring-projects.

the class ExpressionBasedMessageSecurityMetadataSourceFactoryTests method createExpressionMessageMetadataSourceMatchSecond.

@Test
public void createExpressionMessageMetadataSourceMatchSecond() {
    when(matcher2.matches(message)).thenReturn(true);
    Collection<ConfigAttribute> attrs = source.getAttributes(message);
    assertThat(attrs.size()).isEqualTo(1);
    ConfigAttribute attr = attrs.iterator().next();
    assertThat(attr).isInstanceOf(MessageExpressionConfigAttribute.class);
    assertThat(((MessageExpressionConfigAttribute) attr).getAuthorizeExpression().getValue(rootObject)).isEqualTo(false);
}
Also used : ConfigAttribute(org.springframework.security.access.ConfigAttribute) Test(org.junit.Test)

Example 20 with ConfigAttribute

use of org.springframework.security.access.ConfigAttribute in project spring-security by spring-projects.

the class AclEntryVoter method vote.

public int vote(Authentication authentication, MethodInvocation object, Collection<ConfigAttribute> attributes) {
    for (ConfigAttribute attr : attributes) {
        if (!this.supports(attr)) {
            continue;
        }
        // Need to make an access decision on this invocation
        // Attempt to locate the domain object instance to process
        Object domainObject = getDomainObjectInstance(object);
        // If domain object is null, vote to abstain
        if (domainObject == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Voting to abstain - domainObject is null");
            }
            return ACCESS_ABSTAIN;
        }
        // Evaluate if we are required to use an inner domain object
        if (StringUtils.hasText(internalMethod)) {
            try {
                Class<?> clazz = domainObject.getClass();
                Method method = clazz.getMethod(internalMethod, new Class[0]);
                domainObject = method.invoke(domainObject);
            } catch (NoSuchMethodException nsme) {
                throw new AuthorizationServiceException("Object of class '" + domainObject.getClass() + "' does not provide the requested internalMethod: " + internalMethod);
            } catch (IllegalAccessException iae) {
                logger.debug("IllegalAccessException", iae);
                throw new AuthorizationServiceException("Problem invoking internalMethod: " + internalMethod + " for object: " + domainObject);
            } catch (InvocationTargetException ite) {
                logger.debug("InvocationTargetException", ite);
                throw new AuthorizationServiceException("Problem invoking internalMethod: " + internalMethod + " for object: " + domainObject);
            }
        }
        // Obtain the OID applicable to the domain object
        ObjectIdentity objectIdentity = objectIdentityRetrievalStrategy.getObjectIdentity(domainObject);
        // Obtain the SIDs applicable to the principal
        List<Sid> sids = sidRetrievalStrategy.getSids(authentication);
        Acl acl;
        try {
            // Lookup only ACLs for SIDs we're interested in
            acl = aclService.readAclById(objectIdentity, sids);
        } catch (NotFoundException nfe) {
            if (logger.isDebugEnabled()) {
                logger.debug("Voting to deny access - no ACLs apply for this principal");
            }
            return ACCESS_DENIED;
        }
        try {
            if (acl.isGranted(requirePermission, sids, false)) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Voting to grant access");
                }
                return ACCESS_GRANTED;
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("Voting to deny access - ACLs returned, but insufficient permissions for this principal");
                }
                return ACCESS_DENIED;
            }
        } catch (NotFoundException nfe) {
            if (logger.isDebugEnabled()) {
                logger.debug("Voting to deny access - no ACLs apply for this principal");
            }
            return ACCESS_DENIED;
        }
    }
    // No configuration attribute matched, so abstain
    return ACCESS_ABSTAIN;
}
Also used : ConfigAttribute(org.springframework.security.access.ConfigAttribute) NotFoundException(org.springframework.security.acls.model.NotFoundException) Method(java.lang.reflect.Method) Acl(org.springframework.security.acls.model.Acl) InvocationTargetException(java.lang.reflect.InvocationTargetException) Sid(org.springframework.security.acls.model.Sid) ObjectIdentity(org.springframework.security.acls.model.ObjectIdentity) AuthorizationServiceException(org.springframework.security.access.AuthorizationServiceException)

Aggregations

ConfigAttribute (org.springframework.security.access.ConfigAttribute)88 Test (org.junit.Test)54 SecurityConfig (org.springframework.security.access.SecurityConfig)21 FilterInvocation (org.springframework.security.web.FilterInvocation)15 AccessDeniedException (org.springframework.security.access.AccessDeniedException)13 MockMethodInvocation (org.springframework.security.access.intercept.method.MockMethodInvocation)12 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)10 ArrayList (java.util.ArrayList)9 LinkedHashMap (java.util.LinkedHashMap)8 Authentication (org.springframework.security.core.Authentication)8 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)8 Collection (java.util.Collection)6 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)6 Method (java.lang.reflect.Method)5 List (java.util.List)5 MethodInvocation (org.aopalliance.intercept.MethodInvocation)5 GrantedAuthority (org.springframework.security.core.GrantedAuthority)5 RequestMatcher (org.springframework.security.web.util.matcher.RequestMatcher)5 AuthorizationFailureEvent (org.springframework.security.access.event.AuthorizationFailureEvent)4 SimpleMethodInvocation (org.springframework.security.util.SimpleMethodInvocation)4