OTP Authentication in Spring Boot: Complete Guide
🎉 Article Published: 222
if you are not a medium member then Click here to read free
OTP Authentication in Spring Boot: Complete Guide
In this guide, I’ll walk you through implementing OTP (One-Time Password) authentication in a Spring Boot application. We’ll cover both email and SMS-based OTP verification.
Table of Contents
Project Setup
Database Configuration
OTP Service Implementation
Email Service for OTP
SMS Service for OTP (Twilio)
API Endpoints
Security Configuration
Testing the Implementation
Project Setup
First, create a new Spring Boot project with the following dependencies:
<button data-code="
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-data-jpa
mysql
mysql-connector-java
runtime
org.springframework.boot
spring-boot-starter-security
io.jsonwebtoken
jjwt-api
0.11.5
io.jsonwebtoken
jjwt-impl
0.11.5
runtime
io.jsonwebtoken
jjwt-jackson
0.11.5
runtime
org.springframework.boot
spring-boot-starter-mail
com.twilio.sdk
twilio
8.31.1
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-validation
” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
<!-- pom.xml -->
<dependencies>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQL Driver (or your preferred database) -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- Java JWT for token handling -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<!-- Spring Mail for email OTP -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- Twilio for SMS OTP (optional) -->
<dependency>
<groupId>com.twilio.sdk</groupId>
<artifactId>twilio</artifactId>
<version>8.31.1</version>
</dependency>
<!-- Lombok for reducing boilerplate code -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- Validation -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</dependencies>
<!-- pom.xml -->
<dependencies>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQL Driver (or your preferred database) -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- Java JWT for token handling -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<!-- Spring Mail for email OTP -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- Twilio for SMS OTP (optional) -->
<dependency>
<groupId>com.twilio.sdk</groupId>
<artifactId>twilio</artifactId>
<version>8.31.1</version>
</dependency>
<!-- Lombok for reducing boilerplate code -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- Validation -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</dependencies>
Database Configuration
Configure your database in application.properties:
# application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/otp_auth_db?useSSL=false
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
# JWT Configuration
jwt.secret=your-256-bit-secret
jwt.expiration.ms=86400000 # 24 hours
# Email Configuration
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username[email protected]
spring.mail.password=your-email-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
# Twilio Configuration (optional)
twilio.account.sid=your-account-sid
twilio.auth.token=your-auth-token
twilio.phone.number=+1234567890
# application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/otp_auth_db?useSSL=false
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
# JWT Configuration
jwt.secret=your-256-bit-secret
jwt.expiration.ms=86400000 # 24 hours
# Email Configuration
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username[email protected]
spring.mail.password=your-email-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
# Twilio Configuration (optional)
twilio.account.sid=your-account-sid
twilio.auth.token=your-auth-token
twilio.phone.number=+1234567890
Entity Classes
Create the necessary entity classes
<button data-code="// User.java
@Entity
@Table(name = "users")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String email;
@Column(nullable = false)
private String password;
@Column(name = "phone_number", unique = true)
private String phoneNumber;
@Column(name = "is_verified", nullable = false)
private boolean isVerified = false;
@Enumerated(EnumType.STRING)
@Column(nullable = false)
private Role role;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List otps = new ArrayList();
}
// Otp.java
@Entity
@Table(name = "otps")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Otp {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String code;
@Column(nullable = false)
private LocalDateTime createdAt;
@Column(nullable = false)
private LocalDateTime expiresAt;
@Column(nullable = false)
private boolean verified;
@Enumerated(EnumType.STRING)
@Column(nullable = false)
private OtpType type;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
private User user;
}
// Enums
public enum Role {
ROLE_USER,
ROLE_ADMIN
}
public enum OtpType {
EMAIL_VERIFICATION,
PHONE_VERIFICATION,
PASSWORD_RESET
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
// User.java
@Entity
@Table(name = "users")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String email;
@Column(nullable = false)
private String password;
@Column(name = "phone_number", unique = true)
private String phoneNumber;
@Column(name = "is_verified", nullable = false)
private boolean isVerified = false;
@Enumerated(EnumType.STRING)
@Column(nullable = false)
private Role role;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List<Otp> otps = new ArrayList<>();
}
// Otp.java
@Entity
@Table(name = "otps")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Otp {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String code;
@Column(nullable = false)
private LocalDateTime createdAt;
@Column(nullable = false)
private LocalDateTime expiresAt;
@Column(nullable = false)
private boolean verified;
@Enumerated(EnumType.STRING)
@Column(nullable = false)
private OtpType type;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
private User user;
}
// Enums
public enum Role {
ROLE_USER,
ROLE_ADMIN
}
public enum OtpType {
EMAIL_VERIFICATION,
PHONE_VERIFICATION,
PASSWORD_RESET
}
// User.java
@Entity
@Table(name = "users")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String email;
@Column(nullable = false)
private String password;
@Column(name = "phone_number", unique = true)
private String phoneNumber;
@Column(name = "is_verified", nullable = false)
private boolean isVerified = false;
@Enumerated(EnumType.STRING)
@Column(nullable = false)
private Role role;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List<Otp> otps = new ArrayList<>();
}
// Otp.java
@Entity
@Table(name = "otps")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Otp {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String code;
@Column(nullable = false)
private LocalDateTime createdAt;
@Column(nullable = false)
private LocalDateTime expiresAt;
@Column(nullable = false)
private boolean verified;
@Enumerated(EnumType.STRING)
@Column(nullable = false)
private OtpType type;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
private User user;
}
// Enums
public enum Role {
ROLE_USER,
ROLE_ADMIN
}
public enum OtpType {
EMAIL_VERIFICATION,
PHONE_VERIFICATION,
PASSWORD_RESET
}
Repository Interfaces
<button data-code="// UserRepository.java
public interface UserRepository extends JpaRepository {
Optional findByEmail(String email);
Optional findByPhoneNumber(String phoneNumber);
Boolean existsByEmail(String email);
Boolean existsByPhoneNumber(String phoneNumber);
}
// OtpRepository.java
public interface OtpRepository extends JpaRepository {
Optional findByCodeAndUser_IdAndTypeAndVerifiedIsFalseAndExpiresAtAfter(
String code, Long userId, OtpType type, LocalDateTime now);
List findByUser_IdAndVerifiedIsFalseAndExpiresAtBefore(Long userId, LocalDateTime now);
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
// UserRepository.java
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
Optional<User> findByPhoneNumber(String phoneNumber);
Boolean existsByEmail(String email);
Boolean existsByPhoneNumber(String phoneNumber);
}
// OtpRepository.java
public interface OtpRepository extends JpaRepository<Otp, Long> {
Optional<Otp> findByCodeAndUser_IdAndTypeAndVerifiedIsFalseAndExpiresAtAfter(
String code, Long userId, OtpType type, LocalDateTime now);
List<Otp> findByUser_IdAndVerifiedIsFalseAndExpiresAtBefore(Long userId, LocalDateTime now);
}
// UserRepository.java
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
Optional<User> findByPhoneNumber(String phoneNumber);
Boolean existsByEmail(String email);
Boolean existsByPhoneNumber(String phoneNumber);
}
// OtpRepository.java
public interface OtpRepository extends JpaRepository<Otp, Long> {
Optional<Otp> findByCodeAndUser_IdAndTypeAndVerifiedIsFalseAndExpiresAtAfter(
String code, Long userId, OtpType type, LocalDateTime now);
List<Otp> findByUser_IdAndVerifiedIsFalseAndExpiresAtBefore(Long userId, LocalDateTime now);
}
OTP Service Implementation
<button data-code="// OtpService.java
@Service
@RequiredArgsConstructor
public class OtpService {
private static final int OTP_LENGTH = 6;
private static final int OTP_EXPIRATION_MINUTES = 5;
private final OtpRepository otpRepository;
public String generateOtp() {
// Generate a 6-digit numeric OTP
Random random = new Random();
StringBuilder otp = new StringBuilder();
for (int i = 0; i < OTP_LENGTH; i++) {
otp.append(random.nextInt(10));
}
return otp.toString();
}
public Otp createOtp(User user, OtpType type) {
// Clean up expired OTPs for this user
cleanUpExpiredOtps(user.getId());
// Generate and save new OTP
String code = generateOtp();
LocalDateTime now = LocalDateTime.now();
LocalDateTime expiresAt = now.plusMinutes(OTP_EXPIRATION_MINUTES);
Otp otp = new Otp();
otp.setCode(code);
otp.setCreatedAt(now);
otp.setExpiresAt(expiresAt);
otp.setVerified(false);
otp.setType(type);
otp.setUser(user);
return otpRepository.save(otp);
}
public boolean validateOtp(User user, String code, OtpType type) {
LocalDateTime now = LocalDateTime.now();
Optional otpOptional = otpRepository.findByCodeAndUser_IdAndTypeAndVerifiedIsFalseAndExpiresAtAfter(
code, user.getId(), type, now);
if (otpOptional.isPresent()) {
Otp otp = otpOptional.get();
otp.setVerified(true);
otpRepository.save(otp);
return true;
}
return false;
}
private void cleanUpExpiredOtps(Long userId) {
LocalDateTime now = LocalDateTime.now();
List expiredOtps = otpRepository.findByUser_IdAndVerifiedIsFalseAndExpiresAtBefore(userId, now);
otpRepository.deleteAll(expiredOtps);
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
// OtpService.java
@Service
@RequiredArgsConstructor
public class OtpService {
private static final int OTP_LENGTH = 6;
private static final int OTP_EXPIRATION_MINUTES = 5;
private final OtpRepository otpRepository;
public String generateOtp() {
// Generate a 6-digit numeric OTP
Random random = new Random();
StringBuilder otp = new StringBuilder();
for (int i = 0; i < OTP_LENGTH; i++) {
otp.append(random.nextInt(10));
}
return otp.toString();
}
public Otp createOtp(User user, OtpType type) {
// Clean up expired OTPs for this user
cleanUpExpiredOtps(user.getId());
// Generate and save new OTP
String code = generateOtp();
LocalDateTime now = LocalDateTime.now();
LocalDateTime expiresAt = now.plusMinutes(OTP_EXPIRATION_MINUTES);
Otp otp = new Otp();
otp.setCode(code);
otp.setCreatedAt(now);
otp.setExpiresAt(expiresAt);
otp.setVerified(false);
otp.setType(type);
otp.setUser(user);
return otpRepository.save(otp);
}
public boolean validateOtp(User user, String code, OtpType type) {
LocalDateTime now = LocalDateTime.now();
Optional<Otp> otpOptional = otpRepository.findByCodeAndUser_IdAndTypeAndVerifiedIsFalseAndExpiresAtAfter(
code, user.getId(), type, now);
if (otpOptional.isPresent()) {
Otp otp = otpOptional.get();
otp.setVerified(true);
otpRepository.save(otp);
return true;
}
return false;
}
private void cleanUpExpiredOtps(Long userId) {
LocalDateTime now = LocalDateTime.now();
List<Otp> expiredOtps = otpRepository.findByUser_IdAndVerifiedIsFalseAndExpiresAtBefore(userId, now);
otpRepository.deleteAll(expiredOtps);
}
}
// OtpService.java
@Service
@RequiredArgsConstructor
public class OtpService {
private static final int OTP_LENGTH = 6;
private static final int OTP_EXPIRATION_MINUTES = 5;
private final OtpRepository otpRepository;
public String generateOtp() {
// Generate a 6-digit numeric OTP
Random random = new Random();
StringBuilder otp = new StringBuilder();
for (int i = 0; i < OTP_LENGTH; i++) {
otp.append(random.nextInt(10));
}
return otp.toString();
}
public Otp createOtp(User user, OtpType type) {
// Clean up expired OTPs for this user
cleanUpExpiredOtps(user.getId());
// Generate and save new OTP
String code = generateOtp();
LocalDateTime now = LocalDateTime.now();
LocalDateTime expiresAt = now.plusMinutes(OTP_EXPIRATION_MINUTES);
Otp otp = new Otp();
otp.setCode(code);
otp.setCreatedAt(now);
otp.setExpiresAt(expiresAt);
otp.setVerified(false);
otp.setType(type);
otp.setUser(user);
return otpRepository.save(otp);
}
public boolean validateOtp(User user, String code, OtpType type) {
LocalDateTime now = LocalDateTime.now();
Optional<Otp> otpOptional = otpRepository.findByCodeAndUser_IdAndTypeAndVerifiedIsFalseAndExpiresAtAfter(
code, user.getId(), type, now);
if (otpOptional.isPresent()) {
Otp otp = otpOptional.get();
otp.setVerified(true);
otpRepository.save(otp);
return true;
}
return false;
}
private void cleanUpExpiredOtps(Long userId) {
LocalDateTime now = LocalDateTime.now();
List<Otp> expiredOtps = otpRepository.findByUser_IdAndVerifiedIsFalseAndExpiresAtBefore(userId, now);
otpRepository.deleteAll(expiredOtps);
}
}
Email Service for OTP
// EmailService.java
@Service
@RequiredArgsConstructor
public class EmailService {
private final JavaMailSender mailSender;
private final Environment env;
public void sendOtpEmail(String toEmail, String otpCode) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(env.getProperty("spring.mail.username"));
message.setTo(toEmail);
message.setSubject("Your OTP Code");
message.setText("Your OTP code is: " + otpCode + "nThis code will expire in 5 minutes.");
mailSender.send(message);
}
}
// EmailService.java
@Service
@RequiredArgsConstructor
public class EmailService {
private final JavaMailSender mailSender;
private final Environment env;
public void sendOtpEmail(String toEmail, String otpCode) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(env.getProperty("spring.mail.username"));
message.setTo(toEmail);
message.setSubject("Your OTP Code");
message.setText("Your OTP code is: " + otpCode + "nThis code will expire in 5 minutes.");
mailSender.send(message);
}
}
SMS Service for OTP (Twilio)
// SmsService.java
@Service
@RequiredArgsConstructor
public class SmsService {
private final Environment env;
public void sendOtpSms(String phoneNumber, String otpCode) {
String accountSid = env.getProperty("twilio.account.sid"));
String authToken = env.getProperty("twilio.auth.token"));
String twilioNumber = env.getProperty("twilio.phone.number"));
Twilio.init(accountSid, authToken);
Message.creator(
new PhoneNumber(phoneNumber),
new PhoneNumber(twilioNumber),
"Your OTP code is: " + otpCode + ". This code will expire in 5 minutes."
).create();
}
}
// SmsService.java
@Service
@RequiredArgsConstructor
public class SmsService {
private final Environment env;
public void sendOtpSms(String phoneNumber, String otpCode) {
String accountSid = env.getProperty("twilio.account.sid"));
String authToken = env.getProperty("twilio.auth.token"));
String twilioNumber = env.getProperty("twilio.phone.number"));
Twilio.init(accountSid, authToken);
Message.creator(
new PhoneNumber(phoneNumber),
new PhoneNumber(twilioNumber),
"Your OTP code is: " + otpCode + ". This code will expire in 5 minutes."
).create();
}
}
User Service
new RuntimeException("User not found"));
Otp otp = otpService.createOtp(user, OtpType.EMAIL_VERIFICATION);
emailService.sendOtpEmail(user.getEmail(), otp.getCode());
}
public void initiatePhoneVerification(Long userId) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new RuntimeException("User not found"));
if (user.getPhoneNumber() == null) {
throw new RuntimeException("Phone number not set");
}
Otp otp = otpService.createOtp(user, OtpType.PHONE_VERIFICATION);
smsService.sendOtpSms(user.getPhoneNumber(), otp.getCode());
}
public boolean verifyEmailOtp(Long userId, String code) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new RuntimeException("User not found"));
boolean isValid = otpService.validateOtp(user, code, OtpType.EMAIL_VERIFICATION);
if (isValid) {
user.setVerified(true);
userRepository.save(user);
}
return isValid;
}
public boolean verifyPhoneOtp(Long userId, String code) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new RuntimeException("User not found"));
return otpService.validateOtp(user, code, OtpType.PHONE_VERIFICATION);
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
// UserService.java
@Service
@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final OtpService otpService;
private final EmailService emailService;
private final SmsService smsService;
public User registerUser(UserRegistrationRequest request) {
if (userRepository.existsByEmail(request.getEmail())) {
throw new RuntimeException("Email already in use");
}
User user = new User();
user.setEmail(request.getEmail());
user.setPassword(passwordEncoder.encode(request.getPassword()));
user.setPhoneNumber(request.getPhoneNumber());
user.setRole(Role.ROLE_USER);
user.setVerified(false);
return userRepository.save(user);
}
public void initiateEmailVerification(String email) {
User user = userRepository.findByEmail(email)
.orElseThrow(() -> new RuntimeException("User not found"));
Otp otp = otpService.createOtp(user, OtpType.EMAIL_VERIFICATION);
emailService.sendOtpEmail(user.getEmail(), otp.getCode());
}
public void initiatePhoneVerification(Long userId) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new RuntimeException("User not found"));
if (user.getPhoneNumber() == null) {
throw new RuntimeException("Phone number not set");
}
Otp otp = otpService.createOtp(user, OtpType.PHONE_VERIFICATION);
smsService.sendOtpSms(user.getPhoneNumber(), otp.getCode());
}
public boolean verifyEmailOtp(Long userId, String code) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new RuntimeException("User not found"));
boolean isValid = otpService.validateOtp(user, code, OtpType.EMAIL_VERIFICATION);
if (isValid) {
user.setVerified(true);
userRepository.save(user);
}
return isValid;
}
public boolean verifyPhoneOtp(Long userId, String code) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new RuntimeException("User not found"));
return otpService.validateOtp(user, code, OtpType.PHONE_VERIFICATION);
}
}
// UserService.java
@Service
@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final OtpService otpService;
private final EmailService emailService;
private final SmsService smsService;
public User registerUser(UserRegistrationRequest request) {
if (userRepository.existsByEmail(request.getEmail())) {
throw new RuntimeException("Email already in use");
}
User user = new User();
user.setEmail(request.getEmail());
user.setPassword(passwordEncoder.encode(request.getPassword()));
user.setPhoneNumber(request.getPhoneNumber());
user.setRole(Role.ROLE_USER);
user.setVerified(false);
return userRepository.save(user);
}
public void initiateEmailVerification(String email) {
User user = userRepository.findByEmail(email)
.orElseThrow(() -> new RuntimeException("User not found"));
Otp otp = otpService.createOtp(user, OtpType.EMAIL_VERIFICATION);
emailService.sendOtpEmail(user.getEmail(), otp.getCode());
}
public void initiatePhoneVerification(Long userId) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new RuntimeException("User not found"));
if (user.getPhoneNumber() == null) {
throw new RuntimeException("Phone number not set");
}
Otp otp = otpService.createOtp(user, OtpType.PHONE_VERIFICATION);
smsService.sendOtpSms(user.getPhoneNumber(), otp.getCode());
}
public boolean verifyEmailOtp(Long userId, String code) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new RuntimeException("User not found"));
boolean isValid = otpService.validateOtp(user, code, OtpType.EMAIL_VERIFICATION);
if (isValid) {
user.setVerified(true);
userRepository.save(user);
}
return isValid;
}
public boolean verifyPhoneOtp(Long userId, String code) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new RuntimeException("User not found"));
return otpService.validateOtp(user, code, OtpType.PHONE_VERIFICATION);
}
}
JWT Utility Class
<button data-code="// JwtTokenUtil.java
@Component
public class JwtTokenUtil {
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expiration.ms}")
private long expirationMs;
public String generateToken(UserDetails userDetails) {
Map claims = new HashMap();
return Jwts.builder()
.setClaims(claims)
.setSubject(userDetails.getUsername())
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + expirationMs))
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
public String getUsernameFromToken(String token) {
return Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody()
.getSubject();
}
public boolean validateToken(String token, UserDetails userDetails) {
final String username = getUsernameFromToken(token);
return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
}
private boolean isTokenExpired(String token) {
final Date expiration = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody()
.getExpiration();
return expiration.before(new Date());
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
// JwtTokenUtil.java
@Component
public class JwtTokenUtil {
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expiration.ms}")
private long expirationMs;
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
return Jwts.builder()
.setClaims(claims)
.setSubject(userDetails.getUsername())
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + expirationMs))
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
public String getUsernameFromToken(String token) {
return Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody()
.getSubject();
}
public boolean validateToken(String token, UserDetails userDetails) {
final String username = getUsernameFromToken(token);
return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
}
private boolean isTokenExpired(String token) {
final Date expiration = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody()
.getExpiration();
return expiration.before(new Date());
}
}
// JwtTokenUtil.java
@Component
public class JwtTokenUtil {
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expiration.ms}")
private long expirationMs;
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
return Jwts.builder()
.setClaims(claims)
.setSubject(userDetails.getUsername())
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + expirationMs))
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
public String getUsernameFromToken(String token) {
return Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody()
.getSubject();
}
public boolean validateToken(String token, UserDetails userDetails) {
final String username = getUsernameFromToken(token);
return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
}
private boolean isTokenExpired(String token) {
final Date expiration = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody()
.getExpiration();
return expiration.before(new Date());
}
}
Security Configuration
auth
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/api/public/**").permitAll()
.anyRequest().authenticated()
);
http.addFilterBefore(jwtRequestFilter(), UsernamePasswordAuthenticationFilter.class);
return http.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public JwtRequestFilter jwtRequestFilter() {
return new JwtRequestFilter(userDetailsService, jwtTokenUtil);
}
}
// JwtRequestFilter.java
@Component
@RequiredArgsConstructor
public class JwtRequestFilter extends OncePerRequestFilter {
private final UserDetailsService userDetailsService;
private final JwtTokenUtil jwtTokenUtil;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
final String requestTokenHeader = request.getHeader("Authorization");
String username = null;
String jwtToken = null;
if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
jwtToken = requestTokenHeader.substring(7);
try {
username = jwtTokenUtil.getUsernameFromToken(jwtToken);
} catch (IllegalArgumentException e) {
logger.error("Unable to get JWT Token");
} catch (ExpiredJwtException e) {
logger.error("JWT Token has expired");
}
}
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}
}
chain.doFilter(request, response);
}
}
// JwtAuthenticationEntryPoint.java
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
// SecurityConfig.java
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private final UserDetailsService userDetailsService;
private final JwtTokenUtil jwtTokenUtil;
private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/api/public/**").permitAll()
.anyRequest().authenticated()
);
http.addFilterBefore(jwtRequestFilter(), UsernamePasswordAuthenticationFilter.class);
return http.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public JwtRequestFilter jwtRequestFilter() {
return new JwtRequestFilter(userDetailsService, jwtTokenUtil);
}
}
// JwtRequestFilter.java
@Component
@RequiredArgsConstructor
public class JwtRequestFilter extends OncePerRequestFilter {
private final UserDetailsService userDetailsService;
private final JwtTokenUtil jwtTokenUtil;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
final String requestTokenHeader = request.getHeader("Authorization");
String username = null;
String jwtToken = null;
if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
jwtToken = requestTokenHeader.substring(7);
try {
username = jwtTokenUtil.getUsernameFromToken(jwtToken);
} catch (IllegalArgumentException e) {
logger.error("Unable to get JWT Token");
} catch (ExpiredJwtException e) {
logger.error("JWT Token has expired");
}
}
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}
}
chain.doFilter(request, response);
}
}
// JwtAuthenticationEntryPoint.java
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
}
// SecurityConfig.java
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private final UserDetailsService userDetailsService;
private final JwtTokenUtil jwtTokenUtil;
private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/api/public/**").permitAll()
.anyRequest().authenticated()
);
http.addFilterBefore(jwtRequestFilter(), UsernamePasswordAuthenticationFilter.class);
return http.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public JwtRequestFilter jwtRequestFilter() {
return new JwtRequestFilter(userDetailsService, jwtTokenUtil);
}
}
// JwtRequestFilter.java
@Component
@RequiredArgsConstructor
public class JwtRequestFilter extends OncePerRequestFilter {
private final UserDetailsService userDetailsService;
private final JwtTokenUtil jwtTokenUtil;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
final String requestTokenHeader = request.getHeader("Authorization");
String username = null;
String jwtToken = null;
if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
jwtToken = requestTokenHeader.substring(7);
try {
username = jwtTokenUtil.getUsernameFromToken(jwtToken);
} catch (IllegalArgumentException e) {
logger.error("Unable to get JWT Token");
} catch (ExpiredJwtException e) {
logger.error("JWT Token has expired");
}
}
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}
}
chain.doFilter(request, response);
}
}
// JwtAuthenticationEntryPoint.java
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
}
DTO Classes
// AuthRequest.java
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AuthRequest {
@NotBlank
private String email;
@NotBlank
private String password;
}
// AuthResponse.java
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AuthResponse {
private String token;
private Long userId;
private String email;
private boolean verified;
}
// UserRegistrationRequest.java
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserRegistrationRequest {
@NotBlank
@Email
private String email;
@NotBlank
@Size(min = 6, max = 20)
private String password;
private String phoneNumber;
}
// OtpVerificationRequest.java
@Data
@AllArgsConstructor
@NoArgsConstructor
public class OtpVerificationRequest {
@NotBlank
private String code;
private Long userId;
}
// AuthRequest.java
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AuthRequest {
@NotBlank
private String email;
@NotBlank
private String password;
}
// AuthResponse.java
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AuthResponse {
private String token;
private Long userId;
private String email;
private boolean verified;
}
// UserRegistrationRequest.java
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserRegistrationRequest {
@NotBlank
@Email
private String email;
@NotBlank
@Size(min = 6, max = 20)
private String password;
private String phoneNumber;
}
// OtpVerificationRequest.java
@Data
@AllArgsConstructor
@NoArgsConstructor
public class OtpVerificationRequest {
@NotBlank
private String code;
private Long userId;
}
Controller Classes
<button data-code="// AuthController.java
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {
private final AuthenticationManager authenticationManager;
private final JwtTokenUtil jwtTokenUtil;
private final UserDetailsService userDetailsService;
private final UserService userService;
@PostMapping("/register")
public ResponseEntity registerUser(@RequestBody UserRegistrationRequest request) {
User user = userService.registerUser(request);
// Initiate email verification
userService.initiateEmailVerification(user.getEmail());
return ResponseEntity.ok("User registered successfully. Verification OTP sent to email.");
}
@PostMapping("/login")
public ResponseEntity createAuthenticationToken(@RequestBody AuthRequest request) throws Exception {
try {
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(request.getEmail(), request.getPassword())
);
} catch (BadCredentialsException e) {
throw new Exception("Incorrect username or password", e);
}
final UserDetails userDetails = userDetailsService.loadUserByUsername(request.getEmail());
final String token = jwtTokenUtil.generateToken(userDetails);
User user = userService.getUserByEmail(request.getEmail());
return ResponseEntity.ok(new AuthResponse(token, user.getId(), user.getEmail(), user.isVerified()));
}
@PostMapping("/verify-email")
public ResponseEntity verifyEmail(@RequestBody OtpVerificationRequest request) {
boolean isValid = userService.verifyEmailOtp(request.getUserId(), request.getCode());
if (isValid) {
return ResponseEntity.ok("Email verified successfully");
} else {
return ResponseEntity.badRequest().body("Invalid or expired OTP");
}
}
@PostMapping("/resend-email-otp")
public ResponseEntity resendEmailOtp(@RequestParam String email) {
userService.initiateEmailVerification(email);
return ResponseEntity.ok("OTP resent successfully");
}
@PostMapping("/verify-phone")
public ResponseEntity verifyPhone(@RequestBody OtpVerificationRequest request) {
boolean isValid = userService.verifyPhoneOtp(request.getUserId(), request.getCode());
if (isValid) {
return ResponseEntity.ok("Phone verified successfully");
} else {
return ResponseEntity.badRequest().body("Invalid or expired OTP");
}
}
@PostMapping("/initiate-phone-verification")
public ResponseEntity initiatePhoneVerification(@RequestParam Long userId) {
userService.initiatePhoneVerification(userId);
return ResponseEntity.ok("OTP sent to phone number");
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
// AuthController.java
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {
private final AuthenticationManager authenticationManager;
private final JwtTokenUtil jwtTokenUtil;
private final UserDetailsService userDetailsService;
private final UserService userService;
@PostMapping("/register")
public ResponseEntity<?> registerUser(@RequestBody UserRegistrationRequest request) {
User user = userService.registerUser(request);
// Initiate email verification
userService.initiateEmailVerification(user.getEmail());
return ResponseEntity.ok("User registered successfully. Verification OTP sent to email.");
}
@PostMapping("/login")
public ResponseEntity<?> createAuthenticationToken(@RequestBody AuthRequest request) throws Exception {
try {
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(request.getEmail(), request.getPassword())
);
} catch (BadCredentialsException e) {
throw new Exception("Incorrect username or password", e);
}
final UserDetails userDetails = userDetailsService.loadUserByUsername(request.getEmail());
final String token = jwtTokenUtil.generateToken(userDetails);
User user = userService.getUserByEmail(request.getEmail());
return ResponseEntity.ok(new AuthResponse(token, user.getId(), user.getEmail(), user.isVerified()));
}
@PostMapping("/verify-email")
public ResponseEntity<?> verifyEmail(@RequestBody OtpVerificationRequest request) {
boolean isValid = userService.verifyEmailOtp(request.getUserId(), request.getCode());
if (isValid) {
return ResponseEntity.ok("Email verified successfully");
} else {
return ResponseEntity.badRequest().body("Invalid or expired OTP");
}
}
@PostMapping("/resend-email-otp")
public ResponseEntity<?> resendEmailOtp(@RequestParam String email) {
userService.initiateEmailVerification(email);
return ResponseEntity.ok("OTP resent successfully");
}
@PostMapping("/verify-phone")
public ResponseEntity<?> verifyPhone(@RequestBody OtpVerificationRequest request) {
boolean isValid = userService.verifyPhoneOtp(request.getUserId(), request.getCode());
if (isValid) {
return ResponseEntity.ok("Phone verified successfully");
} else {
return ResponseEntity.badRequest().body("Invalid or expired OTP");
}
}
@PostMapping("/initiate-phone-verification")
public ResponseEntity<?> initiatePhoneVerification(@RequestParam Long userId) {
userService.initiatePhoneVerification(userId);
return ResponseEntity.ok("OTP sent to phone number");
}
}
// AuthController.java
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {
private final AuthenticationManager authenticationManager;
private final JwtTokenUtil jwtTokenUtil;
private final UserDetailsService userDetailsService;
private final UserService userService;
@PostMapping("/register")
public ResponseEntity<?> registerUser(@RequestBody UserRegistrationRequest request) {
User user = userService.registerUser(request);
// Initiate email verification
userService.initiateEmailVerification(user.getEmail());
return ResponseEntity.ok("User registered successfully. Verification OTP sent to email.");
}
@PostMapping("/login")
public ResponseEntity<?> createAuthenticationToken(@RequestBody AuthRequest request) throws Exception {
try {
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(request.getEmail(), request.getPassword())
);
} catch (BadCredentialsException e) {
throw new Exception("Incorrect username or password", e);
}
final UserDetails userDetails = userDetailsService.loadUserByUsername(request.getEmail());
final String token = jwtTokenUtil.generateToken(userDetails);
User user = userService.getUserByEmail(request.getEmail());
return ResponseEntity.ok(new AuthResponse(token, user.getId(), user.getEmail(), user.isVerified()));
}
@PostMapping("/verify-email")
public ResponseEntity<?> verifyEmail(@RequestBody OtpVerificationRequest request) {
boolean isValid = userService.verifyEmailOtp(request.getUserId(), request.getCode());
if (isValid) {
return ResponseEntity.ok("Email verified successfully");
} else {
return ResponseEntity.badRequest().body("Invalid or expired OTP");
}
}
@PostMapping("/resend-email-otp")
public ResponseEntity<?> resendEmailOtp(@RequestParam String email) {
userService.initiateEmailVerification(email);
return ResponseEntity.ok("OTP resent successfully");
}
@PostMapping("/verify-phone")
public ResponseEntity<?> verifyPhone(@RequestBody OtpVerificationRequest request) {
boolean isValid = userService.verifyPhoneOtp(request.getUserId(), request.getCode());
if (isValid) {
return ResponseEntity.ok("Phone verified successfully");
} else {
return ResponseEntity.badRequest().body("Invalid or expired OTP");
}
}
@PostMapping("/initiate-phone-verification")
public ResponseEntity<?> initiatePhoneVerification(@RequestParam Long userId) {
userService.initiatePhoneVerification(userId);
return ResponseEntity.ok("OTP sent to phone number");
}
}
Testing the Implementation
You can test the implementation using Postman or cURL:
- Register a new user
curl -X POST http://localhost:8080/api/auth/register
-H "Content-Type: application/json"
-d '{
"email": "[email protected]",
"password": "password123",
"phoneNumber": "+1234567890"
}'
curl -X POST http://localhost:8080/api/auth/register
-H "Content-Type: application/json"
-d '{
"email": "[email protected]",
"password": "password123",
"phoneNumber": "+1234567890"
}'
Verify email with OTP:`
`curl -X POST http://localhost:8080/api/auth/verify-email
-H "Content-Type: application/json"
-d '{
"userId": 1,
"code": "123456"
}'
`curl -X POST http://localhost:8080/api/auth/verify-email
-H "Content-Type: application/json"
-d '{
"userId": 1,
"code": "123456"
}'
Login:
curl -X POST http://localhost:8080/api/auth/login
-H "Content-Type: application/json"
-d '{
"email": "[email protected]",
"password": "password123"
}'
curl -X POST http://localhost:8080/api/auth/login
-H "Content-Type: application/json"
-d '{
"email": "[email protected]",
"password": "password123"
}'
Initiate phone verification:
curl -X POST http://localhost:8080/api/auth/initiate-phone-verification
-H "Content-Type: application/json"
-d '{
"userId": 1
}'
curl -X POST http://localhost:8080/api/auth/initiate-phone-verification
-H "Content-Type: application/json"
-d '{
"userId": 1
}'
Verify phone with OTP
curl -X POST http://localhost:8080/api/auth/verify-phone
-H "Content-Type: application/json"
-d '{
"userId": 1,
"code": "654321"
}'
curl -X POST http://localhost:8080/api/auth/verify-phone
-H "Content-Type: application/json"
-d '{
"userId": 1,
"code": "654321"
}'
Conclusion
This implementation provides a complete OTP authentication system in Spring Boot with:
- User registration with email and phone number
- Email verification via OTP
- Phone number verification via OTP (SMS)
- JWT-based authentication for secured endpoints
- Proper error handling and validation
You can extend this further by:
- Adding password reset functionality with OTP
- Implementing rate limiting for OTP requests
- Adding more security features like IP-based restrictions
- Implementing a frontend to consume these APIs
Remember to secure your email and SMS credentials properly in production and consider using environment variables for sensitive configuration.
Thank You for Reading!
✅ “Follow me on Medium to never miss an update!”


