Spring Cloud学习笔记(三) Eureka安全配置

1 为Eureka Server配置HttpBasic验证

为了保证服务的安全性,我们为EurekaServer配置HttpBasic验证,只有知道用户名和密码的服务才能注册到Eureka Server。接下来我们基于之前的项目代码,来改造配置一下这部分相关内容。

在项目中引入依赖

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
</dependency>

在Eureka Server配置文件中加入用户名和密码相关配置

spring:  
  security:
    user:
      name: username
      password: password

访问Eureka Server UI

输入用户名和密码,可以登录

2 配置Eureka Client注册服务

修改Service-Provider服务的配置文件,在地址前加入用户名和密码,启动服务。

eureka:
  client:
    serviceUrl:
      defaultZone: http://username:password@eureka-server-peer1:8100/eureka 

服务报403的错误

Request execution failure with status code 403; retrying on another server if available

查看官方文档,发现下面一段话

By default when Spring Security is on the classpath it will require that a valid CSRF token be sent with every request to the app. Eureka clients will not generally possess a valid cross site request forgery (CSRF) token you will need to disable this requirement for the /eureka/** endpoints

大概意思就是我们的Eureka Server加入了spring-boot-starter-security依赖之后,默认情况下,所有发送给Eureka Server的请求都必须带上CSRF Token,那么我们关闭这个验证就可以了,加入WebSecurityConfig,关闭此项验证。

package org.dothwinds.eurekaserver;

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 httpSecurity) throws Exception {
        httpSecurity.csrf().disable();
        super.configure(httpSecurity);
    }
}

然后启动服务,发现没有报错,进入Eureka Server UI查看服务已经注册成功了:)

参考资料:

https://cloud.spring.io/spring-cloud-static/Greenwich.SR5/single/spring-cloud.html#spring-cloud-eureka-server

https://cloud.spring.io/spring-cloud-static/Greenwich.SR5/single/spring-cloud.html#_service_discovery_eureka_clients

代码:https://gitee.com/dothwinds/Spring-Cloud-Study/tree/master/spring-cloud-study-eureka

发布了18 篇原创文章 · 获赞 33 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Dothwinds/article/details/104985105