【Spring Boot Admin】使用(整合Spring Security服务,添加鉴权)

Spring Boot Admin 监控平台

背景:Spring Boot Admin 监控平台不添加鉴权就直接访问的话,是非常不安全的。所以在生产环境中使用时,需要添加鉴权,只有通过鉴权后才能监控客户端服务。本文整合Spring Security进行实现。
pom依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-server</artifactId>
            <version>2.6.11</version>
        </dependency>
        <!--alibaba-nacos-discovery(阿里注册中心discovery)-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
    </dependencies>
    
    <dependencyManagement>
        <dependencies>
            <!--Spring Boot 相关依赖-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-parent</artifactId>
                <version>2.5.3</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--Spring Cloud 相关依赖-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>2020.0.5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--Spring Cloud Alibaba 相关依赖-->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2021.1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

yml配置

server:
  port: 18000

spring:
  application:
    name: admin-server
  security:
    user:
      name: admin
      password: admin
  cloud:
    nacos:
      discovery:
        enabled: true
        server-addr: 127.0.0.1:8848
        group: admin  #指定group
        namespace: public
        service: ${spring.application.name}

启动类@EnableAdminServer

package com.admin;

import de.codecentric.boot.admin.server.config.EnableAdminServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@EnableDiscoveryClient
@EnableAdminServer
@SpringBootApplication
public class AdminServerApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(AdminServerApplication.class,args);
    }
}

安全配置类:SecuritySecureConfig.java

package com.admin.config;

import de.codecentric.boot.admin.server.config.AdminServerProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

@Configuration(proxyBeanMethods = false)
public class SecuritySecureConfig extends WebSecurityConfigurerAdapter {

    private final String adminContextPath;

    public SecuritySecureConfig(AdminServerProperties adminServerProperties) {
        this.adminContextPath = adminServerProperties.getContextPath();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
        successHandler.setTargetUrlParameter( "redirectTo" );

        http.authorizeRequests()
                .antMatchers( adminContextPath + "/assets/**" ).permitAll()
                .antMatchers( adminContextPath + "/login" ).permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage( adminContextPath + "/login" ).successHandler( successHandler ).and()
                .logout().logoutUrl( adminContextPath + "/logout" ).and()
                .httpBasic().and()
                .csrf().disable();
    }
}

服务启动成功后,访问链接:http://127.0.0.1:18000。需要先进行登录(admin-admin),才能进入控制台页面。
在这里插入图片描述

客户端服务

背景:客户端服务的检查接口(/actuator/**)默认可以直接通过接口调用,是非常不安全的。所以在生产环境中使用时,可添加鉴权功能提升安全性。
pom依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-client</artifactId>
            <version>2.6.11</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.14</version>
            <scope>provided</scope>
        </dependency>
        <!-- alibaba-nacos-discovery(阿里注册中心discovery)-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
    </dependencies>
    
    <dependencyManagement>
        <dependencies>
            <!--Spring Boot 相关依赖-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-parent</artifactId>
                <version>2.5.3</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--Spring Cloud 相关依赖-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>2020.0.5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--Spring Cloud Alibaba 相关依赖-->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2021.1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

yml配置(通过Url注册)

spring:
  security:
    user:
      name: user
      password: user
  application:
    name: admin-order
  # spring boot admin
  boot:
    admin:
      client:
        url: http://127.0.0.1:18000
        username: admin
        password: admin
        instance:
          prefer-ip: true
          name: admin-order
          # 这个name与password用于在注册到管理端时,使管理端有权限获取客户端端点数据
          metadata: 
            user.name: ${spring.security.user.name}
            user.password: ${spring.security.user.password}
server:
  port: 18001
  servlet:
    context-path: /order

#  endpoints config
management:
  endpoints:
    web:
      exposure:
        include: "*"
  endpoint:
    health:
      show-details: always

logging:
  # 只有配置了日志文件,才能被监控收集
  file:
    name: logs/${spring.application.name}/${spring.application.name}.log

yml配置(通过注册中心注册)

spring:
  security:
    user:
      name: user
      password: user
  application:
    name: admin-order
  cloud:
    nacos:
      discovery:
        metadata:
          # 为服务实例添加一个名为“user.name”的元数据项,并将其值设置为指定的服务用户名。这个用户名通常用于进行鉴权,以确保只有授权的用户才能访问该服务。
          user.name: ${spring.security.user.name}
          user.password: ${spring.security.user.password}
          management:
            # 表示Actuator端点的上下文路径。具体地说,这个属性的作用是将Actuator端点的上下文路径设置为${server.servlet.context-path}/actuator
            context-path: ${server.servlet.context-path}/actuator
        enabled: true
        server-addr: 127.0.0.1:8848
        group: admin  #指定group
        namespace: public
        service: ${spring.application.name}

server:
  port: 18001
  servlet:
    context-path: /order

#  endpoints config
management:
  endpoints:
    web:
      exposure:
        include: "*"
  endpoint:
    health:
      show-details: always

logging:
  # 只有配置了日志文件,才能被监控收集
  file:
    name: logs/${spring.application.name}/${spring.application.name}.log

启动类

package com.admin;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@Slf4j
@EnableDiscoveryClient
@SpringBootApplication
public class AdminOrderApp {
    public static void main(String[] args) {
        SpringApplication.run(AdminOrderApp.class, args);
    }
}

服务启动成功后,访问监控平台,就能监控admin-order服务了。

注意:如果监控平台上没有看见客户端服务,则需要重启Spring Boot Admin 监控服务

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot整合Spring Security可以帮助我们实现应用程序的身份验证和授权功能。以下是一个简单的示例代码,演示了如何在Spring Boot项目中使用Spring Security。 首先,我们需要在`pom.xml`中添加Spring Security的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 接下来,在我们的应用程序主类上使用`@EnableWebSecurity`注解启用Spring Security: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; 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 public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasRole("USER") .antMatchers("/**").permitAll() .and() .formLogin(); } } } ``` 在上述代码中,我们定义了一些基本的URL路径和相应的角色要求。例如,`/admin/**`路径需要`ADMIN`角色才能访问,`/user/**`路径需要`USER`角色才能访问,而其他路径允许所有人访问。 最后,我们可以创建一个`UserDetailsService`的实现类来加载用户信息。这里提供一个简单的示例: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private BCryptPasswordEncoder passwordEncoder; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { if ("admin".equals(username)) { return User.builder() .username("admin") .password(passwordEncoder().encode("admin")) .roles("ADMIN") .build(); } else if ("user".equals(username)) { return User.builder() .username("user") .password(passwordEncoder().encode("user")) .roles("USER") .build(); } else { throw new UsernameNotFoundException("User not found"); } } @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ``` 在上述代码中,我们使用了`BCryptPasswordEncoder`来加密用户密码,并实现了`UserDetailsService`接口来加载用户信息。这里只提供了两个简单的用户,一个是admin用户,一个是user用户。 通过以上步骤,我们已经完成了Spring BootSpring Security的简单整合。当我们启动应用程序后,访问不同的URL路径时,系统会根据配置的角色要求进行身份验证和授权。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值