我使用Spring 3並從MySQL數據庫中抓取用戶。如何在Spring Security中檢查醃製密碼?
現在,在測試中,我有一個擁有MD5密碼的用戶。我可以使用它進行身份驗證。
但是,我們希望在密碼的散列方面更安全一些。我們想要:
MD5(username + salt + password)
鹽是存儲在用戶記錄中的隨機字符串。但我似乎無法弄清楚在哪裏/如何做到這一點。這是我到目前爲止有:
userDAO的
public class UserDao {
public static Users findUserByUsername(String paUsername) {
String hql = "from Users where username = :username";
List<Users> list = null;
Users user = null;
try {
IO io = new IO("web"); // custom Hibernate framework
IOQuery query = new IOQuery();
query.setStatement(hql);
query.setParameter(new IOParameter("username", paUsername));
list = io.runQuery(query);
if (list.isEmpty()) {
return null;
}
return list.get(0);
} catch (Exception ex) {
return null;
}
}
}
UserDetailsServiceImpl
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserDao userDao;
@Override
public UserDetails loadUserByUsername(String paUsername) throws UsernameNotFoundException {
Users user = userDao.findUserByUsername(paUsername);
if(user == null) {
throw new UsernameNotFoundException("User not found");
}
return new User(
user.getUsername(),
user.getPassword(),
user.getEnabled(),
true,
true,
true,
getAuthorities(Enums.UserRoles.IT));
}
private Collection<? extends GrantedAuthority> getAuthorities(Enums.UserRoles paRole) {
List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(paRole));
return authList;
}
private List<String> getRoles(Enums.UserRoles paRole) {
List<String> roles = new ArrayList<>();
if (paRole.equals(Enums.UserRoles.USER)) {
roles.add(Enums.UserRoles.USER.name());
} else if (paRole.equals(Enums.UserRoles.IT)) {
roles.add(Enums.UserRoles.USER.name());
roles.add(Enums.UserRoles.IT.name());
}
return roles;
}
private static List<GrantedAuthority> getGrantedAuthorities(List<String> paRoles) {
List<GrantedAuthority> authorities = new ArrayList<>();
for (String role : paRoles) {
authorities.add(new SimpleGrantedAuthority(role));
}
return authorities;
}
}
的UserDetailsService
public class UserDetailService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return new UserDetailsServiceImpl().loadUserByUsername(username);
}
}
安全應用程序上下文
<beans:bean id="loginSuccessHandler" class="com.myapp.security.LoginSuccessHandler" />
<beans:bean id="loginFailureHandler" class="com.myapp.security.LoginFailureHandler" />
<beans:bean id="detailsService" class="com.myapp.security.UserDetailService" />
什麼我需要做的任何想法?
感謝
如何讓Spring引用這個? – cbmeeks
@cbmeeks使用'String encryptedPassword = new PasswordEncoder()。encodePassword(pass,salt);'。在這裏檢查MessageDigestPasswordEncoder的API http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/authentication/encoding/MessageDigestPasswordEncoder.html –