Eureka進行安全控制,通過用戶名密碼來注冊到注冊中心


首先導入maven依賴

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
</dependency>
然后在配置文件中添加
spring:
  application:
    name: eureka-server
  security:
    user:
      name: admin
      password: 123456
此時啟動注冊中心就需要輸入賬號密碼登錄了
 
修改EurekaClient配置
eureka:
  instance:
    prefer-ip-address: true
  client:
    serviceUrl:
      defaultZone: http://admin:123456@localhost:8761/eureka/
如果不配置用戶名和密碼,會報401錯誤
Request execution failure with status code 401; retrying on another server if available
配置上以后還會報錯
Request execution failure with status code 403; retrying on another server if available
這是因為Eureka 默認啟用了csrf檢驗,可以將其disable掉
Eureka注冊中心添加如下代碼:
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableWebSecurity
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        super.configure(http);
    }
}
重啟注冊中心,就會發現服務注冊上來了
但是注冊中心日志還會報錯
Batch update failure with HTTP status code 401; discarding 1 replication tasks
這是因為在eureka注冊中心啟用了security安全機制,因此在進行配置defualtZone時也要設置下相關用戶名和密碼,配置如下:
eureka:
  instance:
    prefer-ip-address: true
  client:
    registerWithEureka: false
    fetchRegistry: false
    server:
      waitTimeInMsWhenSyncEmpty: 0
    service-url:
      defaultZone: http://${spring.security.user.name}:${spring.security.user.password}@localhost:8761/eureka/
注冊中心整體配置如下:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM