Skip to content
Advertisement

How to integrate Spring Security with Spring Batch?

I want to create a secured web application where users can launch Spring Batch jobs. I want to keep track about who launched which job and thus I have to associate a JobInstance (or a JobExecution?) with a user. I additionally want to query for JobExecutions that were started by a particular user. This does not seem to be a common use case since I could not find a solution for this in the reference guide.

Do I have to write my own implementations for the persistence layer of Spring Batch? This seems to be much overhead for just adding a field to a table. Does anybody know a simple solution?

Advertisement

Answer

As @Artem Bilan suggested I inject the current user into the JobParameters. I have written a simple service class that provides a method that queries for the execution ids of a given user:

@Service
public class JobService {

    private static final String FIND_EXECUTIONS = "SELECT JOB_EXECUTION_ID FROM batch_job_execution_params WHERE KEY_NAME = 'user' AND STRING_VAL = ? ORDER BY JOB_EXECUTION_ID DESC";

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<Long> findJobExecutionIdsByUser(String username) {
        return jdbcTemplate.queryForList(FIND_EXECUTIONS, Long.class, username);
    }

}

With this list I am able to get the JobExecutions from the default JobExplorer like this:

final List<Long> executionIds = jobService.findJobExecutionIdsByUser("user");
final List<JobExecution> executions = new ArrayList<>();

for (Long executionId : executionIds) {
    final JobExecution execution = explorer.getJobExecution(executionId);

    if (execution != null) {
        executions.add(execution);
    }
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement