Spring Security 3: Salting password issue

夙愿已清 提交于 2019-12-03 12:24:11

ReflectionSaltSource extracts a salt from the instance of UserDetails. But you use org.springframework.security.core.userdetails.User as an implementation of UserDetails, and it doesn't have a property named id (instead of that you have this property in UserDetailsAdapter, that doesn't make sense, since UserDetailsAdapter is a singleton).

So, you need to create a subclass of org.springframework.security.core.userdetails.User with id property, and return it from your UserDetailsAdapter.

Here are the updated files that made it working:

UserDetailsAdapter.java

public class UserDetailsAdapter extends org.springframework.security.core.userdetails.User {
    private final Long id;
    public UserDetailsAdapter(User userEntity) {

        super(userEntity.getUsername(), userEntity.getPassword(), userEntity.isEnabled(), true, true, true, toAuthorities(userEntity.getAuthorities()));
        this.id = userEntity.getId();
    }

    private static Collection<GrantedAuthority> toAuthorities(List<String> authorities) {
        Collection<GrantedAuthority> authorityList = new ArrayList<GrantedAuthority>();
        for (String authority: authorities) {
            authorityList.add(new GrantedAuthorityImpl(authority));
        }
        return authorityList;
    }

    public Long getId() {
        return id;
    }

}

UserDetailsServiceImpl.java

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserDao userDao;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
        UserDetails userDetails = null;
        User userEntity = userDao.findByUsername(username);

        if (userEntity == null) {
          throw new UsernameNotFoundException("user not found");
        }
        userDetails = new UserDetailsAdapter(userEntity);

        return userDetails;
    }
}

UserServiceImpl.java

@Service
public class UserServiceImpl implements UserService {
...
    public void createUser(User user) {
        userDao.create(user);

        UserDetailsAdapter userDetails = new UserDetailsAdapter(user);
        String password = userDetails.getPassword();
        Object salt = saltSource.getSalt(userDetails);
        user.setPassword(passwordEncoder.encodePassword(password, salt));
        userDao.update(user);

    }
...
}

Thanks :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!