{"record":{"id":"159f19a892557ee6","repo":"pagehelper-org/Mybatis-PageHelper","slug":"order-by-orderby-has-a-risk-of-sql-injection","errorCode":null,"errorMessage":"order by [${orderBy}] has a risk of SQL injection, if you want to avoid SQL injection verification, you can call Page.setUnsafeOrderBy","messagePattern":"order by \\[(.+?)\\] has a risk of SQL injection, if you want to avoid SQL injection verification, you can call Page\\.setUnsafeOrderBy","errorType":"exception","errorClass":"PageException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/github/pagehelper/Page.java","lineNumber":284,"sourceCode":"    public Page<E> setPageSizeZero(Boolean pageSizeZero) {\n        if (this.pageSizeZero == null && pageSizeZero != null) {\n            this.pageSizeZero = pageSizeZero;\n        }\n        return this;\n    }\n\n    public String getOrderBy() {\n        return orderBy;\n    }\n\n    /**\n     * 设置排序字段，增加 SQL 注入校验，如果需要在 order by 使用函数，可以使用 {@link #setUnsafeOrderBy(String)} 方法\n     *\n     * @param orderBy 排序字段\n     */\n    public <E> Page<E> setOrderBy(String orderBy) {\n        if (SqlSafeUtil.check(orderBy)) {\n            throw new PageException(\"order by [\" + orderBy + \"] has a risk of SQL injection, \" +\n                    \"if you want to avoid SQL injection verification, you can call Page.setUnsafeOrderBy\");\n        }\n        this.orderBy = orderBy;\n        return (Page<E>) this;\n    }\n\n    /**\n     * 不安全的设置排序方法，如果从前端接收参数，请自行做好注入校验。\n     * <p>\n     * 请不要故意使用该方法注入然后提交漏洞!!!\n     *\n     * @param orderBy 排序字段\n     */\n    public <E> Page<E> setUnsafeOrderBy(String orderBy) {\n        this.orderBy = orderBy;\n        return (Page<E>) this;\n    }\n","sourceCodeStart":266,"sourceCodeEnd":302,"githubUrl":"https://github.com/pagehelper-org/Mybatis-PageHelper/blob/c692616c5bc95b41aa779b502f991825c8e5acbc/src/main/java/com/github/pagehelper/Page.java#L266-L302","documentation":"PageHelper validates the orderBy string passed to a Page object with SqlSafeUtil to prevent SQL injection, since ORDER BY clauses cannot be parameterized. If the string contains characters deemed unsafe (quotes, comments, multiple tokens that look like injected SQL), a PageException is thrown before any query runs. The library offers setUnsafeOrderBy to bypass this check when you intentionally use functions in ORDER BY.","triggerScenarios":"Calling Page.setOrderBy(String) (directly or via PageHelper.orderBy(...), PageHelper.startPage(page,size,orderBy), PageHelper.offsetPage, or PageHelper.getPageFromObject binding an orderBy param) with a string SqlSafeUtil.check() rejects, e.g. containing single quotes, semicolons, or SQL comments.","commonSituations":"Passing a sort string straight from an HTTP request parameter (user-controlled 'sort=name; DROP TABLE x' or 'id desc--'), or intentionally using ORDER BY functions like 'if(is_valid=1, id, create_time) desc' which the safe check rejects.","solutions":["Sanitize the orderBy value: only allow whitelisted column names and directions before calling setOrderBy.","If the value is trusted and you need functions/expressions, call page.setUnsafeOrderBy(orderBy) instead of setOrderBy.","Map user input to fixed internal sort keys instead of passing raw strings.","Intercept on the API layer: reject/revert inputs containing quotes, semicolons, or comment markers."],"exampleFix":"// before\nPageHelper.startPage(pageNum, pageSize, request.getParameter(\"sort\"));\n// after\nString sort = request.getParameter(\"sort\");\nif (\"price\".equals(sort)) {\n    PageHelper.startPage(pageNum, pageSize, \"price desc\");\n} else {\n    PageHelper.startPage(pageNum, pageSize, \"id desc\"); // whitelist\n}","handlingStrategy":"validation","validationCode":"private static final Pattern SAFE_ORDER = Pattern.compile(\"^[a-zA-Z0-9_.]+(\\\\s+(asc|desc))?$\", Pattern.CASE_INSENSITIVE);\nstatic void assertSafeOrderBy(String orderBy) {\n    if (orderBy == null || !SAFE_ORDER.matcher(orderBy.trim()).matches()) {\n        throw new IllegalArgumentException(\"unsafe orderBy: \" + orderBy);\n    }\n}","typeGuard":"static boolean isSafeOrderBy(String s) {\n    return s != null && s.matches(\"[\\\\w.,\\\\s()]+\") && !s.matches(\".*('|;|--|/\\\\*).*\");\n}","tryCatchPattern":"try {\n    PageHelper.orderBy(orderBy);\n} catch (PageException e) {\n    log.warn(\"Rejected orderBy: {}\", orderBy, e);\n    PageHelper.orderBy(\"id desc\"); // safe default\n}","preventionTips":["Never pass raw request parameters into setOrderBy; map to a whitelist of allowed sort keys.","Only use setUnsafeOrderBy for trusted, developer-controlled strings.","Unit test every sort expression string you ship with SqlSafeUtil.check().","Reject quotes, semicolons, and comment markers at the API validation layer."],"tags":["sql-injection","security-validation","orderby","java"],"backgroundTag":"sql-injection-risk","analyzedSha":"c692616c5bc95b41aa779b502f991825c8e5acbc","analyzedAt":"2026-09-08T03:50:49.192Z","contentChangedAt":"2026-09-08T03:50:49.192Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}