关于eureka注册中心的搭建可以参考我的这篇博客-> 零基础也能学会的SpringCloud教程(一): eureka注册中心的搭建
1.在eureka相关项目下的pom.xml文件里添加相关的依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2.IDEA运行eureka注册中心,浏览器输入访问地址:“http://localhost:10086”,其中10086为自己设定的端口号,弹出登录页面,用户名默认为user,密码会在IDEA控制台随机生成。
3.输入用户名和密码,点击“Sign in”登录,之后成功进入监控中心的图形化界面。
4.你可以修改application.yml文件,设置自定义用户名和密码,注册中心地址也要随之改变
# 配置端口号
server:
port: 10086
# 微服务的名称 - 注册中心本身就是一个微服务
spring:
application:
name: guqueyeu-eureka
# 自定义的用户名和密码
security:
user:
name: guqueyue
password: guqueyue
eureka:
client:
# 注册中心的地址 - 若设置了访问密码,注册中心地址也要随之改变
service-url:
defaultZone: http://guqueyue:guqueyue@localhost:10086/eureka
# 当前微服务是否可以调用其他微服务,默认为true
fetch-registry: false
# 当前的微服务是否注册到eureka上,默认为true
register-with-eureka: false
5.重新启动项目,输入自定义的用户名和密码,成功访问!
6.接下来我们需要再创建一个类如“EurekaConfig”进行相应的配置,原因如下:
当你使用密码后,若使用高版本的SpringBoot时,会有一个防攻击,即出现跨域问题(路由网关不在一个机器也不是一个端口)时,会出现禁止注册现象,所以要将其关闭。
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;
/**
* @author guqueyue
* @Date 2020/3/30
**/
@EnableWebSecurity
public class EurekaConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable() // 禁止掉csrf跨域攻击,以免服务无法注册
.authorizeRequests() // 设置需要认证所有请求
.mvcMatchers("/eureka/**").permitAll() // 符合设置路径规则的放行
.anyRequest().authenticated().and().httpBasic(); // 剩余所有请求都需要认证
}
}