Spring 2為Eureka server新增使用者認證
阿新 • • 發佈:2018-12-20
專案基礎:
1、微服務建立:https://blog.csdn.net/m_sophia/article/details/80867514
2、服務註冊:https://blog.csdn.net/m_sophia/article/details/80867712
使用者認證:
1、在microservice-discovery-eureka專案的pom.xml中增加security依賴。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> <version>2.0.3.RELEASE</version> </dependency>
儘量增加版本號
2、配置application.yml檔案
原先配置:
security:
baisc:
enabled: true
user:
name: nsk
password: abcd1234
在2.0.3版本中,沒有security屬性,並移到了spring屬性中,並且basic.enabled無效。
現有配置:
spring: application: name: microservice-discovery-eureka security: user:name: nsk password: abcd1234 server: port: 8764 eureka: client: register-with-eureka: false fetch-registry: false service-url: defaultZone: http://nsk:[email protected]:8764/eureka/
3、修改專案啟動檔案。
錯誤配置:
此時會去掉使用者認證。@EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); } }
現有配置:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().httpBasic();
}
}
4、執行專案,在瀏覽器中輸入:localhost:8764/,出現使用者認證視窗
5、註冊微服務到需要認證的Eureka Server
修改defaultZone的值
eureka:
client:
service-url:
defaultZone: http://nsk:[email protected]:8764/eureka/ # nsk為使用者名稱,abcd1234為密碼
6、此時可以在認證後的Eureka server中檢視註冊的微服務