大家好,
我有一个任务,我必须创建 3 个页面: /login - 我们输入电子邮件和密码的地方, /result - 我们必须告诉用户他是否经过身份验证,如果成功,我们可以显示第 3 页 - / dataEntry 我们可以在其中保存或更新数据库中的用户信息。
典型项目的不同之处在于用户电子邮件和密码在 USERS.XML 中而不是在数据库(DB)中
我已经用sax和dom解析了它。
Parser 返回HashMap,其中“ key ”是“ email ”,“ value ”是“ password ”。
比我做的默认域:
1) Login.class - 是主要的认证类,只能与 users.xml 一起使用。它有下一个字段:电子邮件、密码。
2) User.class - 使用数据库(保存、更新、加载用户信息)。它有下一个字段:id、email、firstName、secondName、gender。
接下来我做了这个域的dao和service层。在我的询问底部,我将提供 bitbucket 的链接,但请全部阅读我的问题。
我通过 Java 配置项目,所以我做了Hibernate 配置(它工作正常)、Web 配置(似乎它也工作正常)和安全配置(此刻我想哭了)。
我的安全配置:
安全WebApplicationInitializer
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 的链接:Bitbucket
任何人请帮助我。非常感谢。