首页 > 其他分享 >SpringBoot-3 拦截器注入配置

SpringBoot-3 拦截器注入配置

时间:2023-08-03 11:22:12浏览次数:32  
标签:拦截器 SpringBoot expectedToken token tokenProperties 注入 public String

如果拦截器加载的时间点在Spring的上下文初始化之前,导致注入的值为null,您可以尝试以下两种解决方法:

  1. 使用@PostConstruct注解:
    在拦截器中使用@PostConstruct注解标记一个初始化方法,在该方法中手动获取配置值,并进行相应的处理。这样可以确保在拦截器初始化完成后,配置值已经被正确加载。例如:
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Value("${authorize.token}")
    private String expectedToken;

    private String cachedExpectedToken;

    @PostConstruct
    public void init() {
        // 在初始化方法中获取配置值并缓存
        cachedExpectedToken = expectedToken;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 使用缓存的配置值进行处理
        String token = request.getHeader("Authorization");
        System.out.println("从header中获取到token:" + token);
        System.out.println("expectedToken:" + cachedExpectedToken);
        if (token != null && token.equals(cachedExpectedToken)) {
            return true;
        } else {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("无权限访问");
            return false;
        }
    }

    // 省略其他方法
}
  1. 自定义属性读取类:
    创建一个自定义的属性读取类,在该类中手动读取配置文件中的属性值,并在拦截器中使用该属性读取类获取配置值。这样可以确保配置值在拦截器初始化之前已经被正确加载。例如:
@Component
public class TokenProperties {

    @Value("${authorize.token}")
    private String expectedToken;

    public String getExpectedToken() {
        return expectedToken;
    }
}

@Component
public class TokenInterceptor implements HandlerInterceptor {

    private final TokenProperties tokenProperties;

    @Autowired
    public TokenInterceptor(TokenProperties tokenProperties) {
        this.tokenProperties = tokenProperties;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 使用属性读取类获取配置值进行处理
        String token = request.getHeader("Authorization");
        System.out.println("从header中获取到token:" + token);
        System.out.println("expectedToken:" + tokenProperties.getExpectedToken());
        if (token != null && token.equals(tokenProperties.getExpectedToken())) {
            return true;
        } else {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("无权限访问");
            return false;
        }
    }

    // 省略其他方法
}

标签:拦截器,SpringBoot,expectedToken,token,tokenProperties,注入,public,String
From: https://www.cnblogs.com/zhaogaojian/p/17602802.html

相关文章

  • web渗透测试(12):命令注入
    命令注入来自缺乏对作为命令一部分使用的信息的过滤和编码。最简单的示例来自使用函数system(运行命令)并将HTTP参数作为此命令的参数。 有很多方法可以利用命令注入:例如,通过在反引号内注入命令 `id`通过将第一个命令的结果重定向到第二个命令 |id如果由第一个成功运行的......
  • SpringBoot 快速配置日志方法
     快速配置日志方法#loglogging.file=logs/stdout.loglogging.file.max-size=20KBlogging.pattern.file=%date[%thread][IP:%X{ip}|USER:%X{user}][%-5level%logger{80}]%msg%nlogging.pattern.console=%date[%thread][IP:%X{ip}|USER:%X{user}][%-5level%logger{80}]......
  • SpringBoot 单元测试不执行:maven-surefire-plugin 版本问题
    SpringBoot单元测试不执行:maven-surefire-plugin版本问题 问题现象SpringBoot项目,在编写单元测试时,使用了JUnit4.13.2以上的版本。为了让Maven能自动运行单元测试,需要引入MavenSurefire或MavenFailsafe插件。项目中使用的maven-surefire-plugin版本号为......
  • 《Web安全基础》03. SQL 注入
    @目录1:简要SQL注入2:MySQL注入2.1:信息获取2.2:跨库攻击2.3:文件读写2.4:常见防护3:注入方法3.1:类型方法明确3.2:盲注3.3:编码3.4:二次注入3.5:DNSlog注入3.6:堆叠注入4:WAF绕过4.1:WAF简介4.2:绕过方法5:其他数据库注入5.1:Access5.2:SqlServer5.3:PostgreSQL5.4:Oracle5.5:MongoDB本系列侧......
  • 运维——springboot项目部署
    转自:https://juejin.cn/post/6844903877150507016#heading-20摘要本文主要以图文的形式讲解mall在Linux环境下的部署,涉及在Docker容器中安装Mysql、Redis、Nginx、RabbitMQ、Elasticsearch、Mongodb,以及SpringBoot应用部署,基于CenterOS7.6。Docker环境安装安装yum-utils:......
  • post时间注入脚本
    importrequestsimportsysimporttimeimportpdbclassInjection():def__init__(self):self.url=""self.schemataNum=0defInjectionSchemaNumber(self):high=30low=1mid=(low+high)//2......
  • springboot 初始化加载过程 条件注解
    官网解释:https://docs.spring.io/spring-boot/docs/3.0.9/reference/html/features.html#features.developing-auto-configuration.condition-annotations从其他博客粘过来的表格:条件注解Condition处理类实例解释@ConditionalOnBeanOnBeanCondition@ConditionalOnBean(D......
  • Springboot+elasticsearch基础整合实例
    es,当插入数据的时候,可以自动创建索引,但是mapping却都是默认类型,导致搜索时需要key.keyword方式,不科学。索引也可以手偶刚创建,指定mapping。当然还有一种优雅的方案使用template,当自动创建索引的时候,我们的字段类型就可控了。真实业务中,不能用一个固定的index,索引是需要切分的......
  • 逆向工程核心原理——第二十七章 进程注入-代码注入
    官方源码地址:https://blog.kakaocdn.net/dn/buCuJU/btq2OpiKoTz/JIIGkCcw1xjLtsDt4yV5dk/%EC%86%8C%EC%8A%A4%EC%BD%94%EB%93%9C.zip?attach=1&knm=tfile.zip虽然是韩语,但是编译依然ok! 写在前面,我用官方给的代码,使用vs2022编译release模式,在win11上也注入成功了!注意dll也需要编译......
  • 进程注入如何通过调用栈,使用ML分类来检测——非常值得借鉴,待实践
    4、MachineLearningtoUltimatelyDefeatAdvancedRansomwareThreatsRSA2022的这个分享主题核心讲解了进程注入如何通过调用栈,使用ML分类来检测。当然,勒索的其他本质特征例如文件加密等没有提到。但是其进程注入的检测值得重点关注。Ryukasthemostadvancedformofransomw......