View Javadoc

    1   package sample.annotations;
    2
    3
    4   import org.acegisecurity.AccessDeniedException;
    5   import org.acegisecurity.GrantedAuthority;
    6   import org.acegisecurity.GrantedAuthorityImpl;
    7   import org.acegisecurity.context.SecurityContextHolder;
    8   import org.acegisecurity.context.SecurityContextImpl;
    9   import org.acegisecurity.providers.TestingAuthenticationToken;
    10
    11  import org.springframework.context.support.ClassPathXmlApplicationContext;
    12
    13
    14  /***
    15   *
    16   * @author Mark St.Godard
    17   * @version $Id: Main.java,v 1.2 2005/11/17 00:56:29 benalex Exp $
    18   */
    19  public class Main {
    20      //~ Methods ================================================================
    21
    22      public static void main(String[] args) throws Exception {
    23          createSecureContext();
    24
    25          ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
    26                  "applicationContext-annotations.xml");
    27          BankService service = (BankService) context.getBean("bankService");
    28
    29          // will succeed
    30          service.listAccounts();
    31
    32          // will fail
    33          try {
    34              System.out.println(
    35                  "We expect an AccessDeniedException now, as we do not hold the ROLE_PERMISSION_BALANCE granted authority, and we're using a unanimous access decision manager... ");
    36              service.balance("1");
    37          } catch (AccessDeniedException e) {
    38              e.printStackTrace();
    39          }
    40
    41          destroySecureContext();
    42      }
    43
    44      /***
    45       * This can be done in a web app by using a filter or
    46       * <code>SpringMvcIntegrationInterceptor</code>.
    47       */
    48      private static void createSecureContext() {
    49          TestingAuthenticationToken auth = new TestingAuthenticationToken("test",
    50                  "test",
    51                  new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_TELLER"), new GrantedAuthorityImpl(
    52                          "ROLE_PERMISSION_LIST")});
    53
    54          SecurityContextHolder.getContext().setAuthentication(auth);
    55      }
    56
    57      private static void destroySecureContext() {
    58          SecurityContextHolder.setContext(new SecurityContextImpl());
    59      }
    60  }