spring boot版本2.0.3
pom依赖:
<!-- 开启密码访问 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
application.yml:添加配置
spring:
security:
user:
#你的用户名
name: ypp
#你的密码
password: admin
roles:
- user
roles是个String数组,可以选择user,可不选.也可以配置其他用户角色的密码
还有ypp admin user这些信息后面不要加注释,spring不会报错,但是登录不了的(亲自尝试),注释可以放在上面,不要跟在后面
访问eureka界面
输入密码后,登录成功
然后会发现其他路径访问不了的,比如向eureka注册服务,注册不进来。那是因为springboot在这个版本默认开启了CSRF攻击防御,2.x其他版本很多也会存在此问题。网上的解决办法是禁用CSRF防御,禁用之后部分版本会出现在登录eureka界面的时候又没有安全登录验证了,要注册服务禁用/eureka即可,而不是直接禁用CSRF
package com.chwl.cn;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
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;
@SpringBootApplication
@EnableEurekaServer // 告诉springcloud我是EurekaServer端,接受其他服务可以进来
public class EurekaServerApplication2001 {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication2001.class, args);
}
@Configuration
@EnableWebSecurity
static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// // Spring Security 默认开启了所有 CSRF 攻击防御,需要禁用 /eureka 的防御
http.csrf().ignoringAntMatchers("/eureka/**");
//访问eureka控制台和/actuator时能做安全控制
super.configure(http);
// http.csrf().disable();//禁用CSRF
// http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
}
}
}
服务注册加上用户名和密码:
eureka:
client:
#register-with-eureka: false
service-url:
defaultZone: http://ypp:[email protected]:2002/eureka/,http://ypp:[email protected]:2001/eureka/ #eureka开启密码,在eureka server配置
instance:
instance-id: consumer
prefer-ip-address: true