【FastRequest】2024.1.3破解版与自动配置token脚本

原帖:https://www.lisok.cn/reverse-programming/306.html

破解版插件:https://pan.baidu.com/s/1tF4hH8GUAqJAYYR63Qm-UA?pwd=7drv


安装好插件,配置环境信息


以下脚本采用Groovy编写

todo 你需要根据自己的实际情景进行修改
以下通过FastRequest 内置环境变量实现,多个工程间无法共享token

import groovy.json.JsonSlurper
import java.time.LocalDateTime

request.header("Content-Type", "application/json")
// 租户id
def tenantId = "0"
// 用户名
def username = "guest"
// 密码
def password = "123456"
// 登录路径
def loginUrl = ""
// 当前环境
def currentEnvName = rfr.currentEnvName
console.info("CurrentEnv: ${currentEnvName}")
// todo 配置环境信息
switch (currentEnvName) {
    case "dev":
        tenantId = "1566"
        loginUrl = "http://dev-api.yourdomain.com/login"
        break
    case "test":
        tenantId = "4588"
        loginUrl = "http://test-api.yourdomain.com/login"
        break
    case "uat":
    case "prod":
        tenantId = "0"
        break
}

request.header("Tenant-Id", tenantId)
console.info("Set TenantId: ${tenantId}")

// 登录,获取token
def login(loginUrl, tenantId, username, password, tokenKey, tokenExpiresKey) {
    def loginRequest = cn.hutool.http.HttpRequest.post(loginUrl)
    loginRequest.header("Content-Type", "application/json")
    def jsonBody = """{
                "tenantId": "${tenantId}",
                "username": "${username}",
                "password": "${password}"
            }"""
    loginRequest.body(jsonBody)
    console.info("Login loginRequest: ${loginRequest}")
    def loginResponse = loginRequest.execute()
    console.info("Login Response: ${loginResponse.body()}")

    // todo 从json获取token
    def parsedJson = new JsonSlurper().parseText(loginResponse.body())
    console.info("Login ParsedJson.data: ${parsedJson.data}")
    console.info("Login Token: ${parsedJson.data.token}")
    rfr.environment.put(tokenKey, "Bearer ${parsedJson.data.token}")

    def tokenExpires = LocalDateTime.now()
    console.info("Login Now: ${tokenExpires}")
    console.info("Login TokenExpires: ${tokenExpires.plusHours(12)}")
    // todo 设置token过期时间
    rfr.environment.put(tokenExpiresKey, tokenExpires.plusHours(12))
}

console.info("environment: ${rfr.environment}")
def tokenKey = rfr.currentEnvName.toUpperCase() + "_TOKEN"
def tokenExpiresKey = rfr.currentEnvName.toUpperCase() + "_TOKEN_EXPIRES"

def token = rfr.environment.get(tokenKey)
console.info("${tokenKey}: ${token}")
def tokenExpires = rfr.environment.get(tokenExpiresKey)
console.info("${tokenExpiresKey}: ${tokenExpires}")
if (!token || (tokenExpires && LocalDateTime.now().isAfter(LocalDateTime.parse(tokenExpires)))) {
    console.info("now is after tokenExpires: ${LocalDateTime.now().isAfter(LocalDateTime.parse(tokenExpires))}")
    login(loginUrl, tenantId, username, password, tokenKey, tokenExpiresKey)
}

request.header("Authorization", "${token}")
console.info("Set Authorization: ${token}")

以下通过文件实现,多个工程间可以共享token

import cn.hutool.http.HttpRequest
import cn.hutool.http.HttpResponse
import cn.hutool.json.JSONUtil
import io.github.kings1990.plugin.fastrequest.core.Console

import java.io.File
import java.io.FileOutputStream
import java.io.FileReader
import java.nio.charset.StandardCharsets
import java.time.LocalDateTime
import java.util.Properties

class AutoToken {
    Console console
    HttpRequest request
    private static final String filePath = "D:/fastRequestEnv.properties"
    Properties props = new Properties()
    ENV env
    loginInfo loginInfo

    AutoToken(String envName, HttpRequest request, Console console) {
        console.info("Init AutoToken Start...")
        console.info("Properties Save Path: $filePath")
        this.console = console
        this.request = request
        initEnv(envName)
        initProps()
        console.info("Init AutoToken End")
    }

    // todo 改为自己的环境信息,账户密码
    void initEnv(String envName) {
        console.info("Env: $envName")
        switch (envName) {
            case ['local', 'dev']:
                this.env = ENV.DEV
                this.loginInfo = new loginInfo("0", 'guest', 'guest', "http://dev-api.yourdomain.com/auth/login")
                break
            case 'test':
                this.env = ENV.TEST
                this.loginInfo = new loginInfo("0", 'guest', 'guest', "http://test-api.yourdomain.com/auth/login")
                break
            case 'uat':
                this.env = ENV.UAT
                this.loginInfo = new loginInfo("0", 'guest', 'guest', "http://uat-api.yourdomain.com/auth/login")
                break
            case 'prod':
                this.env = ENV.PROD
                this.loginInfo = new loginInfo("0", 'guest', 'guest', "http://prod-api.yourdomain.com/auth/login")
                break
            default:
                throw new RuntimeException("Not Found Env In AutoToken.ENV!")
        }
    }

    void initProps() {
        if (!new File(filePath).exists()) {
            try (FileWriter fileWriter = new FileWriter(filePath, StandardCharsets.UTF_8)) {
                props.store(fileWriter, "FastRequest Token");
            } catch (IOException e) {
                console.error(e)
            }
        }
        try (FileReader fileReader = new FileReader(filePath, StandardCharsets.UTF_8)) {
            props.load(fileReader)
        } catch (IOException e) {
            console.error(e)
        }

        String token = props.getProperty(env.tokenKey)
        LocalDateTime tokenExpires = props.getProperty(env.tokenExpiresKey) == null ? null : LocalDateTime.parse(props.getProperty(env.tokenExpiresKey))
        if (!token || (tokenExpires && LocalDateTime.now().isAfter(tokenExpires))) {
            getToken()
        }
    }

    void getToken() {
        console.info("Login Start...")
        console.info("Props: $props")
        HttpRequest loginRequest = HttpRequest.post(loginInfo.loginUrl)
        loginRequest.header('Content-Type', 'application/json')
        loginRequest.body(JSONUtil.toJsonPrettyStr(loginInfo))
        console.info(loginRequest)

        HttpResponse response = loginRequest.execute()
        console.info("Response: ${response.body()}")
        BaseResult result = JSONUtil.toBean(response.body(), BaseResult)
        console.info("Result: ${result}")
        if (result && result.isSuccess() && result.data) {
            props.setProperty(env.tokenKey, result.data.token)
            props.setProperty(env.tokenExpiresKey, LocalDateTime.now().plusHours(12).toString())
        }
        try (FileWriter fileWriter = new FileWriter(filePath, StandardCharsets.UTF_8)) {
            props.store(fileWriter, "FastRequest Token");
        } catch (IOException e) {
            console.error(e)
        }
        console.info("Props: $props")
        console.info("Login End")
    }

    void run() {
        console.info("Set Headers Start...")
        console.info("Props: $props")
        this.request.header('Content-Type', 'application/json')
        this.request.header('X-QiFu-Tenant-Id', loginInfo.tenantId)
        this.request.header('Authorization', "Bearer " + props.getProperty(env.tokenKey))
        console.info("Set Headers End")
    }
     
    // todo 改成自己的响应数据结构
    private class BaseResult {
        Integer code
        AuthVO data

        boolean isSuccess() { 20000 == code }
    }

    private class AuthVO {
        String token
    }

    private class loginInfo {
        String tenantId
        String username
        String password
        String loginUrl

        loginInfo(String tenantId, String username, String password, String loginUrl) {
            this.tenantId = tenantId
            this.username = username
            this.password = password
            this.loginUrl = loginUrl
        }
    }

    private enum ENV {
        DEV('DEV_TOKEN', 'DEV_TOKEN_EXPIRES'),
        TEST('TEST_TOKEN', 'TEST_TOKEN_EXPIRES'),
        UAT('UAT_TOKEN', 'UAT_TOKEN_EXPIRES'),
        PROD('PROD_TOKEN', 'PROD_TOKEN_EXPIRES')

        private String tokenKey
        private String tokenExpiresKey

        ENV(String tokenKey, String tokenExpiresKey) {
            this.tokenKey = tokenKey
            this.tokenExpiresKey = tokenExpiresKey
        }
    }
}

AutoToken autoToken = new AutoToken(rfr.currentEnvName, request, console)
autoToken.run()

配置脚本到FastRequest

5 Likes

wow