Почему мой веб-сервис запрещает мои соединения при использовании .hasIpAddress ()? - PullRequest
0 голосов
/ 23 октября 2019

Defintieyl уже искал stackex для этого. Проблемы с hasIpAddress часто кажутся уникальными.

Мне кажется, я понимаю маршрут моего запроса на мой сервер.

Пользователь -> Zuul -> Мой веб-сервис

http.authorizeRequests().antMatchers("/**").permitAll(); 

в моем веб-сервисе позволяет отправлять запросы и получать ответы от localhost и IP-адреса моей системы.

http.authorizeRequests().antMatchers("/**").hasIpAddress(10.10.1.24);

или

http.authorizeRequests().antMatchers("/**").hasIpAddress("127.0.0.1");

оба не удаются.

Когда Zuul даетдоступ к моему веб-сервису ... он неверно сообщает IP-адрес моего запроса или что-то еще?

Если мой hasIpAddress () не должен быть localhost, 127.0.0.1 или 10.10.1.24, тогда что еще это может быть?

Я отключил Зуула, Эврику и всех остальных и снова их всех запустил. Я также сделал Maven Clean.

2019-10-23 11:58:46.608  INFO 7468 --- [  restartedMain] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@27040a7b, org.springframework.security.web.context.SecurityContextPersistenceFilter@6d6a2d29, org.springframework.security.web.header.HeaderWriterFilter@3485fdae, org.springframework.security.web.authentication.logout.LogoutFilter@198a3831, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@2c7fb62d, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@20043371, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@ad82f08, org.springframework.security.web.session.SessionManagementFilter@2285c828, org.springframework.security.web.access.ExceptionTranslationFilter@6511c7f9, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@7e27dfef]
2019-10-23 11:58:46.618  WARN 7468 --- [  restartedMain] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
2019-10-23 11:58:46.618  INFO 7468 --- [  restartedMain] c.n.c.sources.URLConfigurationSource     : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2019-10-23 11:58:46.621  WARN 7468 --- [  restartedMain] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
2019-10-23 11:58:46.621  INFO 7468 --- [  restartedMain] c.n.c.sources.URLConfigurationSource     : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2019-10-23 11:58:46.731  INFO 7468 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-10-23 11:58:47.264  WARN 7468 --- [  restartedMain] ockingLoadBalancerClientRibbonWarnLogger : You already have RibbonLoadBalancerClient on your classpath. It will be used by default. As Spring Cloud Ribbon is in maintenance mode. We recommend switching to BlockingLoadBalancerClient instead. In order to use it, set the value of `spring.cloud.loadbalancer.ribbon.enabled` to `false` or remove spring-cloud-starter-netflix-ribbon from your project.
2019-10-23 11:58:47.365  INFO 7468 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 54293 (http) with context path ''
2019-10-23 11:58:47.366  INFO 7468 --- [  restartedMain] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 54293
2019-10-23 11:58:47.370  INFO 7468 --- [  restartedMain] o.s.c.n.eureka.InstanceInfoFactory       : Setting initial instance status as: STARTING
2019-10-23 11:58:47.392  INFO 7468 --- [  restartedMain] com.netflix.discovery.DiscoveryClient    : Initializing Eureka in region us-east-1
2019-10-23 11:58:47.491  INFO 7468 --- [  restartedMain] c.n.d.provider.DiscoveryJerseyProvider   : Using JSON encoding codec LegacyJacksonJson
2019-10-23 11:58:47.492  INFO 7468 --- [  restartedMain] c.n.d.provider.DiscoveryJerseyProvider   : Using JSON decoding codec LegacyJacksonJson
2019-10-23 11:58:47.570  INFO 7468 --- [  restartedMain] c.n.d.provider.DiscoveryJerseyProvider   : Using XML encoding codec XStreamXml
2019-10-23 11:58:47.571  INFO 7468 --- [  restartedMain] c.n.d.provider.DiscoveryJerseyProvider   : Using XML decoding codec XStreamXml
2019-10-23 11:58:47.690  INFO 7468 --- [  restartedMain] c.n.d.s.r.aws.ConfigClusterResolver      : Resolving eureka endpoints via configuration
2019-10-23 11:58:47.814  INFO 7468 --- [  restartedMain] com.netflix.discovery.DiscoveryClient    : Disable delta property : false
2019-10-23 11:58:47.814  INFO 7468 --- [  restartedMain] com.netflix.discovery.DiscoveryClient    : Single vip registry refresh property : null
2019-10-23 11:58:47.814  INFO 7468 --- [  restartedMain] com.netflix.discovery.DiscoveryClient    : Force full registry fetch : false
2019-10-23 11:58:47.814  INFO 7468 --- [  restartedMain] com.netflix.discovery.DiscoveryClient    : Application is null : false
2019-10-23 11:58:47.815  INFO 7468 --- [  restartedMain] com.netflix.discovery.DiscoveryClient    : Registered Applications size is zero : true
2019-10-23 11:58:47.815  INFO 7468 --- [  restartedMain] com.netflix.discovery.DiscoveryClient    : Application version is -1: true
2019-10-23 11:58:47.815  INFO 7468 --- [  restartedMain] com.netflix.discovery.DiscoveryClient    : Getting all instance registry info from the eureka server
2019-10-23 11:58:47.890  INFO 7468 --- [  restartedMain] com.netflix.discovery.DiscoveryClient    : The response status is 200
2019-10-23 11:58:47.892  INFO 7468 --- [  restartedMain] com.netflix.discovery.DiscoveryClient    : Starting heartbeat executor: renew interval is: 30
2019-10-23 11:58:47.894  INFO 7468 --- [  restartedMain] c.n.discovery.InstanceInfoReplicator     : InstanceInfoReplicator onDemand update allowed rate per min is 4
2019-10-23 11:58:47.897  INFO 7468 --- [  restartedMain] com.netflix.discovery.DiscoveryClient    : Discovery Client initialized at timestamp 1571842727896 with initial instances count: 0
2019-10-23 11:58:47.900  INFO 7468 --- [  restartedMain] o.s.c.n.e.s.EurekaServiceRegistry        : Registering application USERS-WS with eureka with status UP
2019-10-23 11:58:47.900  INFO 7468 --- [  restartedMain] com.netflix.discovery.DiscoveryClient    : Saw local status change event StatusChangeEvent [timestamp=1571842727900, current=UP, previous=STARTING]
2019-10-23 11:58:47.902  INFO 7468 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_USERS-WS/users-ws:90ae4ec0932916bcd2b9155854f3a269: registering service...
2019-10-23 11:58:47.945  INFO 7468 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_USERS-WS/users-ws:90ae4ec0932916bcd2b9155854f3a269 - registration status: 204
2019-10-23 11:58:48.064  INFO 7468 --- [  restartedMain] c.p.p.a.u.PhotoAppApiUsersApplication    : Started PhotoAppApiUsersApplication in 5.037 seconds (JVM running for 5.825)
2019-10-23 11:59:17.895  INFO 7468 --- [freshExecutor-0] com.netflix.discovery.DiscoveryClient    : Disable delta property : false
2019-10-23 11:59:17.895  INFO 7468 --- [freshExecutor-0] com.netflix.discovery.DiscoveryClient    : Single vip registry refresh property : null
2019-10-23 11:59:17.895  INFO 7468 --- [freshExecutor-0] com.netflix.discovery.DiscoveryClient    : Force full registry fetch : false
2019-10-23 11:59:17.896  INFO 7468 --- [freshExecutor-0] com.netflix.discovery.DiscoveryClient    : Application is null : false
2019-10-23 11:59:17.896  INFO 7468 --- [freshExecutor-0] com.netflix.discovery.DiscoveryClient    : Registered Applications size is zero : true
2019-10-23 11:59:17.896  INFO 7468 --- [freshExecutor-0] com.netflix.discovery.DiscoveryClient    : Application version is -1: false
2019-10-23 11:59:17.896  INFO 7468 --- [freshExecutor-0] com.netflix.discovery.DiscoveryClient    : Getting all instance registry info from the eureka server
2019-10-23 11:59:17.959  INFO 7468 --- [freshExecutor-0] com.netflix.discovery.DiscoveryClient    : The response status is 200

Ответы [ 2 ]

1 голос
/ 30 октября 2019

Вот рабочий базовый пример использования spring-boot 2.2.0.RELEASE с spring-boot-starter-security и spring-boot-starter-web

Работает при доступе через http://localhost:8080/ip


@SpringBootApplication
public class SpringSecurityHasIpAddressApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringSecurityHasIpAddressApplication.class, args);
    }

}

@RestController
class HelloController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello World!";
    }


    @GetMapping("/ip")
    public String ip(HttpServletRequest request) {
        return request.getRemoteAddr();
    }


    @GetMapping("/secure")
    public String secure(Principal principal,HttpServletRequest request) {
        return principal.getName() + " with " + request.getRemoteAddr();
    }
}

@Configuration
class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests(
                    authorizeRequests ->
                        authorizeRequests
                            .antMatchers("/hello").permitAll()
                            .antMatchers("/secure").authenticated()
                            .antMatchers("/ip").hasIpAddress("0:0:0:0:0:0:0:1") // localhost
                            .anyRequest().authenticated()
            )
            .formLogin();
    }
}

Вы можете получить доступ к /secureпуть, то вы можете увидеть, что вы на самом деле использовали IP-адрес.

0:0:0:0:0:0:0:1 - мой локальный адрес, поэтому я могу получить доступ к /ip без аутентификации


Установка уровня ведения журнала org.springframework.security также может быть очень полезна.

application.properties

logging.level.org.springframework.security=debug

, тогда вы можете увидеть в журнале что-то вроде:

2019-10-30 19: 14: 01.039 DEBUG 3692 -- [nio-8080-exec-6] osswaiFilterSecurityInterceptor: предварительно аутентифицированный: org.springframework.security.authentication.AnonymousAuthenticationToken@536ff536: принципал: anonymousUser;Полномочия: [ЗАЩИЩЕНО];Аутентифицировано: правда;Подробности: org.springframework.security.web.authentication.WebAuthenticationDetails@166c8: RemoteIpAddress: 0: 0: 0: 0: 0: 0: 0: 1; SessionId: 7602343558C34E2576CD0D3E20EDCBEE;Предоставленные полномочия: ROLE_ANONYMOUS 2019-10-30 19: 14: 01.040 DEBUG 3692 --- [nio-8080-exec-6] ossaccess.vote.AffirmatoryBased: Voter: org.springframework.security.web.access.expression.WebExpressionVoter @7527e914, возвращено: -1 2019-10-30 19: 14: 01.041 DEBUG 3692 --- [nio-8080-exec-6] osswaExceptionTranslationFilter: Доступ запрещен (пользователь анонимный);перенаправление к точке входа аутентификации


, если вы попытаетесь через http://127.0.0.1/ip выше решение не получится, вы можете использовать

        ...
        .antMatchers("/ip").hasIpAddress("127.0.0.1/32")
        ...


Если вы хотите использоватьдиапазон разрешенных IP-адресов, которые вы могли бы использовать

        ...
        .antMatchers("/access") // multiple IP matching
              .access("hasIpAddress('192.168.0.1/16') or hasIpAddress('127.0.0.1/32')") 
        ...

0 голосов
/ 03 ноября 2019

hasIpAddress(1.1.1.1) всегда работал нормально для меня. вам не нужен / 32, но вы можете использовать его. на самом деле это тот же IP с / 32 на нем, но он вам действительно нужен, если вы пытаетесь сопоставить диапазон IP в подсети. Я предполагаю, что вы получаете IP Zuul, а не localhost / 127.0.0.1, и используете встроенный Tomcat без установленного <Valve className="org.apache.catalina.valves.RemoteIpValve" />. Кроме того, включите журнал доступа для Tomcat, чтобы узнать, какой IP-адрес влияет на ваш сервис, через свойства загрузки SPring, расположенные по адресу https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html - просто найдите tomcat

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...