在網絡世界中,任何網絡中的服務都是不安全的,爲了使咱們的 Eureka 服務更加安全,咱們能夠添加各類各樣的認證方式,以使客戶端在提供相應的證實以後纔可以註冊到 Eureka 中。而此次咱們就添加一個最基本的 Http Basic 認證到 Eureka 中。 HTTP Basic 是簡單的用戶名密碼認證,客戶端在發送註冊請求時,會附帶用戶名和密碼一塊兒發送到 Eureka Server,這種傳輸方式也屬於不太安全的一種。java
Gitee碼雲git
打開遠程 git 倉庫中的 eureka-server.yml
文件,添加以下配置:web
--- spring: profiles: peer1 security: user: name: test password: 123456 roles: USER server: port: 8761 eureka: instance: hostname: peer1 client: register-with-eureka: false fetch-registry: false # serviceUrl: # defaultZone: http://peer2:8762/eureka ---
爲了簡化服務註冊,咱們此次測試只使用 peer1 這個 profile,而且把 register-with-eureka
和 fetch-registry
設置爲了 false 以關閉自身註冊。而後咱們在 spring
下配置了 security.user.name
,password
, roles
,分別用來指定能夠登陸的用戶名,密碼,和用戶組。spring
在咱們的 registry 項目中建立一個 Java 類 cn.zxuqian.configurations.WebSecurityConfig
,並添加以下代碼:安全
@Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private static Logger log = LoggerFactory.getLogger(WebSecurityConfig.class); @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable().httpBasic(); } @Bean public UserDetailsService userDetailsService() { User.UserBuilder builder = User.withDefaultPasswordEncoder(); InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); manager.createUser(builder.username("test").password("123456").roles("USER").build()); return manager; } }
這裏覆蓋了 WebSecurityConfigurerAdapter
中的 configure() 方法,用來停用 CSRF 保護,由於咱們的 Eureka Server 使用了 peer
作爲 hostname,而稍後測試的 product-service
使用了 localhost
,會被禁止訪問 Eureka 資源。而後在 userDetailsService()
方法中添加了一個 test
用戶用於認證。網絡
打開遠程 git 倉庫中的 product-service.yml
文件,添加以下配置:curl
eureka: client: serviceUrl: defaultZone: http://test:123456@peer1:8761/eureka/
這裏在 defaultZone
指定的 Url 中添加了 [username]:[password]@host:port/eureka/
形式的地址,此爲 curl 發送用戶名和密碼的方式。ide
首先運行 Config Server,而後使用 mvn spring-boot:run -Dspring-boot.run.profiles=peer1
運行 Eureka Server,最後運行 product-service
,稍等片刻就會看到 product-service
註冊成功,而 Eureka Server
的 log 中會有以下字樣(需設置 log level 爲 debug):spring-boot
2018-05-19 18:16:45.278 DEBUG 19055 --- [nio-8761-exec-9] w.c.HttpSessionSecurityContextRepository : Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: 'org.springframework.security.core.context.SecurityContextImpl@442bd3dc: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@442bd3dc: Principal: org.springframework.security.core.userdetails.User@364492: Username: test; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_USER'
歡迎訪問個人博客:http://zxuqian.cn/測試