Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @Configuration
- @EnableWebSecurity(debug = true)
- /*
- Spring web security configuration
- */
- public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
- private static final String MYSQL_DATA_SOURCE = "java:jboss/MysqlDataSource";
- private Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class);
- private RestAuthenticationEntryPoint restAuthenticationEntryPoint = new RestAuthenticationEntryPoint();
- @Autowired
- private MySavedRequestAwareAuthenticationSuccessHandler authenticationSuccessHandler;
- @Bean
- public DataSource dataSource() {
- JndiDataSourceLookup jndiDataSourceLookup = new JndiDataSourceLookup();
- return jndiDataSourceLookup.getDataSource(MYSQL_DATA_SOURCE);
- }
- @Autowired
- public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
- auth.jdbcAuthentication().dataSource(dataSource())
- .usersByUsernameQuery(
- "select USERNAME,PASSWORD, ACTIVE from ConcertLiveCheck.USER where USERNAME=?")
- .authoritiesByUsernameQuery(
- "SELECT userTable.USERNAME, roleTable.NAME as 'ROLE'\n"
- + "FROM ConcertLiveCheck.USER userTable, ConcertLiveCheck.ROLE roleTable, ConcertLiveCheck.USER_ROLE userRoleTable\n"
- + "WHERE userTable.ID = userRoleTable.USER_ID AND roleTable.ID = userRoleTable.ROLE_ID AND userRoleTable.USER_ID = \n"
- + "(SELECT ID from ConcertLiveCheck.USER WHERE USERNAME = ?);");
- }
- @Bean
- public MySavedRequestAwareAuthenticationSuccessHandler mySuccessHandler() {
- return new MySavedRequestAwareAuthenticationSuccessHandler();
- }
- @Bean
- public SimpleUrlAuthenticationFailureHandler myFailureHandler() {
- return new SimpleUrlAuthenticationFailureHandler();
- }
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http //Authorization
- .csrf().disable()
- .exceptionHandling()
- .authenticationEntryPoint(restAuthenticationEntryPoint)
- .and()
- //Url matching
- .authorizeRequests() //Authorize Request Configuration
- .antMatchers("/login/**", "/register/**").permitAll()
- .antMatchers("/admin/**").hasRole("ADMIN")
- .antMatchers("/", "/*").hasAnyRole("USER", "ADMIN")
- .anyRequest().authenticated()
- .and()
- //Persistant cookie
- .rememberMe()
- .rememberMeCookieName("example-app-remember-me")
- .tokenRepository(persistentTokenRepository())
- .tokenValiditySeconds(24 * 60 * 60)
- .and()
- //Form matching
- .formLogin()
- .usernameParameter("username").passwordParameter("password")
- .loginPage("/login").permitAll()
- .successHandler(authenticationSuccessHandler)
- .failureHandler(new SimpleUrlAuthenticationFailureHandler())
- .and() //Logout Form configuration
- .logout()
- .permitAll();
- }
- @Bean
- public PersistentTokenRepository persistentTokenRepository() {
- final CLCJdbcTokenRepositoryImpl jdbcTokenRepository = new CLCJdbcTokenRepositoryImpl();
- jdbcTokenRepository.setDataSource(dataSource());
- return jdbcTokenRepository;
- }
- }
- public class CLCJdbcTokenRepositoryImpl extends JdbcDaoSupport implements PersistentTokenRepository {
- public static final String
- CREATE_TABLE_SQL
- = "create table ConcertLiveCheck.PERSISTENT_SESSION (ID varchar (40) primary key, USERNAME varchar(64) not null, SERIES varchar(64), TOKEN varchar(64) not null, LAST_LOGIN_DATE"
- + "timestamp not null)";
- public static final String DEF_TOKEN_BY_SERIES_SQL = "select USERNAME,SERIES,TOKEN,LAST_LOGIN_DATE from ConcertLiveCheck.PERSISTENT_SESSION where series = ?";
- public static final String DEF_INSERT_TOKEN_SQL = "insert into ConcertLiveCheck.PERSISTENT_SESSION(USERNAME, SERIES, TOKEN, LAST_LOGIN_DATE) values(?,?,?,?)";
- public static final String DEF_UPDATE_TOKEN_SQL = "update ConcertLiveCheck.PERSISTENT_SESSION set TOKEN = ?, LAST_LOGIN_DATE = ? where SERIES = ?";
- public static final String DEF_REMOVE_USER_TOKENS_SQL = "delete from ConcertLiveCheck.PERSISTENT_SESSION where USERNAME = ?";
- private String tokensBySeriesSql = "select username,series,token,LAST_LOGIN_DATE from ConcertLiveCheck.PERSISTENT_SESSION where series = ?";
- private String insertTokenSql = "insert into ConcertLiveCheck.PERSISTENT_SESSION (username, series, token, LAST_LOGIN_DATE) values(?,?,?,?)";
- private String updateTokenSql = "update ConcertLiveCheck.PERSISTENT_SESSION set token = ?, LAST_LOGIN_DATE = ? where series = ?";
- private String removeUserTokensSql = "delete from ConcertLiveCheck.PERSISTENT_SESSION where username = ?";
- private boolean createTableOnStartup;
- public CLCJdbcTokenRepositoryImpl() {
- }
- @Override
- protected void initDao() {
- if (this.createTableOnStartup) {
- this.getJdbcTemplate().execute("create table ConcertLiveCheck.PERSISTENT_SESSION (username varchar(64) not null, series varchar(64) primary key, token varchar(64) not null, LAST_LOGIN_DATE timestamp not null)");
- }
- }
- public void createNewToken(PersistentRememberMeToken token) {
- this.getJdbcTemplate().update(this.insertTokenSql, new Object[] {token.getUsername(), token.getSeries(), token.getTokenValue(), token.getDate()});
- }
- public void updateToken(String series, String tokenValue, Date lastUsed) {
- this.getJdbcTemplate().update(this.updateTokenSql, new Object[] {tokenValue, lastUsed, series});
- }
- public PersistentRememberMeToken getTokenForSeries(String seriesId) {
- try {
- return this.getJdbcTemplate().queryForObject(this.tokensBySeriesSql, (rs, rowNum) -> new PersistentRememberMeToken(rs.getString(1), rs.getString(2), rs.getString(3), rs.getTimestamp(4)),
- new Object[] {seriesId});
- } catch (EmptyResultDataAccessException var3) {
- if (this.logger.isDebugEnabled()) {
- this.logger.debug("Querying token for series '" + seriesId + "' returned no results.", var3);
- }
- } catch (IncorrectResultSizeDataAccessException var4) {
- this.logger.error("Querying token for series '" + seriesId + "' returned more than one value. Series" + " should be unique");
- } catch (DataAccessException var5) {
- this.logger.error("Failed to load token for series " + seriesId, var5);
- }
- return null;
- }
- public void removeUserTokens(String username) {
- this.getJdbcTemplate().update(this.removeUserTokensSql, new Object[] {username});
- }
- public void setCreateTableOnStartup(boolean createTableOnStartup) {
- this.createTableOnStartup = createTableOnStartup;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement