大家好,
我有一个任务,我必须创建3个页面: / login - 我们有电子邮件和密码输入, / result - 我们必须告诉用户他是否已经授权,如果成功,我们可以显示第3页 - / dataEntry 我们可以在DataBase中保存或更新用户的信息。
典型项目的区别在于用户电子邮件和密码在USERS.XML中,而不在数据库(DB)中
我已经通过 sax 和 dom 解析了它。
Parser返回 HashMap ,其中&#39; 键&#39;是&#39; 电子邮件&#39; <&#39; 值&#39;是&#39; 密码&#39;。
比我做默认域:
1) Login.class - 是auth的主要类,仅适用于users.xml。 它有下一个字段:电子邮件,密码。
2) User.class - 使用DB(保存,更新,加载用户信息)。它有下一个字段:id,email,firstName,secondName,gender。
接下来,我执行了此域的 dao 和 service 图层。 在我问的底部,我会给bitbucket一个链接,但请你仔细阅读我的问题。
我通过Java配置项目,所以我做了 Hibernate配置(它工作正常), Web配置(看起来它也能正常工作)和安全配置(此刻我想开始哭泣)。
我的安全配置:
SecurityWebApplicationInitializer
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
public SecurityWebApplicationInitializer() {
}
SecurityConfiguration
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
有人请帮助我。 非常感谢。
答案 0 :(得分:0)
需要将login-processing-url添加为“/ j_spring_security_check”才能工作,并在登录表单上添加“j_spring_security_check”操作。 在此处阅读更多内容:Spring migration