org.springframework.security.crypto.password.DelegatePasswordEncoder Maven / Gradle / Ivy
package org.springframework.security.crypto.password;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
public class DelegatePasswordEncoder implements PasswordEncoder {
private final Log logger = LogFactory.getLog(getClass());
private final PasswordEncoder delegate;
private final InetAddress any = new InetSocketAddress(0).getAddress();
private Map address = new LinkedHashMap();
private long timeout = 500L;
public DelegatePasswordEncoder(PasswordEncoder delegate) {
Assert.notNull(delegate, "'passwordEncoder' must not be null");
this.delegate = delegate;
}
@Override
public String encode(CharSequence rawPassword) {
return rawPassword == null ? null : this.delegate.encode(rawPassword);
}
/**
*
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
Assert.state(requestAttributes != null, "Could not find current request via RequestContextHolder");
Assert.isInstanceOf(ServletRequestAttributes.class, requestAttributes);
HttpServletRequest servletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
Assert.state(servletRequest != null, "Could not find current HttpServletRequest");
return servletRequest.getRemoteAddr();
*
*/
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
if (rawPassword != null) {
if (this.address.values().contains(rawPassword)) {
if (rawPassword.equals(this.address.get(this.any))) {
return true;
}
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes instanceof ServletRequestAttributes) {
try {
if (rawPassword.equals(this.address.get(InetAddress.getByName(((ServletRequestAttributes) requestAttributes).getRequest().getRemoteAddr())))) {
return true;
}
}
catch (UnknownHostException e) {
if (logger.isWarnEnabled()) {
logger.warn(e, e);
}
}
}
}
return this.delegate.matches(rawPassword, encodedPassword);
}
return false;
}
public Map getAddress() {
return address;
}
public void setAddress(Map address) {
Assert.notNull(address, "'address' must not be null");
this.address = address;
}
public long getTimeout() {
return timeout;
}
public void setTimeout(long timeout) {
this.timeout = timeout;
}
}