1. 程式人生 > >consul 微服務使用SpringSecurityOAuth2 authorization_code 模式遇到的坑

consul 微服務使用SpringSecurityOAuth2 authorization_code 模式遇到的坑

這是開始的服務註冊程式碼塊 bootstrap.yml:

spring:
  cloud:
    consul:
      port: 8500
      host: localhost
      discovery:
        serviceName: auth
        locator:
          lower-case-service-id: true
          enabled: true
        register: true

這是註冊完後的健康檢查

他會把你的主機地址給註冊上來。 平時使用可能沒問題,但是 當做OAuth2的 authorization_code 模式認證的時候,會出現跨域異常情況如下:

這是請求路徑:

http://localhost:8001/auth/oauth/authorize?response_type=code&client_id=client_name&redirect_uri=http://localhost:8001/auth/callback&scope=auth

訪問後跳轉到預設的登入介面:

仔細看,url位置訪問地址變成了之前註冊的主機名 從而導致的結果就是,點選登入介面出現下圖:

沒有許可權 返回401。 問題就出在了,跳轉回主機名導致了跨域問題。

解決該問題的措施就是修改開始的bootstrap.yml的檔案:

spring:
  cloud:
    consul:
      port: 8500
      host: localhost
      discovery:
        serviceName: auth
        locator:
          lower-case-service-id: true
          enabled: true
        register: true
        prefer-ip-address: true #這個必須配
        tags: version=1.0
        instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}
        healthCheckInterval: 15s
        health-check-url: http://${spring.cloud.client.ip-address}:${server.port}/actuator/health

consul註冊增加強制限制 prefer-ip-address:true 強制獲取ip的方