0

Привет всем,Spring Security (Конфигурация Java) проблемы

У меня есть задача, где я должен создать 3 страницы: /Войти - где у нас есть адрес электронной почты и пароль входа, /результат - там, где мы должны сообщить пользователю, он авторизуется или нет, и в случае успеха мы можем показать 3-ю страницу - /dataEntry, где мы можем сохранить информацию о пользователеОбновления пользователя в DataBase.

Отличие типичного проекта пользователи электронной почты и пароли в users.xml не в базе данных (БД)

Я разобранного его саксофона и йот.

Parser возвращает HashMap где 'ключ' является 'электронной 'и' значение' является 'пароль.

Чем я сделал по умолчанию домены:

1) Login.class - это основной класс авторизовать и работать только с users.xml. Имеются следующие поля: адрес электронной почты, пароль.

2) User.class - для работы с БД (сохранение, обновление, загрузка информации пользователя). Он имеет следующие поля: id, email, firstName, secondName, gender.

Дальше я сделал dao и сервис уровни этих доменов. В нижней части моего запроса я дам ссылку на битбакет, но, пожалуйста, прочитайте мой вопрос.

настроить проект на Java, так что я сделал Hibernate конфигурации (она работает правильно), Web конфигурация (кажется, что он работает правильно тоже) и Security Configuration (в этот момент я хочу, чтобы начать плакать) ,

Моя конфигурация безопасности:

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

Необходимо добавить URL-адрес обработки для входа в систему как «/ j_spring_security_check» для работы и добавления действия в вашу регистрационную форму как «j_spring_security_check». Подробнее читайте здесь: Spring migration

Смежные вопросы