简体   繁体   English

Spring Security(Java配置)问题

[英]Spring Security (Java Configuration) problems

Hello everybody, 大家好,

I have a task where I have to create 3 pages: /login - where we have email and password inputs, /result - where we have to tell user does he authificated or not, and in case of successful we can show 3rd page - /dataEntry where we can saveOrUpdate user's info in DataBase. 我有一个任务,必须创建3个页面: / login-我们具有电子邮件和密码输入, / result-我们必须告诉用户他是否已通过身份验证,并且如果成功,我们可以显示第3页- / dataEntry ,我们可以在数据库中保存或更新用户的信息。

The difference of typical project is users email and passwords are in USERS.XML not in DataBase(DB) 典型项目的区别是用户的电子邮件和密码在USERS.XML中而不在DataBase(DB)中

I've parsed it by sax and dom . 我已经通过saxdom对其进行了解析。

Parser returns HashMap where ' key ' is ' email 'and ' value ' is ' password '. 解析器返回HashMap ,其中“ ”是“ 电子邮件 ”,“ ”是“ 密码 ”。

Than I did default domains: 比我做默认域:

1) Login.class - is the main class to auth and to work only with users.xml. 1) Login.class-是进行身份验证的主类,并且仅与users.xml一起使用。 It has next fields: email , password. 它具有下一个字段:电子邮件,密码。

2) User.class - to work with DB (save,update,load user's info). 2) User.class-与数据库一起使用(保存,更新,加载用户信息)。 It has next fields: id, email, firstName, secondName, gender. 它具有下一个字段:ID,电子邮件,firstName,secondName,性别。

Next I did dao and service layers of this domains. 接下来,我做了该域的daoservice层。 On the bottom of my ask I will give a link for bitbucket but please read my question all. 在我的询问底部,我将提供一个有关bitbucket的链接,但请全部阅读我的问题。

I configure project by Java , so I did Hibernate configuration (it works correct), Web configuration (seems like it works correctly too) and Security Configuration (at this moment I want to start crying). 我通过Java配置项目,所以我进行了Hibernate配置 (它可以正常工作), Web配置 (似乎它也可以正常工作)和Security Configuration (此时我想开始哭泣)。

My Security Configuration: 我的安全配置:

SecurityWebApplicationInitializer 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 CustomUserDetailsS​​ervice

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

When I debugged project I noticed that @Overloaded method loadByUsername(String email) is never invoked. 当我调试项目时,我注意到从未调用@Overloaded方法loadByUsername(String email)。

SecurityContext returns me anonymusUser even I entered correct email and password. 即使我输入了正确的电子邮件和密码,SecurityContext也会向我返回anonymusUser。 So I cant get access to /dataEntry page. 所以我无法访问/ dataEntry页面。

LINK TO BITBUCKET: Bitbucket 链接到小桶: Bitbucket

Anybody please help me. 有人请帮助我。 Thank you much. 非常感谢

Need to add login-processing-url as "/j_spring_security_check" to work and add action on your login form as "j_spring_security_check". 需要将login-processing-url添加为“ / j_spring_security_check”才能工作,并在登录表单上添加操作作为“ j_spring_security_check”。 Read more here : Spring migration 在此处了解更多信息: 春季迁移

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM