2016-03-09 26 views
0

在我的Spring项目中,我定义了自己的自定义身份验证提供程序。在引入Spring Security之前,我在Java代码中使用了BCrypt,现在在数据库中进行BCrypting后保存密码。如何将brcypt编码器引用到定制身份验证提供程序?

弹簧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; 
    } 

} 

我不想使用user-service-ref在弹簧security.xml文件wihtin认证经理。

回答

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/

+0

我得到这个org.springframework.beans.factory.parsing.BeanDefinitionParsingException:配置问题:authentication-provider元素在与'ref'属性一起使用时不能有子元素。另外我想引用我的自定义身份验证提供程序。 – user3705478

1

如果您的用户密码数据库已经储存为BCrypt你并不需要太多的做事情。在您的身份验证方法,就像下面

if (BCrypt.checkpw(password, user.getPassword())) { 
     throw new BadCredentialsException("Wrong password."); 
    } 

参考BCrypt源的详细信息,取代密码检查条件。

+0

好的。我现在所面临的另一个问题是\t @覆盖 \t认证公开身份验证(验证认证) \t \t \t抛出的AuthenticationException { \t \t authentication.getCredentials()返回“”但authentication.getName()返回由用户输入的用户名在登录表单中。 – user3705478

+0

它可能是'password-parameter'在登录表单上的密码字段上不匹配。如果答案是正确的,并且您的主要问题已解决,请接受答案 – Yogesh

相关问题