Sign-up endpoint with validation
50 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A shop that cannot register customers cannot sell. Sign-up is the one public door into ShopLite, so it must check every field, never keep a readable password and never hand one back.
POST /api/v1/auth/register with a SignUpRequest record
SignUpRequest is the record that carries the body of POST /api/v1/auth/register: fullName, email, password and an optional phone, each checked by Bean Validation annotations before the service runs.
Anyone may call POST /api/v1/auth/register, so the endpoint is public and every field is validated. Example 1 has the record and the controller.
// src/main/java/com/shoplite/common/security/SecurityConfig.java (the new rule, above anyRequest)// Anyone may create an account.requestMatchers(HttpMethod.POST, "/api/v1/auth/register").permitAll()Example 1 · src/main/java/com/shoplite/user/SignUpRequest.java and AuthController.java
Runs in: the shoplite-api Spring Boot project (Spring Boot 4.1, Spring Security 7, MySQL)
// src/main/java/com/shoplite/user/SignUpRequest.javapackage com.shoplite.user;
import com.shoplite.common.validation.IndianMobile;import com.shoplite.common.validation.MaxBytes;
import jakarta.validation.constraints.Email;import jakarta.validation.constraints.NotBlank;import jakarta.validation.constraints.NotNull;import jakarta.validation.constraints.Size;
/** The body of POST /api/v1/auth/register. */public record SignUpRequest( @NotBlank(message = "is required") @Size(min = 2, max = 100, message = "must be 2-100 characters") String fullName,
@NotBlank(message = "is required") @Email(message = "must be a valid e-mail address") @Size(max = 255, message = "must be at most 255 characters") String email,
@NotNull(message = "is required") @Size(min = 15, max = 64, message = "must be 15-64 characters") @MaxBytes(value = 72, message = "must be at most 72 bytes in UTF-8") String password,
@IndianMobile String phone) {
/** Trim names and e-mails before validation. Never touch the password: every character counts. */ public SignUpRequest { fullName = fullName == null ? null : fullName.trim(); email = email == null ? null : email.trim(); }
/** Records print every field; this one must never print the password. */ @Override public String toString() { return "SignUpRequest[fullName=" + fullName + ", email=" + email + ", password=***, phone=" + phone + "]"; }}
// src/main/java/com/shoplite/user/AuthController.javapackage com.shoplite.user;
import java.net.URI;
import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import jakarta.validation.Valid;
/** Sign-up now; sign-in with a token comes in the JWT module. */@RestController@RequestMapping("/api/v1/auth")class AuthController {
private final UserService userService;
AuthController(UserService userService) { this.userService = userService; }
@PostMapping("/register") ResponseEntity<UserResponse> register(@Valid @RequestBody SignUpRequest request) { UserResponse created = userService.register(request); URI location = ServletUriComponentsBuilder.fromCurrentContextPath() .path("/api/v1/customers/{id}") .buildAndExpand(created.customerId()) .toUri(); return ResponseEntity.created(location).body(created); }}$ curl -i -X POST http://localhost:8080/api/v1/auth/register -H "Content-Type: application/json" -d '{"fullName":"Sneha Patil","email":" Sneha.Patil@Example.com ","password":"my laptop bag arrives at 7 pm","phone":"9876543209"}'
HTTP/1.1 201
Location: http://localhost:8080/api/v1/customers/9
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 08:03:38 GMT
{"id":3,"email":"sneha.patil@example.com","fullName":"Sneha Patil","customerId":9,"roles":["CUSTOMER"]}What this code does
- A guest calls the endpoint without any
Authorizationheader and gets201: thepermitAllrule lets the request through the security chain. - The e-mail was typed with spaces and capitals; the response shows it saved as
sneha.patil@example.com.Locationpoints at customer 9, the new row (the dev data has 8 customers). - The body has no password field. The extra headers (
X-Frame-Options,Cache-Control...) are Spring Security's defaults on every response.
Auth endpoints live under /api/v1/auth/..., next to the rest of the v1 contract. The new permitAll rule sits above anyRequest().authenticated(): a guest has no account yet, so asking them to sign in first would make sign-up impossible.
The record's compact constructor trims fullName and email before validation but never touches the password, because a space at the end may be part of it. Its toString() prints password=***: a record's default toString() prints every field, so one log.debug("{}", request) would put real passwords in the log.
A password policy: length beats complexity
Password policy is the rule a new password must pass. ShopLite requires 15 to 64 characters, allows any characters, and caps the size at 72 bytes in UTF-8, with no capital, digit or symbol rules.
ShopLite checks length and bytes, not capitals or symbols. Examples 2 and 3 show the 400 answers and why length wins.
Example 2 · src/main/java/com/shoplite/common/validation/MaxBytes.java: bad bodies and the 72-byte rule
Runs in: the shoplite-api Spring Boot project (Spring Boot 4.1, Spring Security 7, MySQL)
// src/main/java/com/shoplite/common/validation/MaxBytes.javapackage com.shoplite.common.validation;
import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;
import jakarta.validation.Constraint;import jakarta.validation.Payload;
/** The text must fit in this many bytes when written as UTF-8 (BCrypt reads at most 72). null is allowed. */@Constraint(validatedBy = MaxBytesValidator.class)@Documented@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.RECORD_COMPONENT})@Retention(RetentionPolicy.RUNTIME)public @interface MaxBytes {
int value();
String message() default "is too long";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};}
// src/main/java/com/shoplite/common/validation/MaxBytesValidator.javapackage com.shoplite.common.validation;
import java.nio.charset.StandardCharsets;
import jakarta.validation.ConstraintValidator;import jakarta.validation.ConstraintValidatorContext;
/** Checks @MaxBytes: counts UTF-8 bytes, not characters (one Hindi letter is 3 bytes). */public class MaxBytesValidator implements ConstraintValidator<MaxBytes, String> {
private int maxBytes;
@Override public void initialize(MaxBytes annotation) { this.maxBytes = annotation.value(); }
@Override public boolean isValid(String value, ConstraintValidatorContext context) { return value == null || value.getBytes(StandardCharsets.UTF_8).length <= maxBytes; }}$ curl -X POST http://localhost:8080/api/v1/auth/register -H "Content-Type: application/json" -d '{"fullName":"S","email":"sneha-at-example","password":"campus123","phone":"12345"}'
{"type":"https://shoplite.example/problems/validation-failed","title":"Validation failed","status":400,"detail":"The request has 4 invalid fields.","instance":"/api/v1/auth/register","errors":[{"field":"fullName","message":"must be 2-100 characters"},{"field":"email","message":"must be a valid e-mail address"},{"field":"password","message":"must be 15-64 characters"},{"field":"phone","message":"must be 10 digits starting with 6-9"}]}
$ curl -X POST http://localhost:8080/api/v1/auth/register -H "Content-Type: application/json" -d '{}'
{"type":"https://shoplite.example/problems/validation-failed","title":"Validation failed","status":400,"detail":"The request has 3 invalid fields.","instance":"/api/v1/auth/register","errors":[{"field":"fullName","message":"is required"},{"field":"email","message":"is required"},{"field":"password","message":"is required"}]}
$ curl -X POST http://localhost:8080/api/v1/auth/register -H "Content-Type: application/json" --data-binary @ananya.json
(ananya.json holds the password "मेरा पासवर्ड बहुत लंबा और सुरक्षित है": 37 characters, 99 bytes)
{"type":"https://shoplite.example/problems/validation-failed","title":"Validation failed","status":400,"detail":"The request has 1 invalid field.","instance":"/api/v1/auth/register","errors":[{"field":"password","message":"must be at most 72 bytes in UTF-8"}]}What this code does
- One request with four problems gets one answer listing all of them in body order;
campus123fails on length alone, and no rule asks for capitals or symbols. The 37-character Hindi passphrase passes@Size(max = 64)but is 99 bytes, so@MaxBytes(72)rejects it with a clear 400 before BCrypt ever sees it. - The validator counts
getBytes(StandardCharsets.UTF_8).length, the same bytes BCrypt reads.nullis valid here;@NotNullreports a missing password. - curl's
--data-binary @filesends the file's UTF-8 bytes unchanged; typing non-English text straight into a Windows terminal can change it.
Example 3 · Length beats complexity: counting possible passwords
import java.math.BigInteger;import java.util.Locale;
class Policy { final String name; final int symbols; final int length;
Policy(String name, int symbols, int length) { this.name = name; this.symbols = symbols; this.length = length; }
BigInteger guesses() { return BigInteger.valueOf(symbols).pow(length); // every possible password of this shape }}
public class PasswordSpaceDemo {
// Assumed attack speed against a leaked BCrypt (cost 10) table with many graphics cards static final BigInteger GUESSES_PER_SECOND = BigInteger.valueOf(1_000_000); static final BigInteger SECONDS_PER_YEAR = BigInteger.valueOf(365L * 24 * 60 * 60);
public static void main(String[] args) { Policy[] policies = { new Policy("8 chars, upper+lower+digit+symbol (94 symbols)", 94, 8), new Policy("15 chars, lower-case letters and space (27)", 27, 15), new Policy("20 chars, lower-case letters and space (27)", 27, 20), }; for (Policy policy : policies) { BigInteger years = policy.guesses().divide(GUESSES_PER_SECOND).divide(SECONDS_PER_YEAR); System.out.printf(Locale.ROOT, "%-48s %.1e guesses, %,d years%n", policy.name, policy.guesses().doubleValue(), years); } System.out.println("Real people pick 'Password@123', not random symbols: rules do not stop that."); }}8 chars, upper+lower+digit+symbol (94 symbols) 6.1e+15 guesses, 193 years 15 chars, lower-case letters and space (27) 3.0e+21 guesses, 93,680,641 years 20 chars, lower-case letters and space (27) 4.2e+28 guesses, 1,344,214,810,857,946 years Real people pick 'Password@123', not random symbols: rules do not stop that.
What this code does
symbols^lengthcounts every possible password of a shape. Fifteen plain lower-case letters and spaces already give about 500 000 times more than eight characters from all 94 keyboard symbols.- The years assume a fixed attack speed of one million BCrypt guesses per second for the whole table: a simplified model to compare policies, not a promise.
- The counts treat every password as random. People are not random, which is why the real defence is length plus refusing known leaked passwords.
Each extra character multiplies the number of possible passwords, while a symbol rule mostly produces Password@123, which every attacker's list already has. NIST's password guidance (SP 800-63B, 2025 revision) asks for at least 15 characters when the password is the only factor, at least 64 allowed, and no composition rules. A passphrase such as my laptop bag arrives at 7 pm is long, easy to remember and easy to type on a phone.
The byte rule is a small custom constraint, @MaxBytes(72), in com.shoplite.common.validation. Without it, a 37-character Hindi passphrase passes @Size and then hits the encoder's IllegalArgumentException, which the global handler turns into a 500. A blocklist of leaked passwords is a useful next step: Spring Security 7 has a CompromisedPasswordChecker, which the Common Security Mistakes module returns to.
UserService.register: one transaction
@Transactional makes a method run as one database transaction: every change is saved together when the method ends, or all of them are rolled back if it fails.
UserService.register works in a fixed order: normalise the e-mail, save the customer, hash the password, save the account. Example 4 is the service.
Example 4 · src/main/java/com/shoplite/user/UserService.java: customer and account together
Runs in: the shoplite-api Spring Boot project (Spring Boot 4.1, Spring Security 7, MySQL)
package com.shoplite.user;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.customer.Customer;import com.shoplite.customer.CustomerRepository;
/** Accounts: sign-up now; password change and disabling later. */@Servicepublic class UserService {
private static final Logger log = LoggerFactory.getLogger(UserService.class);
private final UserRepository users; private final CustomerRepository customers; private final PasswordEncoder passwordEncoder;
UserService(UserRepository users, CustomerRepository customers, PasswordEncoder passwordEncoder) { this.users = users; this.customers = customers; this.passwordEncoder = passwordEncoder; }
/** Creates the customer row and its CUSTOMER account together: both are saved, or neither. */ @Transactional public UserResponse register(SignUpRequest request) { String email = Emails.normalise(request.email()); Customer customer = customers.save(new Customer(request.fullName(), email, request.phone())); User user = new User(email, passwordEncoder.encode(request.password()), customer, Role.CUSTOMER); users.save(user); log.info("New customer account {} for customer {}", user.getId(), customer.getId()); return UserResponse.from(user); }}Server log:
INFO com.shoplite.user.UserService : New customer account 3 for customer 9
mysql> SELECT user_id, email, password_hash, enabled, customer_id FROM app_user;
user_id email password_hash enabled customer_id
1 admin@shoplite.example {bcrypt}$2a$10$I8Y8ApR1o0xHK5Pjl.psm.6505DA.Vsi5Ou8ydn8H8yISdoNzUbgS 1 NULL
2 asha.rao@example.com {bcrypt}$2a$10$tf367IbGb5L.PfxIpb8Uq.hnqlV4KsvaVloXYH/WlwE5GbZ55aWvG 1 1
3 sneha.patil@example.com {bcrypt}$2a$10$5moS5F2d4t7gk77MBH.OOeL6Y1s0TvxYr6l/eEEZtJkgKiCHA63rO 1 9
mysql> SELECT * FROM user_role ORDER BY user_id;
user_id role
1 ADMIN
2 CUSTOMER
3 CUSTOMERWhat this code does
customers.saveruns first because the account needs the customer's id;users.savethen inserts theapp_userrow and itsuser_rolerow. All three INSERTs commit together at the end ofregister.- The stored value is
{bcrypt}$2a$10$...from the delegating encoder: no plain password anywhere in the table. - This version has no duplicate check yet: the next lesson adds
existsByEmailand the unique-constraint guard to the same method.
One transaction matters because a failure after the customer INSERT would leave a customer with no account: the person cannot sign in, and signing up again fails because the e-mail is taken. With @Transactional, Spring rolls back the customer row too.
The service hashes; the controller never sees the hash and the entity never leaves the service. What can go wrong: calling passwordEncoder.encode twice (once to check, once to save) costs two slow hashes, and hashing in the controller spreads security code across layers.
201 Created with a UserResponse that has no password
Mass assignment is a client setting fields it should not, such as role or enabled, because the request body is bound straight onto an entity. A client that can set any field can make itself an admin.
The endpoint answers 201 Created with a Location header and a UserResponse that has no password field. Example 5 shows a refused attack.
Example 5 · Mass assignment refused, and the new account signs in
Runs in: the shoplite-api Spring Boot project (Spring Boot 4.1, Spring Security 7, MySQL)
// src/main/java/com/shoplite/user/UserResponse.javapackage com.shoplite.user;
import java.util.List;
/** What the API says about an account. There is deliberately no password or hash field. */public record UserResponse(Integer id, String email, String fullName, Integer customerId, List<String> roles) {
static UserResponse from(User user) { List<String> roles = user.getRoles().stream().sorted().map(Role::name).toList(); return new UserResponse(user.getId(), user.getEmail(), user.getCustomer().getFullName(), user.getCustomer().getId(), roles); }}$ curl -X POST http://localhost:8080/api/v1/auth/register -H "Content-Type: application/json" -d '{"fullName":"Hacker","email":"h@example.com","password":"a long enough password","role":"ADMIN"}'
{"type":"https://shoplite.example/problems/malformed-request","title":"Malformed request","status":400,"detail":"The request body is not valid JSON for this endpoint.","instance":"/api/v1/auth/register"}
$ curl -u "sneha.patil@example.com:my laptop bag arrives at 7 pm" http://localhost:8080/api/v1/customers/9
{"id":9,"fullName":"Sneha Patil","email":"sneha.patil@example.com","phone":"9876543209","createdAt":"2026-10-16T13:33:37+05:30"}What this code does
- A body with an extra
rolefield is a 400malformed-request: the contract refuses unknown fields, andSignUpRequesthas no role component to fill anyway. - Sneha signs in with HTTP Basic using the password she chose:
DatabaseUserDetailsServicefinds her row and BCrypt'smatchesaccepts it. UserResponse.fromreads only safe fields. The customer data comes from theCustomerrow, sofullNameis in the response without being stored twice.
UserResponse has id, email, fullName, customerId and roles, so no future change to the entity can leak a hash by accident. The Location header points at the new customer, /api/v1/customers/{id}, as the contract does for every create. The contract also rejects unknown body fields with 400 (fail-on-unknown-properties=true), so a body with "role": "ADMIN" is refused instead of quietly ignored.
The role is always chosen by the server, Role.CUSTOMER in register. Admin accounts are made by another admin or a seed script, never through public sign-up.
Find the bug
Find the sign-up bug
Each snippet leaks data or lets a client choose too much. Tap the wrong line.
The response record.
Round 1 of 3Normalising e-mails before saving and looking up
Normalising an e-mail means turning every way of typing it into one form: trim the spaces and lower-case it, so " Sneha.Patil@Example.com " becomes sneha.patil@example.com.
ShopLite does it in one place, Emails.normalise, and calls it in register and in loadUserByUsername.
package com.shoplite.user;
import java.util.Locale;
/** One rule for e-mail addresses, used both when saving and when looking up. */public final class Emails {
private Emails() { }
/** " Sneha.Patil@Example.COM " becomes "sneha.patil@example.com". */ public static String normalise(String email) { return email == null ? null : email.trim().toLowerCase(Locale.ROOT); }}Example 6 · Lower-case e-mails: trim and Locale.ROOT
import java.util.Locale;
public class EmailCaseDemo {
static String normalise(String email) { return email.trim().toLowerCase(Locale.ROOT); }
// Shows letters outside plain ASCII as \\uXXXX, so the output is the same on every console static String visible(String text) { StringBuilder out = new StringBuilder(); for (char c : text.toCharArray()) { out.append(c < 128 ? String.valueOf(c) : String.format("\\u%04x", (int) c)); } return out.toString(); }
public static void main(String[] args) { String typed = " PRIYA.SHARMA@Example.COM "; String turkishInput = "INDIRA@EXAMPLE.COM";
System.out.println("[" + normalise(typed) + "]"); System.out.println("Same account? " + normalise(typed).equals("priya.sharma@example.com"));
// toLowerCase() without a Locale uses the computer's language settings String turkish = turkishInput.toLowerCase(Locale.forLanguageTag("tr")); System.out.println("Turkish rules: " + visible(turkish) + " same as indira@example.com? " + turkish.equals("indira@example.com")); System.out.println("Locale.ROOT: " + turkishInput.toLowerCase(Locale.ROOT)); }}[priya.sharma@example.com] Same account? true Turkish rules: \u0131nd\u0131ra@example.com same as indira@example.com? false Locale.ROOT: indira@example.com
What this code does
trim()removes the spaces a phone keyboard or a copy-paste adds;toLowerCasemakesPRIYA.SHARMA@Example.COMthe same account aspriya.sharma@example.com.- Under Turkish rules capital
Ibecomes dotlessı(Unicode\u0131, printed as a code so every console shows it), soINDIRAwould be saved as a different address. On a server set to Turkish,toLowerCase()with no argument does exactly that. Locale.ROOTgives the same result on every computer, which is what a lookup key needs.
Both places must use it: if sign-up saves lower case but sign-in looks up exactly what was typed, Sneha.Patil@example.com cannot sign in on a database that compares case-sensitively. MySQL's default collation happens to ignore case, but PostgreSQL does not, and Java's equals never does.
Locale.ROOT matters: toLowerCase() without a locale uses the computer's language, and under Turkish rules I becomes a dotless ı (Example 6). Strictly, the part before @ may be case-sensitive by the e-mail standard; in practice mail providers ignore case, and so do almost all sites.
Next step
Check your understanding
11 quick questions