【问题标题】:Spring Security (Java Configuration) problemsSpring Security(Java配置)问题
【发布时间】:2016-12-17 00:46:23
【问题描述】:

大家好,

我有一个任务,我必须创建 3 个页面: /login- 我们输入电子邮件和密码的地方, /result - 我们必须告诉用户他是否经过身份验证,如果成功,我们可以显示第三页 - /dataEntry 我们可以在其中保存或更新数据库中的用户信息。

典型项目的区别在于用户邮箱和密码在 USERS.XML 中而不是在数据库(DB)中

我已经通过 saxdom 对其进行了解析。

解析器返回 HashMap,其中 'key' 是 'email' 而 'value' 是 '密码'。

比我做的默认域:

1) Login.class - 是主要的认证类,仅与 users.xml 一起使用。 它有下一个字段:电子邮件、密码。

2) User.class - 使用 DB(保存、更新、加载用户信息)。它有下一个字段:id、email、firstName、secondName、gender。

接下来我做了这个域的 daoservice 层。 在我询问的底部,我将提供 bitbucket 的链接,但请阅读我的全部问题。

我通过 Java 配置项目,所以我做了 Hibernate 配置(它工作正常)、Web 配置(似乎也能正常工作)和 安全配置(此刻我想哭)。

我的安全配置:

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");
}

自定义用户详细信息服务

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

请任何人帮助我。 非常感谢。

【问题讨论】:

    标签: java security spring-security spring-4 userdetailsservice


    【解决方案1】:

    需要将 login-processing-url 添加为“/j_spring_security_check”才能工作,并将登录表单上的操作添加为“j_spring_security_check”。 在这里阅读更多:Spring migration

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-02
      • 2015-11-19
      • 1970-01-01
      • 1970-01-01
      • 2017-07-17
      • 1970-01-01
      • 1970-01-01
      • 2018-07-24
      相关资源
      最近更新 更多