Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2018
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.99 KB | None | 0 0
  1. @Configuration
  2. @EnableWebSecurity(debug = true)
  3. /*
  4. Spring web security configuration
  5.  */
  6. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  7.  
  8.     private static final String MYSQL_DATA_SOURCE = "java:jboss/MysqlDataSource";
  9.     private Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class);
  10.     private RestAuthenticationEntryPoint restAuthenticationEntryPoint = new RestAuthenticationEntryPoint();
  11.     @Autowired
  12.     private MySavedRequestAwareAuthenticationSuccessHandler authenticationSuccessHandler;
  13.  
  14.     @Bean
  15.     public DataSource dataSource() {
  16.         JndiDataSourceLookup jndiDataSourceLookup = new JndiDataSourceLookup();
  17.         return jndiDataSourceLookup.getDataSource(MYSQL_DATA_SOURCE);
  18.     }
  19.  
  20.     @Autowired
  21.     public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
  22.  
  23.         auth.jdbcAuthentication().dataSource(dataSource())
  24.             .usersByUsernameQuery(
  25.                 "select USERNAME,PASSWORD, ACTIVE from ConcertLiveCheck.USER where USERNAME=?")
  26.             .authoritiesByUsernameQuery(
  27.                 "SELECT userTable.USERNAME, roleTable.NAME as 'ROLE'\n"
  28.                     + "FROM ConcertLiveCheck.USER userTable, ConcertLiveCheck.ROLE roleTable, ConcertLiveCheck.USER_ROLE userRoleTable\n"
  29.                     + "WHERE userTable.ID = userRoleTable.USER_ID AND roleTable.ID = userRoleTable.ROLE_ID AND userRoleTable.USER_ID = \n"
  30.                     + "(SELECT ID from ConcertLiveCheck.USER WHERE USERNAME = ?);");
  31.     }
  32.  
  33.     @Bean
  34.     public MySavedRequestAwareAuthenticationSuccessHandler mySuccessHandler() {
  35.         return new MySavedRequestAwareAuthenticationSuccessHandler();
  36.     }
  37.  
  38.     @Bean
  39.     public SimpleUrlAuthenticationFailureHandler myFailureHandler() {
  40.         return new SimpleUrlAuthenticationFailureHandler();
  41.     }
  42.  
  43.     @Override
  44.     protected void configure(HttpSecurity http) throws Exception {
  45.  
  46.         http //Authorization
  47.              .csrf().disable()
  48.              .exceptionHandling()
  49.              .authenticationEntryPoint(restAuthenticationEntryPoint)
  50.              .and()
  51.              //Url matching
  52.              .authorizeRequests() //Authorize Request Configuration
  53.              .antMatchers("/login/**", "/register/**").permitAll()
  54.              .antMatchers("/admin/**").hasRole("ADMIN")
  55.              .antMatchers("/", "/*").hasAnyRole("USER", "ADMIN")
  56.              .anyRequest().authenticated()
  57.              .and()
  58.              //Persistant cookie
  59.              .rememberMe()
  60.              .rememberMeCookieName("example-app-remember-me")
  61.              .tokenRepository(persistentTokenRepository())
  62.              .tokenValiditySeconds(24 * 60 * 60)
  63.              .and()
  64.              //Form matching
  65.              .formLogin()
  66.              .usernameParameter("username").passwordParameter("password")
  67.              .loginPage("/login").permitAll()
  68.              .successHandler(authenticationSuccessHandler)
  69.              .failureHandler(new SimpleUrlAuthenticationFailureHandler())
  70.              .and() //Logout Form configuration
  71.              .logout()
  72.              .permitAll();
  73.     }
  74.  
  75.     @Bean
  76.     public PersistentTokenRepository persistentTokenRepository() {
  77.         final CLCJdbcTokenRepositoryImpl jdbcTokenRepository = new CLCJdbcTokenRepositoryImpl();
  78.         jdbcTokenRepository.setDataSource(dataSource());
  79.         return jdbcTokenRepository;
  80.     }
  81. }
  82.  
  83.  
  84.  
  85.  
  86.  
  87.  
  88.  
  89.  
  90.  
  91.  
  92.  
  93.  
  94.  
  95.  
  96. public class CLCJdbcTokenRepositoryImpl extends JdbcDaoSupport implements PersistentTokenRepository {
  97.     public static final String
  98.         CREATE_TABLE_SQL
  99.         = "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"
  100.         + "timestamp not null)";
  101.     public static final String DEF_TOKEN_BY_SERIES_SQL = "select USERNAME,SERIES,TOKEN,LAST_LOGIN_DATE from ConcertLiveCheck.PERSISTENT_SESSION where series = ?";
  102.     public static final String DEF_INSERT_TOKEN_SQL = "insert into ConcertLiveCheck.PERSISTENT_SESSION(USERNAME, SERIES, TOKEN, LAST_LOGIN_DATE) values(?,?,?,?)";
  103.     public static final String DEF_UPDATE_TOKEN_SQL = "update ConcertLiveCheck.PERSISTENT_SESSION set TOKEN = ?, LAST_LOGIN_DATE = ? where SERIES = ?";
  104.     public static final String DEF_REMOVE_USER_TOKENS_SQL = "delete from ConcertLiveCheck.PERSISTENT_SESSION where USERNAME = ?";
  105.     private String tokensBySeriesSql = "select username,series,token,LAST_LOGIN_DATE from ConcertLiveCheck.PERSISTENT_SESSION where series = ?";
  106.     private String insertTokenSql = "insert into ConcertLiveCheck.PERSISTENT_SESSION (username, series, token, LAST_LOGIN_DATE) values(?,?,?,?)";
  107.     private String updateTokenSql = "update ConcertLiveCheck.PERSISTENT_SESSION set token = ?, LAST_LOGIN_DATE = ? where series = ?";
  108.     private String removeUserTokensSql = "delete from ConcertLiveCheck.PERSISTENT_SESSION where username = ?";
  109.     private boolean createTableOnStartup;
  110.  
  111.     public CLCJdbcTokenRepositoryImpl() {
  112.     }
  113.  
  114.     @Override
  115.     protected void initDao() {
  116.         if (this.createTableOnStartup) {
  117.             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)");
  118.         }
  119.     }
  120.  
  121.     public void createNewToken(PersistentRememberMeToken token) {
  122.         this.getJdbcTemplate().update(this.insertTokenSql, new Object[] {token.getUsername(), token.getSeries(), token.getTokenValue(), token.getDate()});
  123.     }
  124.  
  125.     public void updateToken(String series, String tokenValue, Date lastUsed) {
  126.         this.getJdbcTemplate().update(this.updateTokenSql, new Object[] {tokenValue, lastUsed, series});
  127.     }
  128.  
  129.     public PersistentRememberMeToken getTokenForSeries(String seriesId) {
  130.         try {
  131.             return this.getJdbcTemplate().queryForObject(this.tokensBySeriesSql, (rs, rowNum) -> new PersistentRememberMeToken(rs.getString(1), rs.getString(2), rs.getString(3), rs.getTimestamp(4)),
  132.                                                          new Object[] {seriesId});
  133.         } catch (EmptyResultDataAccessException var3) {
  134.             if (this.logger.isDebugEnabled()) {
  135.                 this.logger.debug("Querying token for series '" + seriesId + "' returned no results.", var3);
  136.             }
  137.         } catch (IncorrectResultSizeDataAccessException var4) {
  138.             this.logger.error("Querying token for series '" + seriesId + "' returned more than one value. Series" + " should be unique");
  139.         } catch (DataAccessException var5) {
  140.             this.logger.error("Failed to load token for series " + seriesId, var5);
  141.         }
  142.  
  143.         return null;
  144.     }
  145.  
  146.     public void removeUserTokens(String username) {
  147.         this.getJdbcTemplate().update(this.removeUserTokensSql, new Object[] {username});
  148.     }
  149.  
  150.     public void setCreateTableOnStartup(boolean createTableOnStartup) {
  151.         this.createTableOnStartup = createTableOnStartup;
  152.     }
  153. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement