springcloud认证security
上一篇:eureka server 集群
下一篇:使用Feign 实现声名式 REST调用
为Eureka Server 添加用户认证在前面的示例中, Eureka Server 是允许匿名访问的, 之前访问服务发现组件的时候不需要密码就能登录了,dubbo还需要密码的,这不需要,是不是感觉不安全。今天学习给服务组件加上认证security
eureka server 认证
1 pom.xml
在服务组件项目中的pom.xml 中添加s pring-boot-starter-security的依赖,该依赖为 Eureka Server 提供用户认证的能力。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2在 application.yml 中添加以下内容:
spring:
security:
user:
name: root
password: root
这样就为 Eureka Server 添加了基于HTTP basic 的认证。如果不设置这段内容 ,账号默认是 user , 密码是一个随机值, 该值会在启动时打印出来。
3创建一个配置文件类,开启认证功能
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;
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable(); //关闭csrf
super.configure(http); //开启认证
}
}
4 将微服务注册到需认证的Eureka Server
defaultZone: http://root:root@localhost:8761/eureka/
最后application.yml的内容如下:
# 指定该Eureka实例的端口
# enableSelfPreservation是否启动自我保护机制
#server:
# port: 8761
# enableSelfPreservation: true
#eureka:
# client:
# service-url:
# defaultZone: http://localhost:8761/eureka/
# register-with-eureka: false
# fetch-registry: false
spring:
application:
name: discovery-eureka
profiles:
active: peer2
---
spring:
profiles: peer1
security:
user:
name: root
password: root
server:
port: 8761
eureka:
client:
registry-fetch-interval-seconds: 30
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://root:root@peer2:8762/eureka/
---
spring:
profiles: peer2
security:
user:
name: root
password: root
server:
port: 8762
eureka:
client:
fetch-registry: true
register-with-eureka: true
service-url:
defaultZone: http://root:root@peer1:8761/eureka/
提供者和消费者项目中的配置
provider(提供者)项目和consumer(消费者)项目中的配置文件也需要加入相关的配置信息
eureka:
client:
service-url:
defaultZone: http://root:root@peer1:8761/eureka/,http://root:root@peer2:8762/eureka/
instance:
prefer-ip-address: true
这样消费者和服务者就可以注册到服务组件上了。
测试
上篇文章已经详细的介绍过了,所以就不唠叨了。
再访问服务组件:http://peer2:8762
会让你输入用户名和密码如下图:
如果你在服务组件项目的配置文件中没有配置如图所示:
那密码就是你启动的时候随机生成的密码
如果配置过了就是你配置文件中的密码
这样认证security就配置完成了