Example usage for org.springframework.security.core.context SecurityContextHolder clearContext

List of usage examples for org.springframework.security.core.context SecurityContextHolder clearContext

Introduction

In this page you can find the example usage for org.springframework.security.core.context SecurityContextHolder clearContext.

Prototype

public static void clearContext() 

Source Link

Document

Explicitly clears the context value from the current thread.

Usage

From source file:de.itsvs.cwtrpc.security.AbstractRpcAuthenticationProcessingFilter.java

@Override
protected void process(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    final Authentication authentication;
    RpcSessionInvalidationPolicy policy = null;
    boolean ok = false;

    try {//from   w w  w  .j  av  a  2  s. c om
        try {
            authentication = attemptAuthentication(request, response);
            if (authentication == null) {
                return;
            }

            /*
             * Since authentication strategy may require the session, we
             * need to prepare the session.
             */
            policy = getRpcHttpSessionStrategy().prepareSession(request, response);

            applySessionAuthenticationStrategy(authentication, request, response);
        } catch (AuthenticationException e) {
            if (e instanceof AuthenticationServiceException) {
                log.error("An authentication service error occured", e);
            } else {
                log.info("Authentication failed", e);
            }
            unsuccessfulAuthentication(request, response, e);
            return;
        }

        successfulAuthentication(request, response, authentication);
        chain.doFilter(request, response);
        if (SecurityContextHolder.getContext().getAuthentication() == null) {
            log.debug("Authentication has been removed " + "(inidicates previous errors in filter chain)");
        } else {
            successfulAuthenticationEnd(request, response, authentication);
            ok = true;
        }
    } finally {
        if (!ok) {
            log.debug("Clearing security context due to previous errors");

            SecurityContextHolder.clearContext();
            if ((policy != null) && policy.isInvalidateOnUnexpectedException()) {
                invalidateSession(request);
            }
        }
    }
}

From source file:com.tasktop.c2c.server.ssh.server.commands.AbstractInteractiveProxyCommand.java

@Override
public void start(final Environment env) throws IOException {
    final AuthenticationToken authenticationToken = session
            .getAttribute(Constants.SESSION_KEY_AUTHENTICATION_TOKEN);
    if (authenticationToken == null) {
        // should never happen
        throw new IllegalStateException();
    }/*from  ww w. j  ava  2  s . com*/

    try {
        String uri = computeCommandPath();

        // path info format is:
        // /<project-identity>/<repository>.git

        Matcher matcher = PATH_PATTERN.matcher(uri);
        if (matcher.matches()) {
            final String projectId = matcher.group(1);
            final String path = matcher.group(2);
            if (path == null || path.indexOf('/') != -1) {
                // short-circuit everything: currently we don't support repositories with nested paths
                pathNotFound(uri);
            }

            final String requestPath = computeRequestPath(path);

            final ProjectService service;
            try {
                service = projectServiceService.findServiceByUri(projectId, requestPath);
            } catch (EntityNotFoundException e) {
                getLogger().info("Project identity not found: " + projectId);
                pathNotFound(uri);
                throw new IllegalStateException();
            }
            if (service == null) {
                getLogger().info(
                        "No ProjectService associated with project " + projectId + " path " + requestPath);
                pathNotFound(uri);
            }
            if (!service.getServiceHost().isAvailable() || service.getServiceHost().getInternalHost() == null) {
                getLogger().info("Service temporarily unavailable for " + projectId + " path " + requestPath);
                throw new CommandException(1, "Repository temporarily unavailable.  Please try again later.");
            }

            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    // setup the security context
                    AuthenticationToken projectSpecializedToken = internalAuthenticationService
                            .specializeAuthenticationToken(authenticationToken,
                                    service.getProjectServiceProfile().getProject());
                    AuthenticationServiceUser user = AuthenticationServiceUser
                            .fromAuthenticationToken(projectSpecializedToken);
                    SecurityContextHolder.getContext()
                            .setAuthentication(new PreAuthenticatedAuthenticationToken(user,
                                    projectSpecializedToken, user.getAuthorities()));
                    try {
                        establishTenancyContext(projectId);
                        try {
                            if (!hasRequiredRoles()) {
                                getLogger().info("Access denied to " + user.getUsername() + " for " + getName()
                                        + " project:" + projectId + " path:" + requestPath);
                                throw new CommandException(1, "Permission denied");
                            }

                            // propagate the tenant and authentication via request headers
                            RequestHeadersSupport headers = new RequestHeadersSupport();
                            tokenSerializer.serialize(headers, projectSpecializedToken);
                            for (Entry<String, String> header : tenancySerializer.computeHeaders().entrySet()) {
                                headers.addHeader(header.getKey(), header.getValue());
                            }

                            performCommand(env, service, projectId, path, requestPath, headers);
                            callback.onExit(0);
                        } catch (CommandException e) {
                            callback.onExit(e.getReturnCode(), e.getMessage());
                        } catch (Throwable t) {
                            callback.onExit(-1, t.getClass().getSimpleName() + ": " + t.getMessage());
                            getLogger().error(t.getMessage(), t);
                        } finally {
                            TenancyUtil.clearContext();
                        }
                    } finally {
                        SecurityContextHolder.clearContext();
                    }
                }
            });
        } else {
            getLogger().info("Repository path does not match expected pattern: " + uri);
            pathNotFound(uri);
        }
    } catch (CommandException e) {
        getLogger().info("CommandException: " + e.getMessage(), e);
        callback.onExit(e.getReturnCode(), e.getMessage());
    }
}

From source file:org.jasig.springframework.security.portlet.authentication.PortletAuthenticationProcessingFilter.java

/**
* Ensures the authentication object in the secure context is set to null when authentication fails.
* <p>//from   w ww .  jav  a2  s  . c o m
* Caches the failure exception as a request attribute
*/
protected void unsuccessfulAuthentication(PortletRequest request, PortletResponse response,
        AuthenticationException failed) {
    SecurityContextHolder.clearContext();

    if (logger.isDebugEnabled()) {
        logger.debug("Cleared security context due to exception", failed);
    }
    request.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, failed);
}

From source file:sample.contact.DataSourcePopulator.java

public void afterPropertiesSet() throws Exception {
    Assert.notNull(mutableAclService, "mutableAclService required");
    Assert.notNull(template, "dataSource required");
    Assert.notNull(tt, "platformTransactionManager required");

    // Set a user account that will initially own all the created data
    Authentication authRequest = new UsernamePasswordAuthenticationToken("rod", "koala",
            AuthorityUtils.createAuthorityList("ROLE_IGNORED"));
    SecurityContextHolder.getContext().setAuthentication(authRequest);

    try {/* w  w  w .  j a va 2s  .c  om*/
        template.execute("DELETE FROM CONTACTS");
        template.execute("DELETE FROM AUTHORITIES");
        template.execute("DELETE FROM USERS");
        template.execute("DELETE FROM ACL_ENTRY");
        template.execute("DELETE FROM ACL_OBJECT_IDENTITY");
        template.execute("DELETE FROM ACL_CLASS");
        template.execute("DELETE FROM ACL_SID");
    } catch (Exception e) {
        System.out.println("Failed to DELETE FROMs: " + e.getMessage());
    }
    /*
     * Passwords encoded using MD5, NOT in Base64 format, with null as salt Encoded
     * password for rod is "koala" Encoded password for dianne is "emu" Encoded
     * password for scott is "wombat" Encoded password for peter is "opal" (but user
     * is disabled) Encoded password for bill is "wombat" Encoded password for bob is
     * "wombat" Encoded password for jane is "wombat"
     */
    template.execute(
            "INSERT INTO USERS VALUES('rod','$2a$10$75pBjapg4Nl8Pzd.3JRnUe7PDJmk9qBGwNEJDAlA3V.dEJxcDKn5O',TRUE);");
    template.execute(
            "INSERT INTO USERS VALUES('dianne','$2a$04$bCMEyxrdF/7sgfUiUJ6Ose2vh9DAMaVBldS1Bw2fhi1jgutZrr9zm',TRUE);");
    template.execute(
            "INSERT INTO USERS VALUES('scott','$2a$06$eChwvzAu3TSexnC3ynw4LOSw1qiEbtNItNeYv5uI40w1i3paoSfLu',TRUE);");
    template.execute(
            "INSERT INTO USERS VALUES('peter','$2a$04$8.H8bCMROLF4CIgd7IpeQ.tcBXLP5w8iplO0n.kCIkISwrIgX28Ii',FALSE);");
    template.execute(
            "INSERT INTO USERS VALUES('bill','$2a$04$8.H8bCMROLF4CIgd7IpeQ.3khQlPVNWbp8kzSQqidQHGFurim7P8O',TRUE);");
    template.execute(
            "INSERT INTO USERS VALUES('bob','$2a$06$zMgxlMf01SfYNcdx7n4NpeFlAGU8apCETz/i2C7VlYWu6IcNyn4Ay',TRUE);");
    template.execute(
            "INSERT INTO USERS VALUES('jane','$2a$05$ZrdS7yMhCZ1J.AAidXZhCOxdjD8LO/dhlv4FJzkXA6xh9gdEbBT/u',TRUE);");
    template.execute("INSERT INTO AUTHORITIES VALUES('rod','ROLE_USER');");
    template.execute("INSERT INTO AUTHORITIES VALUES('rod','ROLE_ADMIN');");
    template.execute("INSERT INTO AUTHORITIES VALUES('dianne','ROLE_USER');");
    template.execute("INSERT INTO AUTHORITIES VALUES('scott','ROLE_USER');");
    template.execute("INSERT INTO AUTHORITIES VALUES('peter','ROLE_USER');");
    template.execute("INSERT INTO AUTHORITIES VALUES('bill','ROLE_USER');");
    template.execute("INSERT INTO AUTHORITIES VALUES('bob','ROLE_USER');");
    template.execute("INSERT INTO AUTHORITIES VALUES('jane','ROLE_USER');");
    template.execute("INSERT INTO AUTHORITIES VALUES('jane','ROLE_ADMIN');");

    template.execute("INSERT INTO contacts VALUES (1, 'John Smith', 'john@somewhere.com');");
    template.execute("INSERT INTO contacts VALUES (2, 'Michael Citizen', 'michael@xyz.com');");
    template.execute("INSERT INTO contacts VALUES (3, 'Joe Bloggs', 'joe@demo.com');");
    template.execute("INSERT INTO contacts VALUES (4, 'Karen Sutherland', 'karen@sutherland.com');");
    template.execute("INSERT INTO contacts VALUES (5, 'Mitchell Howard', 'mitchell@abcdef.com');");
    template.execute("INSERT INTO contacts VALUES (6, 'Rose Costas', 'rose@xyz.com');");
    template.execute("INSERT INTO contacts VALUES (7, 'Amanda Smith', 'amanda@abcdef.com');");
    template.execute("INSERT INTO contacts VALUES (8, 'Cindy Smith', 'cindy@smith.com');");
    template.execute("INSERT INTO contacts VALUES (9, 'Jonathan Citizen', 'jonathan@xyz.com');");

    for (int i = 10; i < createEntities; i++) {
        String[] person = selectPerson();
        template.execute("INSERT INTO contacts VALUES (" + i + ", '" + person[2] + "', '"
                + person[0].toLowerCase() + "@" + person[1].toLowerCase() + ".com');");
    }

    // Create acl_object_identity rows (and also acl_class rows as needed
    for (int i = 1; i < createEntities; i++) {
        final ObjectIdentity objectIdentity = new ObjectIdentityImpl(Contact.class, new Long(i));
        tt.execute(new TransactionCallback<Object>() {
            public Object doInTransaction(TransactionStatus arg0) {
                mutableAclService.createAcl(objectIdentity);

                return null;
            }
        });
    }

    // Now grant some permissions
    grantPermissions(1, "rod", BasePermission.ADMINISTRATION);
    grantPermissions(2, "rod", BasePermission.READ);
    grantPermissions(3, "rod", BasePermission.READ);
    grantPermissions(3, "rod", BasePermission.WRITE);
    grantPermissions(3, "rod", BasePermission.DELETE);
    grantPermissions(4, "rod", BasePermission.ADMINISTRATION);
    grantPermissions(4, "dianne", BasePermission.ADMINISTRATION);
    grantPermissions(4, "scott", BasePermission.READ);
    grantPermissions(5, "dianne", BasePermission.ADMINISTRATION);
    grantPermissions(5, "dianne", BasePermission.READ);
    grantPermissions(6, "dianne", BasePermission.READ);
    grantPermissions(6, "dianne", BasePermission.WRITE);
    grantPermissions(6, "dianne", BasePermission.DELETE);
    grantPermissions(6, "scott", BasePermission.READ);
    grantPermissions(7, "scott", BasePermission.ADMINISTRATION);
    grantPermissions(8, "dianne", BasePermission.ADMINISTRATION);
    grantPermissions(8, "dianne", BasePermission.READ);
    grantPermissions(8, "scott", BasePermission.READ);
    grantPermissions(9, "scott", BasePermission.ADMINISTRATION);
    grantPermissions(9, "scott", BasePermission.READ);
    grantPermissions(9, "scott", BasePermission.WRITE);
    grantPermissions(9, "scott", BasePermission.DELETE);

    // Now expressly change the owner of the first ten contacts
    // We have to do this last, because "rod" owns all of them (doing it sooner would
    // prevent ACL updates)
    // Note that ownership has no impact on permissions - they're separate (ownership
    // only allows ACl editing)
    changeOwner(5, "dianne");
    changeOwner(6, "dianne");
    changeOwner(7, "scott");
    changeOwner(8, "dianne");
    changeOwner(9, "scott");

    String[] users = { "bill", "bob", "jane" }; // don't want to mess around with
    // consistent sample data
    Permission[] permissions = { BasePermission.ADMINISTRATION, BasePermission.READ, BasePermission.DELETE };

    for (int i = 10; i < createEntities; i++) {
        String user = users[rnd.nextInt(users.length)];
        Permission permission = permissions[rnd.nextInt(permissions.length)];
        grantPermissions(i, user, permission);

        String user2 = users[rnd.nextInt(users.length)];
        Permission permission2 = permissions[rnd.nextInt(permissions.length)];
        grantPermissions(i, user2, permission2);
    }

    SecurityContextHolder.clearContext();
}

From source file:de.itsvs.cwtrpc.security.AbstractRpcAuthenticationProcessingFilter.java

protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException exception) throws IOException, ServletException {
    log.debug("Unsuccessful authentication", exception);

    SecurityContextHolder.clearContext();

    getRememberMeServices().loginFail(request, response);
    getAuthenticationFailureHandler().onAuthenticationFailure(request, response, exception);
}

From source file:net.d53.syman.web.controller.PatientController.java

@RequestMapping(value = "/api/auth", method = RequestMethod.POST)
@ResponseBody/*from   w w  w .j  ava  2 s.c o  m*/
public String APIauthenticate(@RequestParam String username, @RequestParam String password,
        HttpServletRequest request, HttpServletResponse response) {
    String token = null;
    UsernamePasswordAuthenticationToken authenticationRequest = new UsernamePasswordAuthenticationToken(
            username, password);

    authenticationRequest.setDetails(APIAuthenticationToken.API_TOKEN_IDENTIFIER);

    try {
        APIAuthenticationToken res = (APIAuthenticationToken) authenticationManager
                .authenticate(authenticationRequest);
        LOGGER.info(ToStringBuilder.reflectionToString(res));
        if (res != null) {
            token = res.getCredentials().toString();
            LOGGER.info("Generated token " + token);
            SecurityContext context = SecurityContextHolder.getContext();
            context.setAuthentication(res);
            this.securityContextRepository.saveContext(context, request, response);
        } else {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        }
    } catch (AuthenticationException e) {
        LOGGER.info("Authentication error: " + e.getMessage());
        SecurityContextHolder.clearContext();
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
    return token;
}

From source file:net.shibboleth.idp.oidc.flow.BuildAuthorizationRequestContextAction.java

/**
 * Check for prompts in the authorization request. Evaluates
 * if redirects to the client should execute
 * or authentication cleared forcing the user
 * to authenticate again.//w  ww .  j  av a2 s  .c o m
 *
 * @param prompt      the prompt
 * @param request     the request
 * @param client      the client
 * @param authRequest the auth request
 * @return the event
 * @throws java.io.IOException the IO exception
 */
private Pair<Events, ? extends Object> checkForPrompts(final String prompt, final HttpServletRequest request,
        final ClientDetailsEntity client, final OIDCAuthorizationRequestContext authRequest) {

    final List<String> prompts = Splitter.on(ConnectRequestParameters.PROMPT_SEPARATOR)
            .splitToList(Strings.nullToEmpty(prompt));
    if (prompts.contains(ConnectRequestParameters.PROMPT_NONE)) {
        return checkForNonePrompt(client, authRequest);
    }

    if (prompts.contains(ConnectRequestParameters.PROMPT_LOGIN)) {
        log.debug("Prompt contains {} which will require forced authN", ConnectRequestParameters.PROMPT_LOGIN);
        SecurityContextHolder.clearContext();
        authRequest.setForceAuthentication(true);
    } else {
        log.debug("Prompt {} is not supported", prompt);
    }
    return new Pair<>(Events.Success, null);
}

From source file:de.itsvs.cwtrpc.security.RpcSessionManagementFilter.java

protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException exception) throws IOException, ServletException {
    SecurityContextHolder.clearContext();
    getAuthenticationFailureHandler().onAuthenticationFailure(request, response, exception);
}

From source file:org.tibetjungle.demo.service.DataSourcePopulator.java

public void afterPropertiesSet() throws Exception {
    Assert.notNull(mutableAclService, "mutableAclService required");
    Assert.notNull(template, "dataSource required");
    Assert.notNull(tt, "platformTransactionManager required");

    // Set a user account that will initially own all the created data
    Authentication authRequest = new UsernamePasswordAuthenticationToken("rod", "koala",
            AuthorityUtils.createAuthorityList("ROLE_IGNORED"));
    SecurityContextHolder.getContext().setAuthentication(authRequest);

    try {//from ww  w  .j a v  a  2  s  .  c om
        template.execute("DROP TABLE CONTACTS");
        template.execute("DROP TABLE AUTHORITIES");
        template.execute("DROP TABLE USERS");
        template.execute("DROP TABLE ACL_ENTRY");
        template.execute("DROP TABLE ACL_OBJECT_IDENTITY");
        template.execute("DROP TABLE ACL_CLASS");
        template.execute("DROP TABLE ACL_SID");
    } catch (Exception e) {
        System.out.println("Failed to drop tables: " + e.getMessage());
    }

    template.execute("CREATE TABLE ACL_SID("
            + "ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY,"
            + "PRINCIPAL BOOLEAN NOT NULL," + "SID VARCHAR_IGNORECASE(100) NOT NULL,"
            + "CONSTRAINT UNIQUE_UK_1 UNIQUE(SID,PRINCIPAL));");
    template.execute("CREATE TABLE ACL_CLASS("
            + "ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY,"
            + "CLASS VARCHAR_IGNORECASE(100) NOT NULL," + "CONSTRAINT UNIQUE_UK_2 UNIQUE(CLASS));");
    template.execute("CREATE TABLE ACL_OBJECT_IDENTITY("
            + "ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY,"
            + "OBJECT_ID_CLASS BIGINT NOT NULL," + "OBJECT_ID_IDENTITY BIGINT NOT NULL,"
            + "PARENT_OBJECT BIGINT," + "OWNER_SID BIGINT," + "ENTRIES_INHERITING BOOLEAN NOT NULL,"
            + "CONSTRAINT UNIQUE_UK_3 UNIQUE(OBJECT_ID_CLASS,OBJECT_ID_IDENTITY),"
            + "CONSTRAINT FOREIGN_FK_1 FOREIGN KEY(PARENT_OBJECT)REFERENCES ACL_OBJECT_IDENTITY(ID),"
            + "CONSTRAINT FOREIGN_FK_2 FOREIGN KEY(OBJECT_ID_CLASS)REFERENCES ACL_CLASS(ID),"
            + "CONSTRAINT FOREIGN_FK_3 FOREIGN KEY(OWNER_SID)REFERENCES ACL_SID(ID));");
    template.execute("CREATE TABLE ACL_ENTRY("
            + "ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY,"
            + "ACL_OBJECT_IDENTITY BIGINT NOT NULL,ACE_ORDER INT NOT NULL,SID BIGINT NOT NULL,"
            + "MASK INTEGER NOT NULL,GRANTING BOOLEAN NOT NULL,AUDIT_SUCCESS BOOLEAN NOT NULL,"
            + "AUDIT_FAILURE BOOLEAN NOT NULL,CONSTRAINT UNIQUE_UK_4 UNIQUE(ACL_OBJECT_IDENTITY,ACE_ORDER),"
            + "CONSTRAINT FOREIGN_FK_4 FOREIGN KEY(ACL_OBJECT_IDENTITY) REFERENCES ACL_OBJECT_IDENTITY(ID),"
            + "CONSTRAINT FOREIGN_FK_5 FOREIGN KEY(SID) REFERENCES ACL_SID(ID));");

    template.execute(
            "CREATE TABLE USERS(USERNAME VARCHAR_IGNORECASE(50) NOT NULL PRIMARY KEY,PASSWORD VARCHAR_IGNORECASE(60) NOT NULL,ENABLED BOOLEAN NOT NULL);");
    template.execute(
            "CREATE TABLE AUTHORITIES(USERNAME VARCHAR_IGNORECASE(50) NOT NULL,AUTHORITY VARCHAR_IGNORECASE(50) NOT NULL,CONSTRAINT FK_AUTHORITIES_USERS FOREIGN KEY(USERNAME) REFERENCES USERS(USERNAME));");
    template.execute("CREATE UNIQUE INDEX IX_AUTH_USERNAME ON AUTHORITIES(USERNAME,AUTHORITY);");

    template.execute(
            "CREATE TABLE CONTACTS(ID BIGINT NOT NULL PRIMARY KEY, CONTACT_NAME VARCHAR_IGNORECASE(50) NOT NULL, EMAIL VARCHAR_IGNORECASE(50) NOT NULL)");

    /*
       Passwords encoded using MD5, NOT in Base64 format, with null as salt
       Encoded password for rod is "koala"
       Encoded password for dianne is "emu"
       Encoded password for scott is "wombat"
       Encoded password for peter is "opal" (but user is disabled)
       Encoded password for bill is "wombat"
       Encoded password for bob is "wombat"
       Encoded password for jane is "wombat"
            
     */
    template.execute(
            "INSERT INTO USERS VALUES('rod','$2a$10$75pBjapg4Nl8Pzd.3JRnUe7PDJmk9qBGwNEJDAlA3V.dEJxcDKn5O',TRUE);");
    template.execute(
            "INSERT INTO USERS VALUES('dianne','$2a$04$bCMEyxrdF/7sgfUiUJ6Ose2vh9DAMaVBldS1Bw2fhi1jgutZrr9zm',TRUE);");
    template.execute(
            "INSERT INTO USERS VALUES('scott','$2a$06$eChwvzAu3TSexnC3ynw4LOSw1qiEbtNItNeYv5uI40w1i3paoSfLu',TRUE);");
    template.execute(
            "INSERT INTO USERS VALUES('peter','$2a$04$8.H8bCMROLF4CIgd7IpeQ.tcBXLP5w8iplO0n.kCIkISwrIgX28Ii',FALSE);");
    template.execute(
            "INSERT INTO USERS VALUES('bill','$2a$04$8.H8bCMROLF4CIgd7IpeQ.3khQlPVNWbp8kzSQqidQHGFurim7P8O',TRUE);");
    template.execute(
            "INSERT INTO USERS VALUES('bob','$2a$06$zMgxlMf01SfYNcdx7n4NpeFlAGU8apCETz/i2C7VlYWu6IcNyn4Ay',TRUE);");
    template.execute(
            "INSERT INTO USERS VALUES('jane','$2a$05$ZrdS7yMhCZ1J.AAidXZhCOxdjD8LO/dhlv4FJzkXA6xh9gdEbBT/u',TRUE);");
    template.execute("INSERT INTO AUTHORITIES VALUES('rod','ROLE_USER');");
    template.execute("INSERT INTO AUTHORITIES VALUES('rod','ROLE_SUPERVISOR');");
    template.execute("INSERT INTO AUTHORITIES VALUES('dianne','ROLE_USER');");
    template.execute("INSERT INTO AUTHORITIES VALUES('scott','ROLE_USER');");
    template.execute("INSERT INTO AUTHORITIES VALUES('peter','ROLE_USER');");
    template.execute("INSERT INTO AUTHORITIES VALUES('bill','ROLE_USER');");
    template.execute("INSERT INTO AUTHORITIES VALUES('bob','ROLE_USER');");
    template.execute("INSERT INTO AUTHORITIES VALUES('jane','ROLE_USER');");

    template.execute("INSERT INTO contacts VALUES (1, 'John Smith', 'john@somewhere.com');");
    template.execute("INSERT INTO contacts VALUES (2, 'Michael Citizen', 'michael@xyz.com');");
    template.execute("INSERT INTO contacts VALUES (3, 'Joe Bloggs', 'joe@demo.com');");
    template.execute("INSERT INTO contacts VALUES (4, 'Karen Sutherland', 'karen@sutherland.com');");
    template.execute("INSERT INTO contacts VALUES (5, 'Mitchell Howard', 'mitchell@abcdef.com');");
    template.execute("INSERT INTO contacts VALUES (6, 'Rose Costas', 'rose@xyz.com');");
    template.execute("INSERT INTO contacts VALUES (7, 'Amanda Smith', 'amanda@abcdef.com');");
    template.execute("INSERT INTO contacts VALUES (8, 'Cindy Smith', 'cindy@smith.com');");
    template.execute("INSERT INTO contacts VALUES (9, 'Jonathan Citizen', 'jonathan@xyz.com');");

    for (int i = 10; i < createEntities; i++) {
        String[] person = selectPerson();
        template.execute("INSERT INTO contacts VALUES (" + i + ", '" + person[2] + "', '"
                + person[0].toLowerCase() + "@" + person[1].toLowerCase() + ".com');");
    }

    // Create acl_object_identity rows (and also acl_class rows as needed
    for (int i = 1; i < createEntities; i++) {
        final ObjectIdentity objectIdentity = new ObjectIdentityImpl(Contact.class, new Long(i));
        tt.execute(new TransactionCallback<Object>() {
            public Object doInTransaction(TransactionStatus arg0) {
                mutableAclService.createAcl(objectIdentity);

                return null;
            }
        });
    }

    // Now grant some permissions
    grantPermissions(1, "rod", BasePermission.ADMINISTRATION);
    grantPermissions(2, "rod", BasePermission.READ);
    grantPermissions(3, "rod", BasePermission.READ);
    grantPermissions(3, "rod", BasePermission.WRITE);
    grantPermissions(3, "rod", BasePermission.DELETE);
    grantPermissions(4, "rod", BasePermission.ADMINISTRATION);
    grantPermissions(4, "dianne", BasePermission.ADMINISTRATION);
    grantPermissions(4, "scott", BasePermission.READ);
    grantPermissions(5, "dianne", BasePermission.ADMINISTRATION);
    grantPermissions(5, "dianne", BasePermission.READ);
    grantPermissions(6, "dianne", BasePermission.READ);
    grantPermissions(6, "dianne", BasePermission.WRITE);
    grantPermissions(6, "dianne", BasePermission.DELETE);
    grantPermissions(6, "scott", BasePermission.READ);
    grantPermissions(7, "scott", BasePermission.ADMINISTRATION);
    grantPermissions(8, "dianne", BasePermission.ADMINISTRATION);
    grantPermissions(8, "dianne", BasePermission.READ);
    grantPermissions(8, "scott", BasePermission.READ);
    grantPermissions(9, "scott", BasePermission.ADMINISTRATION);
    grantPermissions(9, "scott", BasePermission.READ);
    grantPermissions(9, "scott", BasePermission.WRITE);
    grantPermissions(9, "scott", BasePermission.DELETE);

    // Now expressly change the owner of the first ten contacts
    // We have to do this last, because "rod" owns all of them (doing it sooner would prevent ACL updates)
    // Note that ownership has no impact on permissions - they're separate (ownership only allows ACl editing)
    changeOwner(5, "dianne");
    changeOwner(6, "dianne");
    changeOwner(7, "scott");
    changeOwner(8, "dianne");
    changeOwner(9, "scott");

    String[] users = { "bill", "bob", "jane" }; // don't want to mess around with consistent sample data
    Permission[] permissions = { BasePermission.ADMINISTRATION, BasePermission.READ, BasePermission.DELETE };

    for (int i = 10; i < createEntities; i++) {
        String user = users[rnd.nextInt(users.length)];
        Permission permission = permissions[rnd.nextInt(permissions.length)];
        grantPermissions(i, user, permission);

        String user2 = users[rnd.nextInt(users.length)];
        Permission permission2 = permissions[rnd.nextInt(permissions.length)];
        grantPermissions(i, user2, permission2);
    }

    SecurityContextHolder.clearContext();
}