I want get client IP address in method loadUserByUsername() from class implUserDetailsService this my code but it doesn't work
@Service
public class LoginServiceImpl implements UserDetailsService {
@Autowired
UserDao loginDao;
@Autowired
private HttpServletRequest request;
@Override
public UserDetails loadUserByUsername(String username) {
try {
final String ip = getClientIp(request);
net.liyan.psc.main.entity.main.User user = loginDao.findByUserNameForLogin(username);
if (user == null) throw new UsernameNotFoundException("User not found.");
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
if (isLocalZone()) {
grantedAuthorities.add(new SimpleGrantedAuthority('ROLE_1'));
} else {
grantedAuthorities.add(new SimpleGrantedAuthority('ROLE_2'));
}
return new org.springframework.security.core.userdetails.User(
user.getUsername(),
user.getPassword(),
true,
true,
true,
true,
grantedAuthorities);
} catch (UsernameNotFoundException ex) {
throw new UsernameNotFoundException("User not found.");
} catch (Exception ex) {
throw new UsernameNotFoundException("User not found.");
}
}
private static String getClientIp(HttpServletRequest request) {
String remoteAddr = "";
if (request != null) {
remoteAddr = request.getHeader("X-FORWARDED-FOR");
if (remoteAddr == null || "".equals(remoteAddr)) {
remoteAddr = request.getRemoteAddr();
}
}
return remoteAddr;
}
private boolean isLocalZone(String Ip){
// ...
}
}
It get exseption:
java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.