如何将brcypt编码器引用到自定义身份验证提供程序?

时间:2016-03-09 18:45:50

标签: java spring spring-mvc spring-security

在我的Spring项目中,我定义了自己的自定义身份验证提供程序。在引入Spring Security之前,我在Java代码中使用了BCrypt,现在在BCrypting数据库之后保存了密码。

spring-security.xml

 <security:authentication-manager>
            <security:authentication-provider ref="myAuthenticationProvider">
            </security:authentication-provider> 
       </security:authentication-manager> 

    <b:bean id="bcryptEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />

    <b:bean id="myAuthenticationProvider" class="com.cT.www.provider.CustomAuthenticationProvider">
    </b:bean>

我的自定义身份验证提供程序如下所示。

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    public CustomAuthenticationProvider() {
        super();
    }


    @Autowired
    private PersonService personService;    

    @Override
    public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {

        System.out.println(authentication.getName() + "principal" +(String) authentication.getCredentials() );

        String username = authentication.getName();
        String password = (String) authentication.getCredentials();

        UserSignUp user = (UserSignUp) personService.loadUserByUsername(username);

        if (user == null || !user.getUsername().equalsIgnoreCase(username)) {
            throw new BadCredentialsException("Username not found.");
        }

        if (!password.equals(user.getPassword())) {
            throw new BadCredentialsException("Wrong password.");
        }

        List<Role> authorities = user.getAuthorities();

        return new UsernamePasswordAuthenticationToken(user, password, authorities);
    }

    @Override
    public boolean supports(Class<?> arg0) {
        // TODO Auto-generated method stub
        return true;
    }

}

我不想在认证管理器的spring-security.xml中使用user-service-ref

2 个答案:

答案 0 :(得分:1)

如果您的用户密码已在数据库中保存为BCrypt,则您不需要做太多事情。在您的身份验证方法中,只需用下面的

替换您的密码检查条件
    if (BCrypt.checkpw(password, user.getPassword())) {
       throw new BadCredentialsException("Wrong password.");
    }

有关详细信息,请参阅BCrypt来源。

答案 1 :(得分:0)

您可以这样参考BCryptPasswordEncoder:

  <authentication-manager>
    <authentication-provider>
        <password-encoder ref="encoder" />
    </authentication-provider>
  </authentication-manager>

  <beans:bean id="encoder" 
    class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
    <beans:constructor-arg name="strength" value="11" />
  </beans:bean>

有关详细信息,请参阅http://www.mkyong.com/spring-security/spring-security-password-hashing-example/