2016-08-01 5 views
1

私は自分のウェブサイトにSpring Securityを実装しようとしています。私はこれまでこれをやっており、それは魅力のように働く。以下のコードは動作していますが、データベースを認証する前に確認したいフィールドが他にもあります。私が欲しいのは、 "deletedByRecommender"と "deletedByAdministrator"というフィールドがユーザを認証する前にfalseであるかどうかをチェックすることです。ユーザーが完全に有効になっているかどうかを確認するだけでなく、ユーザーが有効になっていないとログインできないという理由でユーザーにメッセージを出力したい。私はフィルターを探していたが、それを動作させることができなかった。これをどうやって作るの?春のセキュリティ:データベースの余分なフィールドが偽であるかどうかをチェックし、ユーザに通知できない理由を知らせてください。

<html lang="en-US" xmlns="http://www.w3.org/1999/xhtml" 
 
     xmlns:h="http://java.sun.com/jsf/html" 
 
     xmlns:ui="http://java.sun.com/jsf/facelets" 
 
     xmlns:c="http://java.sun.com/jsp/jstl/core" 
 
     xmlns:f="http://java.sun.com/jsf/core"> 
 

 
<h:head> 
 
    
 
<title>Recommendation Book</title> 
 

 
<script type="text/javascript"> 
 

 
</script> 
 

 
</h:head> 
 
    
 
<h:body> 
 

 
<div class="Geral"> 
 

 
<h:form name="f" method="post"> 
 

 
\t <table> 
 
\t \t <tr><td>E-mail:</td><td><input type="email" name="username" value="" /></td></tr> 
 
\t \t <tr><td>Password:</td><td><input type="password" name="password" value="" /></td></tr> 
 
\t \t <tr><td>Remember Me:</td><td><input type="checkbox" name="remember-me" /></td></tr> 
 
\t \t <tr><td><input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/></td></tr> 
 
\t \t <tr><td></td><td><input name="submit" type="submit" value="Login" /></td></tr> 
 
\t \t <c:if test="${param.error != null}"> 
 
\t \t <tr><td colspan="2" style="color:red">Invalid email and password.</td></tr> 
 
\t \t </c:if> 
 
\t \t <c:if test="${param.logout != null}"> 
 
\t \t <tr><td colspan="2" style="color:red">You have been logged out.</td></tr> 
 
\t \t </c:if> 
 
\t </table> 
 

 
</h:form> 
 

 
</div> 
 

 
</h:body> 
 
    
 
</html>

package recBook; 
 

 
import org.springframework.security.web.context.*; 
 

 
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { 
 

 
\t public SecurityWebApplicationInitializer() { 
 
\t \t super(WebSecurityConfig.class); 
 
\t } 
 
}

package recBook; 
 

 
import javax.sql.DataSource; 
 

 
import org.springframework.beans.factory.annotation.Autowired; 
 
import org.springframework.context.annotation.Bean; 
 
import org.springframework.jdbc.datasource.DriverManagerDataSource; 
 
import org.springframework.security.config.annotation.authentication.builders.*; 
 
import org.springframework.security.config.annotation.web.builders.HttpSecurity; 
 
import org.springframework.security.config.annotation.web.configuration.*; 
 
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 
 
import org.springframework.security.web.util.matcher.AntPathRequestMatcher; 
 

 
@EnableWebSecurity 
 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 
 

 
\t @Autowired 
 
\t private DataSource dataSource; 
 

 
\t @Autowired 
 
\t public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 
 
\t \t auth 
 
\t \t \t .jdbcAuthentication() 
 
\t \t \t \t .dataSource(dataSource).passwordEncoder(passwordEncoder()); 
 
\t } 
 
\t 
 
\t @Bean 
 
\t public BCryptPasswordEncoder passwordEncoder() { 
 
\t \t return new BCryptPasswordEncoder(); 
 
\t } 
 
\t 
 
\t @Bean(name = "dataSource") 
 
\t public DriverManagerDataSource dataSource() { 
 
\t  DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource(); 
 
\t  driverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver"); 
 
\t  driverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/RecBookSpringDB"); 
 
\t  driverManagerDataSource.setUsername("root"); 
 
\t  driverManagerDataSource.setPassword("**************"); 
 
\t  return driverManagerDataSource; 
 
\t } 
 
\t 
 
\t @Override 
 
\t protected void configure(HttpSecurity http) throws Exception { 
 
\t \t http 
 
\t \t \t .authorizeRequests()                 
 
\t \t \t \t .antMatchers("/index.jsf", "/userPage.jsf").permitAll() 
 
\t \t \t \t .antMatchers("https://stackoverflow.com/users/**").permitAll() 
 
\t \t \t \t .antMatchers("/admin/**").hasAuthority("Administrator") 
 
\t \t \t \t .anyRequest().authenticated() 
 
\t \t \t \t .and() 
 
\t \t \t .formLogin().failureUrl("/login.jsf?error") 
 
\t \t \t \t .loginPage("/login.jsf") 
 
\t \t \t \t .permitAll() 
 
\t \t \t \t .and() 
 
\t \t \t .logout() 
 
\t \t \t \t .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) 
 
\t \t \t \t .permitAll() 
 
\t \t \t \t .logoutSuccessUrl("/login.jsf?logout=true") 
 
\t \t \t \t .and() 
 
\t \t \t .rememberMe().rememberMeParameter("remember-me") 
 
\t \t \t \t .and() 
 
\t \t \t .exceptionHandling().accessDeniedPage("/accessDenied.xhtml") 
 
\t \t \t \t .and() 
 
\t \t \t .csrf(); 
 
\t } 
 

 
}

CREATE TABLE users (
 
\t id SERIAL AUTO_INCREMENT, 
 
\t username VARCHAR(100) NOT NULL, 
 
\t password VARCHAR(150) NOT NULL, 
 
\t enabled TINYINT NOT NULL DEFAULT 1, 
 
\t deletedByRecommender BOOLEAN NOT NULL DEFAULT '0', 
 
\t deletedByAdministrator BOOLEAN NOT NULL DEFAULT '0', 
 
\t deleteReason CHAR(255) NULL DEFAULT 'Approved', 
 
\t lastUpdatedOn TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, 
 
\t createdOn TIMESTAMP DEFAULT CURRENT_TIMESTAMP, 
 
\t PRIMARY KEY (username) 
 
);

+0

([春のセキュリティが強化された追加のパラメータをチェック] http://stackoverflow.com/questions/27658030/check-extra-parameters-with-spring-の可能性のある重複セキュリティ)。これについては、多くのスレッドがあります。これはかなり包括的な答えを持っています。 –

答えて

0

私は古き良きセッションを使用し、UserDetailsS​​erviceインタフェースを実装することでやろうとしたものを達成しました。コード全体が下にあります。どんな質問でも私は質問をしました。間違ったことが分かったら、教えてください。

/* 
 
* 
 
* This is how I hash the password when inserting the user on database 
 
* 
 
*/ 
 

 
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); 
 
String hashedPassword = passwordEncoder.encode("test"); 
 
\t \t \t 
 
Users users = new Users(); 
 
Authorities authorities = new Authorities(); 
 
\t \t \t 
 
users.setUsername("Username"); 
 
users.setPassword(hashedPassword); 
 
\t \t \t 
 
authorities.setUsername("Username"); 
 
authorities.setAuthority("Authority"); 
 
\t \t \t 
 
new RegisterDAO().insert(users, authorities);

<!DOCTYPE html> 
 
<html xmlns="http://www.w3.org/1999/xhtml" 
 
     xmlns:h="http://java.sun.com/jsf/html" 
 
     xmlns:ui="http://java.sun.com/jsf/facelets" 
 
     xmlns:c="http://java.sun.com/jsp/jstl/core" 
 
     xmlns:f="http://java.sun.com/jsf/core"> 
 

 
<h:head> 
 
    
 
<title>Recommendation Book</title> 
 

 
<style> 
 

 
label.error { 
 
\t float: right; 
 
\t color: red; 
 
\t font-weight: bold; 
 
\t margin: 1em; 
 
\t padding: 0.75em; 
 
\t border-radius: 7px; 
 
\t -moz-border-radius: 7px; 
 
\t -khtml-border-radius: 7px; 
 
\t -webkit-border-radius: 7px; 
 
\t border: 2px solid red; 
 
\t background-color: white; 
 
} 
 

 
span.error { 
 
\t color: red; 
 
\t font-weight: bold; 
 
} 
 

 
span.message { 
 
\t color: green; 
 
\t font-weight: bold; 
 
} 
 

 
</style> 
 

 
</h:head> 
 
    
 
<h:body> 
 

 
<div class="Geral"> 
 

 
<h:form method="post" class="Login"> 
 

 
\t <table> 
 
\t \t <tr><td>E-mail:</td><td><input type="email" id="username" name="username" value="" /></td></tr> 
 
\t \t <tr><td>Password:</td><td><input type="password" name="password" value="test" /></td></tr> 
 
\t \t <tr><td>Remember Me:</td><td><input type="checkbox" name="remember-me" /></td></tr> 
 
\t \t <tr><td><input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/></td></tr> 
 
\t \t <tr><td></td><td><input name="submit" type="submit" value="Login" /></td></tr> 
 

 
\t \t <c:if test="${not empty SPRING_SECURITY_LAST_EXCEPTION}"> 
 
\t \t <c:choose> 
 
\t \t \t <c:when test="#{SPRING_SECURITY_LAST_EXCEPTION.message == 'Bad credentials'}"> 
 
\t \t \t \t <tr><td colspan="2"><span class="error">Wrong Email and Password</span></td></tr> 
 
\t \t \t </c:when> 
 
\t \t \t <c:otherwise test="#{SPRING_SECURITY_LAST_EXCEPTION.message == 'User is disabled'}"> 
 
\t \t \t \t <tr><td colspan="2"><span class="error">Recommender is Disabled</span></td></tr> 
 
\t \t \t </c:otherwise> 
 
\t \t \t <c:otherwise> 
 
\t \t \t \t <tr><td colspan="2"><span class="error"><h:outputText value="${SPRING_SECURITY_LAST_EXCEPTION.message}"/></span></td></tr> 
 
\t \t \t </c:otherwise> 
 
\t \t </c:choose> 
 
\t \t </c:if> 
 
\t \t <c:if test="${param.error != null}"> 
 
\t \t \t <c:if test="#{sessionScope['SpringError'] != null}"> 
 
\t \t \t \t <tr><td colspan="2"><span class="error"><h:outputText escape="false" value="#{sessionScope['SpringError']}"/></span></td></tr> 
 
\t \t \t </c:if> 
 
\t \t </c:if> 
 

 
\t \t <c:if test="${param.logout != null}"> 
 
\t \t \t <tr><td colspan="2" ><span class="message">You have been logged out.</span></td></tr> 
 
\t \t </c:if> 
 
\t </table> 
 

 
</h:form> 
 

 
</div> 
 

 
</h:body> 
 
    
 
</html>

package recBook; 
 

 
import java.util.Collection; 
 

 
import javax.annotation.Resource; 
 
import javax.servlet.http.HttpServletRequest; 
 

 
import org.springframework.beans.factory.annotation.Autowired; 
 
import org.springframework.security.core.AuthenticationException; 
 
import org.springframework.security.core.GrantedAuthority; 
 
import org.springframework.security.core.authority.AuthorityUtils; 
 
import org.springframework.security.core.userdetails.User; 
 
import org.springframework.security.core.userdetails.UserDetails; 
 
import org.springframework.security.core.userdetails.UserDetailsService; 
 
import org.springframework.security.core.userdetails.UsernameNotFoundException; 
 

 
@Resource 
 
public class MyUserDetails implements UserDetailsService { 
 

 
\t @Autowired 
 
\t private HttpServletRequest request; 
 
\t 
 
\t public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 
 
\t \t Users users = null; 
 
\t \t Authorities authority = null; 
 
\t \t try { 
 
\t \t \t users = new UsersDAO().select(username); 
 
\t \t \t authority = new AuthoritiesDAO().select(username); 
 
\t \t } catch (Exception e) { 
 
\t \t \t e.printStackTrace(); 
 
\t \t } 
 
\t \t 
 
\t \t Boolean enabled = true; 
 
\t \t String usernameOutro = "anonymousUser"; 
 
\t \t String passwordOutro = "WrongPassword"; 
 
\t \t Collection<? extends GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("WrongAuthority"); 
 
\t \t 
 
\t \t request.getSession().setAttribute("SpringError", ""); 
 
\t \t 
 
\t \t if(users != null && authority != null) { 
 
\t \t \t 
 
\t \t \t usernameOutro = users.getUsername(); 
 
\t \t \t passwordOutro = users.getPassword(); 
 
\t \t \t authorities = AuthorityUtils.createAuthorityList(authority.getAuthority()); 
 
\t \t \t 
 
\t \t \t /* 
 
\t \t \t * 
 
\t \t \t * Sets the login invalid for test 
 
\t \t \t * 
 
\t \t \t */ 
 
\t \t \t //users.setEnabled(0); 
 
\t \t \t //users.setDeletedByAdministrator(true); 
 
\t \t \t //users.setDeletedByRecommender(true); 
 
\t \t \t 
 
\t \t \t String errors = ""; 
 
\t \t \t 
 
\t \t \t if(users.getEnabled().equals(0)) { 
 
\t \t \t \t errors = "You Are Not Enabled to Login"; 
 
\t \t \t \t enabled = false; 
 
\t \t \t } 
 
\t \t \t 
 
\t \t \t if(users.getDeletedByAdministrator().equals(true)) { 
 
\t \t \t \t if(!errors.equals("")) { errors = errors + "<br />"; } 
 
\t \t \t \t errors = errors + "This RB Account Was Deleted By Recommendation Book Administrators"; 
 
\t \t \t \t enabled = false; 
 
\t \t \t } 
 
\t \t \t 
 
\t \t \t if(users.getDeletedByRecommender().equals(true)) { 
 
\t \t \t \t if(!errors.equals("")) { errors = errors + "<br />"; } 
 
\t \t \t \t errors = errors + "This RB Account Was Deleted By The Owner of This RB Account"; 
 
\t \t \t \t enabled = false; 
 
\t \t \t } 
 
\t \t \t 
 
\t \t \t request.getSession().setAttribute("SpringError", errors); 
 
\t \t } 
 
\t \t 
 
\t \t // User(String username, String password, boolean enabled, boolean accountNonExpired, 
 
\t \t // boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) 
 
\t \t return new User(usernameOutro, passwordOutro, enabled, true, true, true, authorities); 
 
\t } 
 

 
}

package recBook; 
 

 
import javax.sql.DataSource; 
 

 
import org.springframework.beans.factory.annotation.Autowired; 
 
import org.springframework.beans.factory.annotation.Qualifier; 
 
import org.springframework.context.annotation.Bean; 
 
import org.springframework.jdbc.datasource.DriverManagerDataSource; 
 
import org.springframework.security.authentication.AuthenticationManager; 
 
import org.springframework.security.authentication.AuthenticationProvider; 
 
import org.springframework.security.config.annotation.authentication.builders.*; 
 
import org.springframework.security.config.annotation.web.builders.HttpSecurity; 
 
import org.springframework.security.config.annotation.web.builders.WebSecurity; 
 
import org.springframework.security.config.annotation.web.configuration.*; 
 
import org.springframework.security.config.http.UserDetailsServiceFactoryBean; 
 
import org.springframework.security.core.userdetails.UserDetailsService; 
 
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 
 
import org.springframework.security.web.util.matcher.AntPathRequestMatcher; 
 

 
@EnableWebSecurity 
 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 
 
\t 
 
\t @Autowired 
 
\t MyUserDetails myUserDetails; 
 
\t 
 
\t @Autowired 
 
\t @Bean(name = "myUserDetails") 
 
\t public MyUserDetails MyUserDetails() { 
 
\t \t MyUserDetails myUserDetails = new MyUserDetails(); 
 
\t \t return myUserDetails; 
 
\t } 
 
\t 
 
\t @Autowired 
 
\t public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 
 
\t \t auth.userDetailsService(MyUserDetails()).passwordEncoder(passwordEncoder()); 
 
\t } 
 
\t 
 
\t @Bean 
 
\t public BCryptPasswordEncoder passwordEncoder() { 
 
\t \t return new BCryptPasswordEncoder(); 
 
\t } 
 
\t 
 
\t @Override 
 
\t protected void configure(HttpSecurity http) throws Exception { 
 
\t \t http 
 
\t \t \t .authorizeRequests() 
 
\t \t \t \t .antMatchers("/index.jsf", "/userPage.jsf").permitAll() 
 
\t \t \t \t .antMatchers("https://stackoverflow.com/users/**").permitAll() 
 
\t \t \t \t .antMatchers("/admin/**").hasAuthority("Administrator") 
 
\t \t \t \t .anyRequest().permitAll() 
 
\t \t \t \t .and() 
 
\t \t \t .formLogin().failureUrl("/login.jsf?error=true") 
 
\t \t \t \t .loginPage("/login.jsf") 
 
\t \t \t \t .permitAll() 
 
\t \t \t \t .and() 
 
\t \t \t .logout() 
 
\t \t \t \t .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) 
 
\t \t \t \t .permitAll() 
 
\t \t \t \t .logoutSuccessUrl("/login.jsf?logout=true") 
 
\t \t \t \t .and() 
 
\t \t \t .rememberMe().rememberMeParameter("remember-me") 
 
\t \t \t \t .and() 
 
\t \t \t .exceptionHandling().accessDeniedPage("/accessDenied.xhtml") 
 
\t \t \t \t .and() 
 
\t \t \t .csrf(); 
 
\t } 
 

 
}

<!-- Put this in web.xml --> 
 
<listener> 
 
\t <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> 
 
</listener>

関連する問題