前面介绍了【搭建服务注册中心】以及【搭建高可用服务注册中心】,如果对搭建服务注册中心还不熟悉的小伙伴可以看一下前面两篇。
之前搭建的服务注册中心,只需要输入地址和端口就能注册了,这如果是生产环境是非常不安全的,我只要知道你的注册中心地址,我是不是可以直接注册服务上去,以及获取你注册中心的服务了。所以这篇文章介绍一下给注册中心搭建一个用户认证。
依然使用前面搭建的eureka-server-test这个项目进行改造,为了方便测试,这里就使用单节点的服务注册中心了。
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
修改配置文件
这里配置文件从.properties 改成了 .yml,感觉还是yml格式看着舒服一些。
其中 eureka.client.serviceUrl做了修改,添加了spring.security的用户名和密码,旧版本中开启认证的security.basic.enabled=true已经无效。
server:
port: 8081
waitTimeInMsWhenSyncEmpty: 0
enableSelfPreservation: false
eureka:
instance:
hostname: localhost
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${spring.security.user.name}:${spring.security.user.password}@${eureka.instance.hostname}:${server.port}/eureka/
spring:
security:
user:
name: admin
password: 123456
添加启动文件
在spring boot 2.0.3中,默认开启了csrf的认证,我们这里手动进行关闭,然后开启httpBasic的认证,这个和以前版本中配置文件security.basic.enabled=true的作用类似。
package clarezhou.example.common;
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 clarezhou
* @date 2019/6/25 10:31
**/
@EnableWebSecurity
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//开启认证
//为了可以使用 http://${user}:${password}@${host}:${port}/eureka/ 这种方式登录,所以必须是httpBasic
http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().httpBasic();
}
}
Eureka Server 服务注册中心就改造完了,然后启动服务,在浏览器中输入注册中心地址,会看到如下弹框。
输入账号,密码就能进入注册中心了。
改造客户端
客户端也使用之前创建的 eureka-client-test这个项目进行改造,这里只需要修改一下配置文件,修改serviceUrl.defaultZone
的地址,在原来的地址前面加上用户名:密码@这些信息。
eureka.client.serviceUrl.defaultZone=http://admin:123456@localhost:8081/eureka/
然后启动客户端,看到注册信息就OK了。