此处客户端是指需要被 Spring Boot Admin 监控的服务
- 引入 actuator 依赖:
org.springframework.boot spring-boot-starter-actuator
- 开放所有监控端点:
management: endpoints: web: exposure: include: "*" endpoint: health: show-details: always
- 开放所有端点有很大的风险性,所以必须引入安全认证框架,引入 spring security :
org.springframework.boot spring-boot-starter-security
- 微服务的业务接口不需要做安全认证,所以添加配置类,放行 actuator 外的其他接口:
@Configuration public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity.httpBasic() .and() .authorizeRequests() .antMatchers("/actuator/**").authenticated() .anyRequest().permitAll() .and() .csrf().disable(); } }
- 引入安全认证后,管理端将同样无法访问监控端点,所以客户端需要将账号密码等元数据注册到注册中心:
spring: security: user: name: jj8&Ujd password: df97jmgi73m@*&^234 cloud: nacos: discovery: metadata: user.name: ${spring.security.user.name} user.password: ${spring.security.user.password}管理端
- 引入依赖:
de.codecentric spring-boot-admin-starter-server
完整的依赖如下(使用 nacos 注册中心,引入安全框架):
org.springframework.boot spring-boot-starter-webcom.alibaba.cloud spring-cloud-starter-alibaba-nacos-discoveryde.codecentric spring-boot-admin-starter-serverorg.springframework.boot spring-boot-starter-mailorg.springframework.boot spring-boot-starter-security
- 添加配置类,开启密码登录:
@Configuration public class AdminSecurityConfig extends WebSecurityConfigurerAdapter { private final String adminContextPath; public AdminSecurityConfig(AdminServerProperties adminServerProperties) { this.adminContextPath = adminServerProperties.getContextPath(); } @Override protected void configure(HttpSecurity http) throws Exception { SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler(); successHandler.setTargetUrlParameter("redirectTo"); successHandler.setDefaultTargetUrl(adminContextPath + "/"); http.authorizeRequests() //1.配置所有静态资源和登录页可以公开访问 .antMatchers(adminContextPath + "/assets/**").permitAll() .antMatchers(adminContextPath + "/login").permitAll() .anyRequest().authenticated() //2.配置登录和登出路径 .and() .formLogin().loginPage(adminContextPath + "/login").successHandler(successHandler) .and() .logout().logoutUrl(adminContextPath + "/logout") //3.开启http basic支持,admin-client注册时需要使用 .and() .httpBasic() //4.开启基于cookie的csrf保护 .and() .csrf() .csrfTokenRepository(cookieCsrfTokenRepository.withHttpOnlyFalse()) //5.忽略这些路径的csrf保护以便admin-client注册 .ignoringAntMatchers( adminContextPath + "/instances", adminContextPath + "/actuator/**" ); } }
- 配置账号密码,并忽略管理端:
spring: security: user: name: admin password: m@#54$fdsG$D boot: # 不显示admin-security-server的监控信息 admin: discovery: ignored-services: ${spring.application.name}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)