Sorting and its safety limits
On This Lesson 4 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
allow sorting without opening a hole.
Planned topics
- Format:
?sort=price,desc. Default to a stable sort such asid. - Accept only an allow-list of fields:
name,price,createdAt. - Never put the user's text into a query or column name; with a database that is SQL injection.
- Unknown field gives
400with a clear message. - Always add a tie-breaker (
id) so pages do not repeat or skip items.
Draft outline details
Demonstration
private static final Set<String> SORTABLE = Set.of("name", "price", "createdAt");
if (!SORTABLE.contains(field)) throw new BadRequestException("Cannot sort by " + field);Check your understanding
Why an allow-list?
Show answer
Users must not choose arbitrary fields or columns.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.