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(); //开启认证 } }