欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Eureka Server 增加安全用户认证 博客分类: spring boot 实践笔记 spring cloudeureka serversecurity

程序员文章站 2024-03-13 18:53:39
...

环境:spring cloud Finchley.RC2,spring boot 2.0.2.RELEASE,eureka 1.9.0

 

1. pom 文件中引入依赖

     添加spring-security支持: 

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

 

2. application.yml 文件增加管理的用户名密码配置

 

   2.1 增加 spring.security 配置

spring:
  security:
    basic:
      enabled: true
    user:
      name: admin
      password: admin123456

 

   2.2 eureka.client.serviceUrl.defaultZone 修改,增加账号密码

http://${spring.security.user.name}:${spring.security.user.password}@${eureka.instance.hostname}:${server.port}/eureka/

    

   2.3 修改后Eureka Server 的完整的 application.yml 为:

server:
  port: 8082

spring:
  security:
    basic:
      enabled: true
    user:
      name: admin
      password: admin123456

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/

 

3. Eureka Server端关闭security的csrf检验

    新版的security默认启用了csrf检验,如果不关闭该检验,eureka client端向eureka server注册时,会报如下异常:com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server,由于还没研究在启用csrf检验的情况下,eureka client注册服务时如何避免该异常,考虑先关闭csrf检验:

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
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        super.configure(http);
    }
}

 

4.eureka client端eureka.client.serviceUrl.defaultZone 修改,增加账号密码

http://${security.username}:${security.password}@localhost:8082/eureka/

    增加配置: 

    security.username=admin   

    security.password=admin123456