Eureka Server添加安全认证

配置注册中心的Maven的pom文件

<!--设置登录密码需要用到Spring Security-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

配置注册中心的application.yml

server:
  port: 8761
  
#设置eurekaServer的登录密码
spring:
  security:
    user:
      name: admin  # 用户名
      password: admin   # 用户密码

eureka:
  instance:
    hostname: localhost
  client:
    registerWithEureka: false #不向eurekaServer注册   因为自己就是server
    fetchRegistry: false      #不获取注册中心的服务     因为自己就是server
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/   #服务注册中心的位置

注册中心关闭Spring Security的CSRF验证, 如果不关闭,那么客户端就连接不上

package com.wind.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;

/**
 1. 如果eurekaServer设置了登录密码   就必须关闭Spring Security的CSRF验证
 */
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable(); //关闭csrf
        super.configure(http);
    }
}

配置Client的application.yml

server:
    port: 8762

spring:
    application:
        name: eureka-client   #配置在eurekaServer中注册的名字

eureka:
    instance:
        prefer-ip-address: true   #在eurekaServer中服务地址以ip显示
    client:
        serviceUrl:
            #defaultZone: http://localhost:8761/eureka/   #设置eurekaServer的uri
            defaultZone: http://admin:admin@localhost:8761/eureka/    #eurekaServer设置了登录验证

此时就大功告成了

作者:windFuturte
来源:CSDN
原文:https://blog.csdn.net/qq_35881988/article/details/85274318
版权声明:本文为博主原创文章,转载请附上博文链接!

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享