本文共 2733 字,大约阅读时间需要 9 分钟。
使用 SpringCloud 微服务,包括我们的服务消费者、服务提供者,在跟我们的服务注册中心注册时,需要增加验证。
我们使用 SpringSecurity 进行安全验证。
在项目 pom.xml 增加 security 依赖(注册中心和微服务都要添加)
org.springframework.boot spring-boot-starter-security
添加之后,就默认有用户名、密码的配置了。
在 Eureka 注册中心的配置文件增加以下配置:
spring: application: name: eureka-server # 注册中心安全验证 security: user: name: biandan password: 123456
添加之后,Eureka 注册中心服务认证就配置好了。
像之前这种: 就是没有添加安全认证的。这种做法非常不好,容易被攻击。
我们需要在消费者和服务提供者的微服务里增加用户名和密码。语法:http://用户名:密码@注册中心地址
eureka: instance: hostname: 127.0.0.1 client: serviceUrl: defaultZone: http://biandan:123456@127.0.0.1:8080/eureka/
或者:
spring: application: name: feign-servereureka: instance: hostname: 127.0.0.1 client: serviceUrl: defaultZone: http://biandan:123456@${eureka.instance.hostname}:8080/eureka/
如果注册中心做集群,也要把认证加上。比如两个注册中心要相互认证,是需要安全认证的。
然后启动我们的注册中心,访问:
这时候,我们的消费者的服务还不能正常的注册到注册中心 Eureka 。因为 Eureka 自动配置了 CSRF 防御机制。
Eureka 会自动化配置 CSRF 防御机制,SpringSecurity 认为 POST、PUT、DELETE 等都是有风险的。如果这些方法发送过程中没有带上 CSRF token 的话,会被拦截 403 的错误。
在注册中心的服务增加配置类:
package com.study.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;/** * @author biandan * @description 安全认证配置类 * @signature 让天下没有难写的代码 * @create 2021-06-21 上午 12:44 */@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity httpSecurity)throws Exception{ super.configure(httpSecurity); //忽略所有 /eureka/** 的请求 httpSecurity.csrf().ignoringAntMatchers("/eureka/**"); } }
可以看到微服务可以注册到注册中心了
在注册中心的服务增加配置类:
package com.study.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;/** * @author biandan * @description 安全认证配置类 * @signature 让天下没有难写的代码 * @create 2021-06-21 上午 12:44 */@EnableWebSecuritypublic class WebSecurityConfig2 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity httpSecurity)throws Exception{ //注意:如果直接 disable 的话会把安全验证也禁用掉 httpSecurity.csrf().disable().authorizeRequests() .anyRequest() .authenticated() .and() .httpBasic(); }}
OK,添加了 Eureka 安全认证,让你的微服务不在【裸奔】!
转载地址:http://bkuhf.baihongyu.com/