[英]Spring Security (Java Configuration) problems
大家好,
我有一個任務,必須創建3個頁面: / login-我們具有電子郵件和密碼輸入, / result-我們必須告訴用戶他是否已通過身份驗證,並且如果成功,我們可以顯示第3頁- / dataEntry ,我們可以在數據庫中保存或更新用戶的信息。
典型項目的區別是用戶的電子郵件和密碼在USERS.XML中而不在DataBase(DB)中
我已經通過sax和dom對其進行了解析。
解析器返回HashMap ,其中“ 鍵 ”是“ 電子郵件 ”,“ 值 ”是“ 密碼 ”。
比我做默認域:
1) Login.class-是進行身份驗證的主類,並且僅與users.xml一起使用。 它具有下一個字段:電子郵件,密碼。
2) User.class-與數據庫一起使用(保存,更新,加載用戶信息)。 它具有下一個字段:ID,電子郵件,firstName,secondName,性別。
接下來,我做了該域的dao和service層。 在我的詢問底部,我將提供一個有關bitbucket的鏈接,但請全部閱讀我的問題。
我通過Java配置項目,所以我進行了Hibernate配置 (它可以正常工作), Web配置 (似乎它也可以正常工作)和Security Configuration (此時我想開始哭泣)。
我的安全配置:
SecurityWebApplicationInitializer
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
public SecurityWebApplicationInitializer() {
}
安全配置
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
/**
* Holds userDetailsService
*/
@Autowired
@Qualifier("customUserDetailsService")
UserDetailsService userDetailsService;
/**
* Gets BCryptPasswordEncoder object.
*
* @return BCryptPasswordEncoder object.
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
/**
* Gets DaoAuthenticationProvider with its parameters
*
* @return authenticationProvider
*/
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService);
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}
/**
* Sets GlobalSecurity parameters.
*
* @param auth - AuthenticationManagerBuilder object.
* @throws Exception
*/
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
/**
* Sets Encoding parameters to work with russian locale, filters to get access to any page.
* /index is login and logout page by default - everybody can open this page.
* /result is page with results of login - everybody can open this page.
* /dataEntry is page to save/update/load user's info - only registered user can open this page.
*
* @param http - {@link HttpSecurity} object
* @throws Exception
*/
@Override
public void configure(HttpSecurity http) throws Exception {
//To work with UTF-8 and RU locale
CharacterEncodingFilter f = new CharacterEncodingFilter();
f.setEncoding("UTF-8");
f.setForceEncoding(true);
http
.addFilterBefore(f, CsrfFilter.class)
.formLogin().loginPage("/index").defaultSuccessUrl("/result")
.usernameParameter("email").passwordParameter("password")
.and().logout().logoutSuccessUrl("/index").invalidateHttpSession(true)
.and().httpBasic().realmName("ArtezioWebApp")
.and().authorizeRequests()
.antMatchers("/", "/index", "/result/**").permitAll()
.antMatchers("/result/**").hasAnyAuthority("ROLE_USER","ROLE_ANONYMOUS")
.antMatchers("/dataEntry/**").hasAuthority("ROLE_USER")
.and().csrf()
.and().exceptionHandling().accessDeniedPage("/result?error");
}
CustomUserDetailsService
public class CustomUserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService {
/**
* Holds logger.
*/
private static final Logger logger = LoggerFactory.getLogger(CustomUserDetailsService.class);
/**
* Holds {@link LoginService} object
*/
@Autowired
@Qualifier("loginService")
private LoginService loginService;
@Autowired
@Qualifier("login")
Login login;
/**
* Gets UserDetailsService object with parameters - email, password, authorities.
*
* @param email - by default has alias 'userName'
* @return UserDetailsService object with email,password and authorities.
* @throws UsernameNotFoundException if user was not found in *.xml file.
*/
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
//All users emails and passwords
HashMap<String, String> h = loginService.getUsers();
logger.info("Searching user with email '{}'...", email);
if (loginService.isValidEmail(email)) {
logger.info("User with email '{}' was found.", email);
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
//Saves data in Login object
login.setPassword(h.get(email));
login.setEmail(email);
return new org.springframework.security.core.userdetails.User(login.getEmail(),
login.getPassword(), true, true, true, true, authorities);
}
throw new UsernameNotFoundException("User with email '" + email + "' not found.");
}
當我調試項目時,我注意到從未調用@Overloaded方法loadByUsername(String email)。
即使我輸入了正確的電子郵件和密碼,SecurityContext也會向我返回anonymusUser。 所以我無法訪問/ dataEntry頁面。
鏈接到小桶: Bitbucket
有人請幫助我。 非常感謝
需要將login-processing-url添加為“ / j_spring_security_check”才能工作,並在登錄表單上添加操作作為“ j_spring_security_check”。 在此處了解更多信息: 春季遷移
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.