Skip to content

Commit 7b256aa

Browse files
Doha2012pivovarit
authored andcommitted
whitelist ip range (eugenp#5221)
1 parent 1aa2340 commit 7b256aa

7 files changed

Lines changed: 179 additions & 0 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package org.baeldung.ip;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
6+
7+
@SpringBootApplication
8+
public class IpApplication extends SpringBootServletInitializer {
9+
public static void main(String[] args) {
10+
SpringApplication.run(IpApplication.class, args);
11+
}
12+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package org.baeldung.ip.config;
2+
3+
import java.util.ArrayList;
4+
import java.util.HashSet;
5+
import java.util.List;
6+
import java.util.Set;
7+
8+
import org.springframework.security.authentication.AuthenticationProvider;
9+
import org.springframework.security.authentication.BadCredentialsException;
10+
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
11+
import org.springframework.security.core.Authentication;
12+
import org.springframework.security.core.AuthenticationException;
13+
import org.springframework.security.core.GrantedAuthority;
14+
import org.springframework.security.core.authority.SimpleGrantedAuthority;
15+
import org.springframework.security.web.authentication.WebAuthenticationDetails;
16+
import org.springframework.stereotype.Component;
17+
18+
@Component
19+
public class CustomIpAuthenticationProvider implements AuthenticationProvider {
20+
21+
Set<String> whitelist = new HashSet<String>();
22+
23+
public CustomIpAuthenticationProvider() {
24+
super();
25+
whitelist.add("11.11.11.11");
26+
whitelist.add("127.0.0.1");
27+
}
28+
29+
@Override
30+
public Authentication authenticate(Authentication auth) throws AuthenticationException {
31+
WebAuthenticationDetails details = (WebAuthenticationDetails) auth.getDetails();
32+
String userIp = details.getRemoteAddress();
33+
if(! whitelist.contains(userIp)){
34+
throw new BadCredentialsException("Invalid IP Address");
35+
}
36+
final String name = auth.getName();
37+
final String password = auth.getCredentials().toString();
38+
39+
if (name.equals("john") && password.equals("123")) {
40+
List<GrantedAuthority> authorities =new ArrayList<GrantedAuthority>();
41+
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
42+
return new UsernamePasswordAuthenticationToken(name, password, authorities);
43+
}
44+
else{
45+
throw new BadCredentialsException("Invalid username or password");
46+
}
47+
}
48+
49+
@Override
50+
public boolean supports(Class<?> authentication) {
51+
return authentication.equals(UsernamePasswordAuthenticationToken.class);
52+
}
53+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package org.baeldung.ip.config;
2+
3+
import org.springframework.beans.factory.annotation.Autowired;
4+
import org.springframework.context.annotation.Configuration;
5+
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
6+
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
7+
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
8+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
9+
10+
@Configuration
11+
@EnableWebSecurity
12+
public class SecurityConfig extends WebSecurityConfigurerAdapter {
13+
14+
@Autowired
15+
private CustomIpAuthenticationProvider authenticationProvider;
16+
17+
@Override
18+
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
19+
auth.inMemoryAuthentication().withUser("john").password("{noop}123").authorities("ROLE_USER");
20+
// auth.authenticationProvider(authenticationProvider);
21+
}
22+
23+
@Override
24+
protected void configure(final HttpSecurity http) throws Exception {
25+
// @formatter:off
26+
http.authorizeRequests()
27+
.antMatchers("/login").permitAll()
28+
// .antMatchers("/foos/**").hasIpAddress("11.11.11.11")
29+
.antMatchers("/foos/**").access("isAuthenticated() and hasIpAddress('11.11.11.11')")
30+
.anyRequest().authenticated()
31+
.and().formLogin().permitAll()
32+
.and().csrf().disable();
33+
// @formatter:on
34+
}
35+
36+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package org.baeldung.ip.config;
2+
3+
4+
//@Configuration
5+
//@EnableWebSecurity
6+
//@ImportResource({ "classpath:spring-security-ip.xml" })
7+
public class SecurityXmlConfig {
8+
9+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package org.baeldung.ip.web;
2+
3+
import javax.servlet.http.HttpServletRequest;
4+
5+
import org.baeldung.custom.persistence.model.Foo;
6+
import org.springframework.stereotype.Controller;
7+
import org.springframework.web.bind.annotation.PathVariable;
8+
import org.springframework.web.bind.annotation.RequestMapping;
9+
import org.springframework.web.bind.annotation.RequestMethod;
10+
import org.springframework.web.bind.annotation.ResponseBody;
11+
12+
@Controller
13+
public class MainController {
14+
15+
@RequestMapping(method = RequestMethod.GET, value = "/foos/{id}")
16+
@ResponseBody
17+
public Foo findById(@PathVariable final long id, HttpServletRequest request) {
18+
return new Foo("Sample");
19+
}
20+
21+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<beans xmlns="http://www.springframework.org/schema/beans"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:security="http://www.springframework.org/schema/security"
4+
xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.2.xsd
5+
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
6+
7+
<security:authentication-manager>
8+
<security:authentication-provider>
9+
<security:user-service>
10+
<security:user name="john" password="{noop}123" authorities="ROLE_USER" />
11+
</security:user-service>
12+
</security:authentication-provider>
13+
</security:authentication-manager>
14+
15+
<security:http>
16+
<security:form-login/>
17+
<security:intercept-url pattern="/login" access="permitAll()" />
18+
<security:intercept-url pattern="/foos/**" access="hasIpAddress('11.11.11.11')" />
19+
<security:intercept-url pattern="/**" access="isAuthenticated()" />
20+
</security:http>
21+
</beans>
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package org.baeldung.web;
2+
3+
import static org.junit.Assert.assertEquals;
4+
import static org.junit.Assert.assertTrue;
5+
import io.restassured.RestAssured;
6+
import io.restassured.response.Response;
7+
8+
import org.junit.Test;
9+
10+
11+
public class IpLiveTest {
12+
13+
@Test
14+
public void givenUser_whenGetHomePage_thenOK() {
15+
final Response response = RestAssured.given().auth().form("john", "123").get("http://localhost:8082/");
16+
assertEquals(200, response.getStatusCode());
17+
assertTrue(response.asString().contains("Welcome"));
18+
}
19+
20+
@Test
21+
public void givenUserWithWrongIP_whenGetFooById_thenForbidden() {
22+
final Response response = RestAssured.given().auth().form("john", "123").get("http://localhost:8082/foos/1");
23+
assertEquals(403, response.getStatusCode());
24+
assertTrue(response.asString().contains("Forbidden"));
25+
}
26+
27+
}

0 commit comments

Comments
 (0)