配置中有一点变化spring-boot1.x
security.basic.enabled=true security.user.name=admin security.user.password=admin
而在spring-boot2.x改为
spring: security: user: name: test # 定义用户名 password: 123456 # 定义密码
eureka.client.serviceUrl.defaultZone改为http://${spring.security.user.name}:${spring.security.user.password}@${eureka.instance.hostname}:${server.port}/eureka/
之后新建一个配置类
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; import org.springframework.security.config.http.SessionCreationPolicy; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER); //关闭csrf http.csrf().disable(); //注意:为了可以使用 http://${user}:${password}@${host}:${port}/eureka/ 这种方式登录,所以必须是httpBasic,如果是form方式,不能使用url格式登录 //开启认证 http.authorizeRequests().anyRequest().authenticated().and().httpBasic(); } }