前面介紹了【搭建服務注冊中心】以及【搭建高可用服務注冊中心】,如果對搭建服務注冊中心還不熟悉的小伙伴可以看一下前面兩篇。
之前搭建的服務注冊中心,只需要輸入地址和端口就能注冊了,這如果是生產環境是非常不安全的,我只要知道你的注冊中心地址,我是不是可以直接注冊服務上去,以及獲取你注冊中心的服務了。所以這篇文章介紹一下給注冊中心搭建一個用戶認證。
依然使用前面搭建的eureka-server-test這個項目進行改造,為了方便測試,這里就使用單節點的服務注冊中心了。
添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
修改配置文件
這里配置文件從.properties 改成了 .yml,感覺還是yml格式看着舒服一些。
其中 eureka.client.serviceUrl做了修改,添加了spring.security的用戶名和密碼,舊版本中開啟認證的security.basic.enabled=true已經無效。
server:
port: 8081
waitTimeInMsWhenSyncEmpty: 0
enableSelfPreservation: false
eureka:
instance:
hostname: localhost
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${spring.security.user.name}:${spring.security.user.password}@${eureka.instance.hostname}:${server.port}/eureka/
spring:
security:
user:
name: admin
password: 123456
添加啟動文件
在spring boot 2.0.3中,默認開啟了csrf的認證,我們這里手動進行關閉,然后開啟httpBasic的認證,這個和以前版本中配置文件security.basic.enabled=true的作用類似。
package clarezhou.example.common;
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;
/**
* @author clarezhou
* @date 2019/6/25 10:31
**/
@EnableWebSecurity
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//開啟認證
//為了可以使用 http://${user}:${password}@${host}:${port}/eureka/ 這種方式登錄,所以必須是httpBasic
http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().httpBasic();
}
}
Eureka Server 服務注冊中心就改造完了,然后啟動服務,在瀏覽器中輸入注冊中心地址,會看到如下彈框。
輸入賬號,密碼就能進入注冊中心了。
改造客戶端
客戶端也使用之前創建的 eureka-client-test這個項目進行改造,這里只需要修改一下配置文件,修改serviceUrl.defaultZone
的地址,在原來的地址前面加上用戶名:密碼@這些信息。
eureka.client.serviceUrl.defaultZone=http://admin:123456@localhost:8081/eureka/
然后啟動客戶端,看到注冊信息就OK了。