|
| 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 | +} |
0 commit comments