FixedTokenInterceptor

如何使用 FixedTokenInterceptor 实现 TioBoot 应用的权限验证

简介

在开发基于 TioBoot 的 Web 应用时,安全性是一个不可忽视的重要部分。本文将指导您如何使用 FixedTokenInterceptor 拦截器来实现简单的权限验证,确保只有拥有有效令牌的请求才能访问特定的路由。

准备工作

首先,确保您的项目中已经集成了 tio-boot 依赖库。此外,需要在配置文件中设置一个属性来存储认证令牌。例如,在 app.properties 文件中添加如下配置:

app.auth.token=123456

配置拦截器

以下步骤将指导您如何配置 FixedTokenInterceptor 以实现 API 的安全访问。

1. 创建配置类

使用 @AConfiguration 注解定义一个配置类。这告诉 TioBoot 框架这个类包含了一些初始化配置。

2. 配置拦截器

在配置类中,使用 @AInitialization 注解的方法设置拦截器。此方法将在服务器启动时执行。

import com.litongjava.jfinal.aop.annotation.AConfiguration;
import com.litongjava.jfinal.aop.annotation.AInitialization;
import com.litongjava.tio.boot.http.interceptor.HttpServerInterceptorModel;
import com.litongjava.tio.boot.http.interceptor.ServerInteceptorConfigure;
import com.litongjava.tio.boot.satoken.FixedTokenInterceptor;
import com.litongjava.tio.boot.server.TioBootServer;
import com.litongjava.tio.http.server.intf.HttpRequestInterceptor;
import com.litongjava.tio.utils.environment.EnvUtils;

@AConfiguration
public class InterceptorConfiguration {

  @AInitialization
  public void config() {
    String authToken = EnvUtils.get("app.auth.token");
    // 创建 SaToken 拦截器实例
    HttpRequestInterceptor tokenInterceptor = new FixedTokenInterceptor(authToken);
    HttpServerInterceptorModel model = new HttpServerInterceptorModel();
    model.setInterceptor(tokenInterceptor);
    model.addblockeUrl("/**"); // 拦截所有路由
    // 设置例外路由 index
    model.addAlloweUrls("/", "");
    // 设置例外路由 register
    model.addAlloweUrls("/register/*");

    ServerInteceptorConfigure serverInteceptorConfigure = new ServerInteceptorConfigure();
    serverInteceptorConfigure.add(model);
    // 将拦截器配置添加到 Tio 服务器,为了提高性能,默认serverInteceptorConfigure为null,必须添加
    TioBootServer.me().setServerInteceptorConfigure(serverInteceptorConfigure);
  }
}

4. 拦截器详解

  • FixedTokenInterceptor:此拦截器使用从配置文件读取的令牌来验证请求。只有在请求头中包含正确的令牌时,请求才被允许通过。
  • HttpServerInterceptorModel:用于配置具体的拦截规则,如哪些 URL 被拦截,哪些允许通过。

5. 设置路由规则

通过 addblockeUrladdAlloweUrls 方法设置哪些路由被拦截,哪些路由不受影响。例如,所有路由默认被拦截,但//register/*路由不被拦截。

6. 请求

请求时需要添加请求头 authorization

curl --location --request GET 'http://localhost' \
--header 'authorization: 123456' \

结束语

通过以上步骤,您可以在 TioBoot 应用中使用 FixedTokenInterceptor 来实现基本的 API 访问控制。这样可以保护您的应用不受未授权访问的影响,增强应用的安全性。