Spring Cloud 学习之Eureka(1) —— 单机模式
Spring Cloud 学习之Eureka(2) —— 集群模式
上一篇我们完成了集群化部署,一般来说,注册中心基本就到此结束了,但是Eureka Server和Eureka Client之间是通过http方式来维护心跳的,所以可能被抓取到资源包,从而冒充请求,非法访问注册中心,所以我们需要对注册中心加入安全策略,这里我用的是Spring Security这个安全框架,虽然这个框架非常笨重,但是结合springboot后,使用非常方便,所以我们就用它来实现安全策略。
首先在pom文件中引入Spring Security的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
然后创建Security的配置文件,我们这里拦截所有请求:
package com.maochd.springcloud.eureka.service.config;
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;
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.NEVER)
.and()
.csrf()
.disable()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic();
}
}
接下来我们在yml文件中创建账户,我创建了一个maochd的用户:
server:
port: 28080
spring:
application:
name: maochd-eureka-server
security:
user:
name: maochd
password: maochd
roles: SERVICE_NODE
eureka:
instance:
hostname: maochd-eureka-server1
client:
service-url:
defaultZone: http://maochd-eureka-server2:28081/eureka
# fetch-registry: false
# register-with-eureka: false
由于引入的安全框架,所以我们需要在注册中心的路径上配置上用户名密码,例如
## example http://username:password@hostname:port/eureka
http://maochd:maochd@maochd-eureka-server2:28082/eureka/
这样我们就跟集群化时是一样的了,接下来我们启动注册中心,访问注册中心控制台,这时候会跳出登录表单,说明安全框架生效了,我们输入新创建的账号,即可正常进入:
接下来我们把所有的defaultZone都加上用户名密码,就可实现安全控制了。
按照集群化部署的方式启动,等所有服务都成功运行后,刷新注册中心,便可看到所有服务已经被注册了:
如果不加用户名,服务就会报错:
然后我们访问一下接口:
发现引入安全策略并不影响接口调用,只是保证了注册中心的安全。