xm
2024-06-14 722af26bc6fec32bb289b1df51a9016a4935610f
提交 | 用户 | 时间
722af2 1 package com.dl.framework.config;
X 2
3 import cn.dev33.satoken.dao.SaTokenDao;
4 import cn.dev33.satoken.interceptor.SaInterceptor;
5 import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
6 import cn.dev33.satoken.router.SaRouter;
7 import cn.dev33.satoken.stp.StpInterface;
8 import cn.dev33.satoken.stp.StpLogic;
9 import cn.dev33.satoken.stp.StpUtil;
10 import com.dl.common.utils.spring.SpringUtils;
11 import com.dl.framework.config.properties.SecurityProperties;
12 import com.dl.framework.handler.AllUrlHandler;
13 import com.dl.framework.satoken.dao.PlusSaTokenDao;
14 import com.dl.framework.satoken.service.SaPermissionImpl;
15 import lombok.RequiredArgsConstructor;
16 import lombok.extern.slf4j.Slf4j;
17 import org.springframework.context.annotation.Bean;
18 import org.springframework.context.annotation.Configuration;
19 import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
20 import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
21
22 /**
23  * sa-token 配置
24  *
25  * @author Lion Li
26  */
27 @RequiredArgsConstructor
28 @Slf4j
29 @Configuration
30 public class SaTokenConfig implements WebMvcConfigurer {
31
32     private final SecurityProperties securityProperties;
33
34     /**
35      * 注册sa-token的拦截器
36      */
37     @Override
38     public void addInterceptors(InterceptorRegistry registry) {
39         // 注册路由拦截器,自定义验证规则
40         registry.addInterceptor(new SaInterceptor(handler -> {
41             AllUrlHandler allUrlHandler = SpringUtils.getBean(AllUrlHandler.class);
42             // 登录验证 -- 排除多个路径
43             SaRouter
44                 // 获取所有的
45                 .match(allUrlHandler.getUrls())
46                 // 对未排除的路径进行检查
47                 .check(() -> {
48                     // 检查是否登录 是否有token
49                     StpUtil.checkLogin();
50
51                     // 有效率影响 用于临时测试
52                     // if (log.isDebugEnabled()) {
53                     //     log.debug("剩余有效时间: {}", StpUtil.getTokenTimeout());
54                     //     log.debug("临时有效时间: {}", StpUtil.getTokenActivityTimeout());
55                     // }
56
57                 });
58         })).addPathPatterns("/**")
59             // 排除不需要拦截的路径
60             .excludePathPatterns(securityProperties.getExcludes());
61     }
62
63     @Bean
64     public StpLogic getStpLogicJwt() {
65         // Sa-Token 整合 jwt (简单模式)
66         return new StpLogicJwtForSimple();
67     }
68
69     /**
70      * 权限接口实现(使用bean注入方便用户替换)
71      */
72     @Bean
73     public StpInterface stpInterface() {
74         return new SaPermissionImpl();
75     }
76
77     /**
78      * 自定义dao层存储
79      */
80     @Bean
81     public SaTokenDao saTokenDao() {
82         return new PlusSaTokenDao();
83     }
84
85 }