Spring boot Security Druid 监控

1. Druid 配置属性

Druid数据源(连接池): 类似 c3p0、dbcp 数据源,可设置数据源连接初始化大小、最大连接数、等待时间、最小连接数等;

Druid web 监控 filter(WebStatFilter): 统计 web 应用请求中所有的数据库信息,比如 发出的 sql 语句,sql 执行的时间、请求次数、请求的 url 地址、以及seesion 监控、数据库表的访问次数 等等。

Druid 后台管理 Servlet(StatViewServlet): Druid 数据源具有监控的功能,并提供了一个 web 界面方便用户查看。

appilication.yml

spring:
  profiles:
    active: dev
  datasource:
    druid:
      initial-size: 1 # 初始化时建立物理连接的个数
      min-idle: 1 # 最小连接池数量
      max-active: 10 # 最大连接池数量
      max-wait: 60000 # 获取连接时最大等待时间,单位毫秒
      time-between-eviction-runs-millis: 60000 # 申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
      min-evictable-idle-time-millis: 300000 # 销毁线程时检测当前连接的最后活动时间和当前时间差大于该值时,关闭当前连接
      validation-query: SELECT 1
      test-while-idle: true
      test-on-borrow: false # 申请连接时会执行validationQuery检测连接是否有效,开启会降低性能,默认为true
      test-on-return: false # 归还连接时会执行validationQuery检测连接是否有效,开启会降低性能,默认为true
      pool-prepared-statements: true # 是否缓存preparedStatement,mysql5.5+建议开启
      max-pool-prepared-statement-per-connection-size: 20 # 当值大于0时poolPreparedStatements会自动修改为true
      filters: stat,wall,slf4j # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
      connect-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500 # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
      use-global-data-source-stat: true # 合并多个DruidDataSource的监控数据
      stat-view-servlet:
        enabled: true # 启用内置的监控页面
        url-pattern: /druid/*
        reset-enable: false #关闭 Reset All 功能
        login-username: admin # 设置登录用户名
        login-password: 123456 # 设置登录密码
        allow: 0.0.0.0 # 白名单(如果allow没有配置或者为空,则允许所有访问)
      web-stat-filter:
        enabled: true # 启用StatFilter
        url-pattern: /*
        exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
        session-stat-enable: true # 开启session统计功能
        session-stat-max-count: 1000

application-dev.yml

spring:
  datasource:
    druid:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&verifyServerCertificate=false&useSSL=false&allowMultiQueries=true
      username: root
      password: 12345678

实际配置:application.yml + applciation-dev.yml

2. Spring security 异常

Spring security 异常包含认证异常和授权异常。

2.1 AuthenticationException 认证异常

用户认证时会抛出的异常。

  • 系统用户不存在
  • 用户被锁定
  • 登录凭证失效
  • 密码错误
  • ...

2.2 AccessDeniedException 授权异常

用户在访问受保护资源时被拒绝而抛出的异常,主要是CSRF相关的异常和授权服务异常。

2.3 实际使用场景

  • WebSecurityConfigureeAdapter 接口实现
  • AuthenticationEntryPoint 接口实现
  • AccessDeniedHandler 接口实现

WebSecurityConfigureeAdapter

@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
		System.out.println("11111111111a");
        httpSecurity
                // we don't need CSRF because our token is invulnerable
                .csrf().disable()
                // set exception handler
                .exceptionHandling()
                .authenticationEntryPoint(authenticationErrorHandler)
                .accessDeniedHandler(jwtAccessDeniedHandler)
                .authorizeRequests()
                .antMatchers("/druid/**").permitAll()
                ....
    }
}

AuthenticationEntryPoint

@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        // This is invoked when user tries to access a secured REST resource without supplying any credentials
        // We should just send a 401 Unauthorized response because there is no 'login page' to redirect to
        // Here you can place any message you want
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(JSONUtil.toJsonStr(TokenResponseResult.failure("The JWT token is expired", "TOKEN_EXPIRED")));
        writer.close();
        response.flushBuffer();
    }
}

AccessDeniedHandler

@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
        // This is invoked when user tries to access a secured REST resource without the necessary authorization
        // We should just send a 403 Forbidden response because there is no 'error' page to redirect to
        // Here you can place any message you want
        response.sendError(HttpServletResponse.SC_FORBIDDEN, accessDeniedException.getMessage());
    }
}

说明

1. WebSecurityConfigureeAdapter 在项目启动时会执行。项目启动之后,在实际访问URL时会根据配置进行匹配。

2. AuthenticationEntryPoint & AccessDeniedHandler 在使用时进行认证。

AuthenticationEntryPoint是Spring Security Web一个概念模型接口,顾名思义,他所建模的概念是:“认证入口点”。

3. commence方法里不能添加打印log,否则会报错。

3. Druid 监控页面

1. 访问页面

2. 数据源页面

数据源页面 是当前DataSource配置的基本信息,上述配置的Filter可以在里面找到,如果没有配置Filter(一些信息会无法统计,例如“SQL监控”,会无法获取JDBC相关的SQL执行信息)

3. SQL监控

统计了所有SQL语句的执行情况

4. URL监控

统计了所有Controller接口的访问以及执行情况

5. Spring监控

利用aop 对指定接口的执行时间,jdbc数进行记录。

spring监控默认是没有数据,需要导入spring-aop 模块。

 <!--SpringBoot 的aop 模块-->
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-aop</artifactId>
 </dependency>

Spring监控AOP切入点,如com.zzg.mapper.*,配置多个英文逗号分隔

  spring.datasource.druid.aop-patterns="com.zzg.mapper.*"

6. SQL防火墙

druid提供了黑白名单的访问,可以清楚的看到sql防护情况。

7. Session监控

可以看到当前的session状况,创建时间、最后活跃时间、请求次数、请求时间等详细参数。

8. JSON API

通过api的形式访问Druid的监控接口,api接口返回Json形式数据。

9. Web应用

 web-stat-filter:
     enabled: true # 启用StatFilter
     url-pattern: /*
     exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
     session-stat-enable: true # 开启session统计功能
     session-stat-max-count: 1000

作用就是统计 web 应用请求中所有的数据库信息,比如 发出的 sql 语句,sql 执行的时间、请求次数、请求的 url 地址、以及seesion 监控、数据库表的访问次数 等等。

10. 慢sql记录

系统中有些SQL执行很慢,我们希望使用日志记录下来,可以开启Druid的慢SQL记录功能

参考

Spring Security 自定义异常处理

Spring Security 异常处理机制

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值