1.添加依賴:
在server和client的依賴文件中增加依賴:spring-boot-starter-security
2.修改配置文件:
2.1修改server的配置文件
注意:在新版本中沒有basic:enabled: true這個配置屬性
spring: application: name: eureka-server security: user: name: admin password: 123
server配置defaultZone改為:
defaultZone: http://${security.user.name}:${security.user.password}@${eureka.instance.hostname}:${server.port}/eureka/
2.2修改client的配置文件
defaultZone: http:admin:123@//localhost:8761/eureka/
3.增加WebSecurityConfig配置類
eureka服務添加security驗證之后,client注冊失敗:cannot execute any request on any know server
是因為新版本的security默認開啟csrf了,關掉就好了,新建一個配置類。
package com.forezp; import org.springframework.context.annotation.Configuration; 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 @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.authorizeRequests().anyRequest().authenticated().and().httpBasic(); //開啟認證 } }