我在Spring启动应用程序中使用spring security。目前,我们可以选择使用用户名和密码生成令牌。现在我需要修改选项,例如我想要用户名作为电子邮件和密码作为手机号码。是否可以像这样使用。
答案 0 :(得分:0)
是的,您可以选择使用自定义值。例如,检查以下代码,
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import sunbox.dao.IUserDAO;
import java.util.ArrayList;
import java.util.List;
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private IUserDAO iuserDAO;
@Autowired
public CustomUserDetailsService(IUserDAO iuserDAO) {
this.iuserDAO = iuserDAO;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
sunbox.domain.User usr = iuserDAO.getUserByEmail(s);
if (usr == null) {
throw new UsernameNotFoundException("User details not found with this username: " + s);
}
String username = usr.getEmail();
String password = usr.getMobile();
String role = usr.getUserType().getUserTypeName();
List authList = getAuthorities(role);
User user = new User(username, password, authList);
return user;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private List getAuthorities(String role) {
List authList = new ArrayList();
authList.add(new SimpleGrantedAuthority("ROLE_USER"));
if (role != null && role.trim().length() > 0) {
if (role.equals("admin")) {
authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
}
}
return authList;
}
}