@Test(expected = AccessDeniedException.class)
 public void accessIsDeniedIfPermissionIsNotGranted() {
   AclService service = mock(AclService.class);
   Acl acl = mock(Acl.class);
   when(acl.isGranted(any(List.class), any(List.class), anyBoolean())).thenReturn(false);
   // Try a second time with no permissions found
   when(acl.isGranted(any(List.class), any(List.class), anyBoolean()))
       .thenThrow(new NotFoundException(""));
   when(service.readAclById(any(ObjectIdentity.class), any(List.class))).thenReturn(acl);
   AclEntryAfterInvocationProvider provider =
       new AclEntryAfterInvocationProvider(service, Arrays.asList(mock(Permission.class)));
   provider.setProcessConfigAttribute("MY_ATTRIBUTE");
   provider.setMessageSource(new SpringSecurityMessageSource());
   provider.setObjectIdentityRetrievalStrategy(mock(ObjectIdentityRetrievalStrategy.class));
   provider.setProcessDomainObjectClass(Object.class);
   provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
   try {
     provider.decide(
         mock(Authentication.class),
         new Object(),
         SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"),
         new Object());
     fail("Expected Exception");
   } catch (AccessDeniedException expected) {
   }
   // Second scenario with no acls found
   provider.decide(
       mock(Authentication.class),
       new Object(),
       SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"),
       new Object());
 }
  private LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> buildRequestMap313() {
    LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap =
        new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>();

    ResourceMapping resourceMapping = new ResourceMapping(getDataSource(), resourceQuery);
    for (Resource resource : (List<Resource>) resourceMapping.execute()) {
      String url = resource.getUrl();
      String role = resource.getRole();

      RequestMatcher key =
          resource.getMatchType().equalsIgnoreCase("ant")
              ? new AntPathRequestMatcher(url)
              : new RegexRequestMatcher(url, null);

      if (requestMap.containsKey(key)) {
        requestMap.get(key).add(new SecurityConfig(role.trim()));
      } else {
        requestMap.put(key, SecurityConfig.createList(role));
      }
    }

    System.out.println("SecurityMetadataSource resourceQuery : " + resourceQuery);
    System.out.println("SecurityMetadataSource resourceMapping : " + resourceMapping);

    return requestMap;
  }
  @Deprecated
  protected LinkedHashMap<RequestKey, Collection<ConfigAttribute>> buildRequestMap() {
    LinkedHashMap<RequestKey, Collection<ConfigAttribute>> requestMap = null;
    requestMap = new LinkedHashMap<RequestKey, Collection<ConfigAttribute>>();

    Map<String, String> resourceMap = this.findResources();

    for (Map.Entry<String, String> entry : resourceMap.entrySet()) {
      RequestKey key = new RequestKey(entry.getKey(), null);
      requestMap.put(key, SecurityConfig.createListFromCommaDelimitedString(entry.getValue()));
    }

    return requestMap;
  }
/**
 * Tests for {@link MapBasedMethodSecurityMetadataSource}.
 *
 * @author Luke Taylor
 * @since 2.0.4
 */
public class MapBasedMethodSecurityMetadataSourceTests {
  private final List<ConfigAttribute> ROLE_A = SecurityConfig.createList("ROLE_A");
  private final List<ConfigAttribute> ROLE_B = SecurityConfig.createList("ROLE_B");
  private MapBasedMethodSecurityMetadataSource mds;
  private Method someMethodString;
  private Method someMethodInteger;

  @Before
  public void initialize() throws Exception {
    mds = new MapBasedMethodSecurityMetadataSource();
    someMethodString = MockService.class.getMethod("someMethod", String.class);
    someMethodInteger = MockService.class.getMethod("someMethod", Integer.class);
  }

  @Test
  public void wildcardedMatchIsOverwrittenByMoreSpecificMatch() {
    mds.addSecureMethod(MockService.class, "some*", ROLE_A);
    mds.addSecureMethod(MockService.class, "someMethod*", ROLE_B);
    assertThat(mds.getAttributes(someMethodInteger, MockService.class)).isEqualTo(ROLE_B);
  }

  @Test
  public void methodsWithDifferentArgumentsAreMatchedCorrectly() throws Exception {
    mds.addSecureMethod(MockService.class, someMethodInteger, ROLE_A);
    mds.addSecureMethod(MockService.class, someMethodString, ROLE_B);

    assertThat(mds.getAttributes(someMethodInteger, MockService.class)).isEqualTo(ROLE_A);
    assertThat(mds.getAttributes(someMethodString, MockService.class)).isEqualTo(ROLE_B);
  }

  @SuppressWarnings("unused")
  private class MockService {
    public void someMethod(String s) {}

    public void someMethod(Integer i) {}
  }
}
  @Test
  public void nullReturnObjectIsIgnored() throws Exception {
    AclService service = mock(AclService.class);
    AclEntryAfterInvocationProvider provider =
        new AclEntryAfterInvocationProvider(service, Arrays.asList(mock(Permission.class)));

    assertThat(
            provider.decide(
                mock(Authentication.class),
                new Object(),
                SecurityConfig.createList("AFTER_ACL_COLLECTION_READ"),
                null))
        .isNull();
    ;
    verify(service, never()).readAclById(any(ObjectIdentity.class), any(List.class));
  }
  @Test
  public void accessIsGrantedIfObjectTypeNotSupported() throws Exception {
    AclEntryAfterInvocationProvider provider =
        new AclEntryAfterInvocationProvider(
            mock(AclService.class), Arrays.asList(mock(Permission.class)));
    provider.setProcessDomainObjectClass(String.class);
    // Not a String
    Object returned = new Object();

    assertThat(returned)
        .isSameAs(
            provider.decide(
                mock(Authentication.class),
                new Object(),
                SecurityConfig.createList("AFTER_ACL_READ"),
                returned));
  }
    @Override
    public boolean authenticate(String username, String password) throws Exception {
      Authentication token = new UsernamePasswordAuthenticationToken(username, password);
      try {
        // Authenticate first to make sure credentials are valid
        token = this.authenticationManager.authenticate(token);
      } catch (AuthenticationException ex) {
        return false;
      }

      // Test access rights if a Spring Security AccessDecisionManager is installed
      if (this.accessDecisionManager != null && token.isAuthenticated() && this.roles != null) {
        try {
          this.accessDecisionManager.decide(token, this, SecurityConfig.createList(this.roles));
        } catch (AccessDeniedException ex) {
          return false;
        }
      }
      return token.isAuthenticated();
    }
  @Deprecated
  private LinkedHashMap<RequestKey, Collection<ConfigAttribute>> buildRequestMap301() {
    LinkedHashMap<RequestKey, Collection<ConfigAttribute>> requestMap =
        new LinkedHashMap<RequestKey, Collection<ConfigAttribute>>();

    ResourceMapping resourceMapping = new ResourceMapping(getDataSource(), resourceQuery);
    for (Resource resource : (List<Resource>) resourceMapping.execute()) {
      String url = resource.getUrl();
      String role = resource.getRole();

      RequestKey key = new RequestKey(url, null);

      if (requestMap.containsKey(key)) {
        requestMap.get(key).add(new SecurityConfig(role.trim()));
      } else {
        requestMap.put(new RequestKey(url, null), SecurityConfig.createList(role));
      }
    }

    return requestMap;
  }
  protected LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> buildMap() {
    LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> map =
        new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>();
    for (Map.Entry<String, String> entry : definition.entrySet()) {
      String value = entry.getValue();
      if (value == null) {
        throw new IllegalArgumentException("The rule for URL '" + value + "' cannot be null");
      }
      value = value.trim();

      if (!SUPPORTED.contains(value)) {
        throw new IllegalArgumentException(
            "The rule for URL '"
                + value
                + "' must be one of REQUIRES_SECURE_CHANNEL, REQUIRES_INSECURE_CHANNEL, or ANY_CHANNEL");
      }

      map.put(new AntPathRequestMatcher(entry.getKey()), SecurityConfig.createList(value));
    }
    return map;
  }
예제 #10
0
  public void execute(
      FilterSecurityInterceptor filterSecurityInterceptor, Map<String, String> resourceMap) {
    Assert.notNull(filterSecurityInterceptor);
    Assert.notNull(resourceMap);

    logger.info("refresh url resource");

    LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = null;
    requestMap = new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>();

    for (Map.Entry<String, String> entry : resourceMap.entrySet()) {
      String key = entry.getKey();
      String value = entry.getValue();
      requestMap.put(
          new AntPathRequestMatcher(key), SecurityConfig.createListFromCommaDelimitedString(value));
    }

    FilterInvocationSecurityMetadataSource source =
        new DefaultFilterInvocationSecurityMetadataSource(requestMap);
    filterSecurityInterceptor.setSecurityMetadataSource(source);
  }
  @Test
  public void accessIsAllowedIfPermissionIsGranted() {
    AclService service = mock(AclService.class);
    Acl acl = mock(Acl.class);
    when(acl.isGranted(any(List.class), any(List.class), anyBoolean())).thenReturn(true);
    when(service.readAclById(any(ObjectIdentity.class), any(List.class))).thenReturn(acl);
    AclEntryAfterInvocationProvider provider =
        new AclEntryAfterInvocationProvider(service, Arrays.asList(mock(Permission.class)));
    provider.setMessageSource(new SpringSecurityMessageSource());
    provider.setObjectIdentityRetrievalStrategy(mock(ObjectIdentityRetrievalStrategy.class));
    provider.setProcessDomainObjectClass(Object.class);
    provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
    Object returned = new Object();

    assertThat(returned)
        .isSameAs(
            provider.decide(
                mock(Authentication.class),
                new Object(),
                SecurityConfig.createList("AFTER_ACL_READ"),
                returned));
  }