为Eureka添加用户认证
前言
登录即可访问到Eureka服务,这样其实是不安全的。接下来,我们为Eureka添加用户认证。
第一步,为Eureka服务端(eureka-server)添加安全认证依赖
在eureka-server的pom文件中添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
第二步,增加application.yml配置文件:
server:
port: 8888
eureka:
instance:
hostname: localhost
client:
###是否将自己注册到Eureka服务中,因为该应用本身就是注册中心,不需要再注册自己(集群的时候为true)
register-with-eureka: false
###是否从Eureka中获取注册信息,因为自己为注册中心,不会在该应用中的检索服务信息
fetch-registry: false
###客户端调用地址
serviceUrl:
defaultZone: http://${spring.security.user.name}:${spring.security.user.password}@${eureka.instance.hostname}:${server.port}/eureka/
#注意这里不要换行
spring:
security:
basic:
enable: true
#开启基于HTTP basic的认证
user:
#配置用户的账号信息
name: oy
password: 123456
第三步,在eurka服务端添加一个安全认证类:
package com.oy.eureka;
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;
import org.springframework.security.config.http.SessionCreationPolicy;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 高版本springcloud的丢弃了配置:
*
* security:
* basic:
* enabled: true
*
* 所以应该使用以下方式开启
*
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
// Configure HttpSecurity as needed (e.g. enable http basic).
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
http.csrf().disable();
//注意:为了可以使用 http://${user}:${password}@${host}:${port}/eureka/ 这种方式登录,所以必须是httpBasic,
// 如果是form方式,不能使用url格式登录
http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
}
}
第四步,重新启动Eureka服务进行测试:
输入正确的用户名密码即可登录。
这时,服务提供者(product,order)注册到Eureka时会报错:
2020-11-04 05:49:28.772 WARN 12528 --- [nfoReplicator-0] c.n.d.s.t.d.RetryableEurekaHttpClient : Request execution failed with message: java.net.ConnectException: Connection refused: connect
2020-11-04 05:49:28.772 WARN 12528 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient : DiscoveryClient_UNKNOWN/192.168.182.1:8888 - registration failed Cannot execute request on any known server
com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server
第五步,服务注册时(client端)设置账户信息
服务注册到有认证需求的注册中心时,需要设置如下地址:
http://USER:PASSWORD@127.0.0.1:端口号/eureka/
配置如下(至此,Eureka注册中心、product服务、order服务3个配置文件全部改成了带账号密码的请求地址):
eureka:
client:
service-url:
defaultZone: http://oy:123456@127.0.0.1:8888/eureka