身份验证失败:密码与存储值不匹配(请参阅更新2)

时间:2014-07-30 11:01:02

标签: java spring spring-mvc spring-security

在我目前的春季项目中,我有以下安全配置:

@Configuration
@ComponentScan(value="com.spring.loja")
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private SocialUserDetailsService socialUserDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void configure(WebSecurity web) throws Exception {
        DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler();
        handler.setPermissionEvaluator(new CustomPermissionEvaluator());
        web.expressionHandler(handler);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
                .disable()
            .authorizeRequests()
                .antMatchers("/resources/**", "/erro/**", "/categoria/**", "/produto/**", "/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/entrar").permitAll()
                .loginProcessingUrl("/login").permitAll()
                .usernameParameter("login")
                .passwordParameter("senha")
                .defaultSuccessUrl("/admin")
                .failureUrl("/entrar?erro=login").permitAll()
                .and()
            .exceptionHandling()
                .accessDeniedPage("/erro/403")
                .and()
            .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/").permitAll()
                .and()
            .apply(new SpringSocialConfigurer());
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .userDetailsService(userDetailsService)
            .passwordEncoder(passwordEncoder);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}

当我运行应用程序并尝试登录时,系统返回登录页面,即使使用正确的登录名称(我确定)。

任何人都可以看到这里有什么问题?

更新

我也尝试过这个问题。在我看来,这个配置无法访问我的userDetailsS​​ervice类,应该通过此类中的autowired属性进行检索:

@Configuration
@ComponentScan(value="com.spring.loja")
@EnableGlobalMethodSecurity(prePostEnabled=true)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private SocialUserDetailsService socialUserDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManagerBuilder auth;

    @Override
    public void configure(WebSecurity web) throws Exception {
        DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler();
        handler.setPermissionEvaluator(new CustomPermissionEvaluator());
        web.expressionHandler(handler);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
                .disable()
            .authorizeRequests()
                .antMatchers("/resources/**", "/erro/**", "/categoria/**", "/produto/**", "/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/entrar").permitAll()
                .loginProcessingUrl("/login").permitAll()
                .usernameParameter("login")
                .passwordParameter("senha")
                .defaultSuccessUrl("/admin")
                .failureUrl("/entrar?erro=login").permitAll()
                .and()
            .exceptionHandling()
                .accessDeniedPage("/erro/403")
                .and()
            .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/").permitAll()
                .and()
            .apply(new SpringSocialConfigurer());
    }

    @Autowired
    protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .userDetailsService(userDetailsService)
            .passwordEncoder(passwordEncoder);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return auth.getOrBuild();
    }

}

更新2

配置log4j后,我发现错误是密码与存储值不匹配。问题是我确保存储在数据库中的密码编码为MD5,而我的PasswordEncoder bean是这样的:

@Component
public class BCryptPasswordEncoder implements PasswordEncoder {

    @Override
    public String encode(CharSequence arg0) {
        try {
            return getMD5Hex((String) arg0);
        } catch (NoSuchAlgorithmException e) {
            return "NoSuchAlgorithmException";
        }
    }

    @Override
    public boolean matches(CharSequence arg0, String arg1) {
        return arg0.equals(encode(arg1));
    }

    public static String getMD5Hex(final String inputString) throws NoSuchAlgorithmException {

        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(inputString.getBytes());

        byte[] digest = md.digest();

        return convertByteToHex(digest);
    }

    private static String convertByteToHex(byte[] byteData) {

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < byteData.length; i++) {
            sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }

        return sb.toString();
    }

}

我明确告诉我要使用MD5。这里有什么问题?

ps:我也注意到应用程序没有使用我在SEcurityConfig类中定义的authenticationManager bean(问题中的第二个列表)

1 个答案:

答案 0 :(得分:2)

org.springframework.security.crypto.password.PasswordEncoder匹配方法有签名

boolean matches(CharSequence rawPassword, String encodedPassword);

因此,这意味着arg0是用户输入的密码,arg1是保存在DB中的编码密码。 所以实现应该是

 public boolean matches(CharSequence rawPassword, String encodedPassword) {
            return encodedPassword.equals(encode(rawPassword));
 }

您正在匹配方法中再次对编码密码进行编码,因为您使用的参数序列不正确。 使用有意义的名称而不是arg0,arg1是一种很好的做法,以避免混淆。