pom.xml
引入 spring-cloud-starter-security
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
</dependency>
application.yml
配置 name & password
server:
port: 7901
eureka:
instance:
hostname: eureka-7901
client:
service-url:
defaultZone: http://eureka-7901:7901/eureka/
#是否将自己注册到 Eureka Server,默认为 true,由于当前就是 server,故而设置成 false
register-with-eureka: false
#是否从 eureka server 获取注册信息,由于单节点,不需要同步其他节点数据,故而设置成 false
fetch-registry: false
server:
#关闭自我保护
enable-self-preservation: false
spring:
security:
user:
name: admin
password: admin
重启 eureka server 打开 http://127.0.0.1:7901/login
关闭防止跨域攻击
如果服务报错
Root name 'timestamp' does not match expected ('instance') for type
是默认开启了防止跨域攻击,手动关闭即可。
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;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// TODO Auto-generated method stub
http.csrf().disable();
super.configure(http);
}
}
配置 provider
provider 配置 defaultZone 时,需要加上 name:password@
如 defaultZone: http://admin:admin@eureka-7901:7901/eureka/ 中 eureka-7901:7901/eureka/ 前的 admin:admin@
eureka:
client:
healthcheck:
#可以上报服务的真实健康状态
enabled: true
service-url:
defaultZone: http://admin:admin@eureka-7901:7901/eureka/