引入依赖

<!--安全认证-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

配置文件,其中集群中互相注册的url要加上用户名和密码,http://root:root@eureka1:8761/eureka/

server:
  port: 8762
spring:
  security:
    user:
      name: root
      password: root
eureka:
  instance:
    hostname: eureka2
    prefer-ip-address: true     #是否使用ip地址注册
    instance-id: ${spring.cloud.client.ip-address}:${server.port}   #显示ip:port
  client:
#    register-with-eureka: true
#    fetch-registry: true
    service-url:
      defaultZone: http://root:root@eureka1:8761/eureka/
  server:
    enable-self-preservation: false     #关闭保护机制,以确保注册中心可以将不可用的实例剔除

当然,注册中心此时会被拦截的,是相互注册不上的

我们要做放行或者关闭csrf防护

方式一,要加上@EnableWebSecurity注解

package com.qiangqiang.config;

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;

/**
 * \* Created with IntelliJ IDEA.
 * \* @author: xiyue
 * \* Date: 2020/12/24
 * \* Time: 13:55
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //用户登录配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        //忽略这个请求
        http.csrf().ignoringAntMatchers("/eureka/**");
    }
}

方式二,要加上@EnableWebSecurity注解

package com.qiangqiang.config;

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;

/**
 * \* Created with IntelliJ IDEA.
 * \* @author: xiyue
 * \* Date: 2020/12/24
 * \* Time: 13:55
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //用户登录配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        //关闭csrf防护
        http.csrf().disable();
    }
}
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐