Fork me on GitHub

IP address validation (v1.9)

pac4j allows you to validate incoming IP address.

1) Dependency

You need to use the following module: pac4j-http.

Example (Maven dependency):

<dependency>
    <groupId>org.pac4j</groupId>
    <artifactId>pac4j-http</artifactId>
    <version>${pac4j.version}</version>
</dependency>

2) IpRegexpAuthenticator

The IpRegexpAuthenticator allows you to check that a given IP address is valid. It is generally defined for an IpClient.

After a successful credentials validation, it “returns” an IpProfile.

Example:

IpClient ipClient = new IpClient(new IpRegexpAuthenticator("10\\..*"));

The IP address is retrieved via the context.getRemoteAddr() method. Though, on some infrastructure, the IP address is available in an HTTP header (like X-Forwarded-For). So you can define the HTTP header from which you preferably want to retrieve the IP address.

Example:

IpClient ipClient = new IpClient(new IpRegexpAuthenticator("10\\..*"));
IpExtractor ipHeaderExtractor = new IpExtractor(ipClient.getName());
ipHeaderExtractor.setAlternateIpHeader("X-Forwarded-For");
ipClient.setCredentialsExtractor(ipHeaderExtractor);