<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Eliud Githuku</title>
    <description>The latest articles on DEV Community by Eliud Githuku (@dev_eliud).</description>
    <link>https://dev.to/dev_eliud</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1907015%2F3bf3a206-1a32-47b0-9573-053bcd280174.jpg</url>
      <title>DEV Community: Eliud Githuku</title>
      <link>https://dev.to/dev_eliud</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/dev_eliud"/>
    <language>en</language>
    <item>
      <title>Implementing Email Code Verification in Java Spring Boot</title>
      <dc:creator>Eliud Githuku</dc:creator>
      <pubDate>Fri, 09 Aug 2024 15:29:01 +0000</pubDate>
      <link>https://dev.to/dev_eliud/implementing-email-code-verification-in-java-spring-boot-2c18</link>
      <guid>https://dev.to/dev_eliud/implementing-email-code-verification-in-java-spring-boot-2c18</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Email verification is a critical component in many applications, especially during user registration, password recovery, and other security-sensitive processes. Verifying a user's email ensures that they are legitimate and helps protect against fraudulent activities. In this blog, we will walk through how to implement email code verification in a Spring Boot application. We will explore use cases, the structure of the verification code (numbers, letters, or a combination), and how to test the implementation to ensure reliability.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prerequisites&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Before we dive into the implementation, make sure you have the following:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Basic knowledge of Java and Spring Boot.&lt;/li&gt;
&lt;li&gt;A working Spring Boot project set up with the following dependencies:

&lt;ul&gt;
&lt;li&gt;Spring Web&lt;/li&gt;
&lt;li&gt;Spring Security&lt;/li&gt;
&lt;li&gt;Spring Data JPA&lt;/li&gt;
&lt;li&gt;Thymeleaf (optional for email templates)&lt;/li&gt;
&lt;li&gt;JavaMailSender for sending emails&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;An SMTP server for sending emails (e.g., Gmail SMTP).&lt;/li&gt;
&lt;li&gt;Basic understanding of unit and integration testing in Spring Boot.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Setting Up the Project&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Start by creating a new Spring Boot project or using an existing one. Add the necessary dependencies in your &lt;code&gt;pom.xml&lt;/code&gt; or &lt;code&gt;build.gradle&lt;/code&gt; file.&lt;/p&gt;

&lt;p&gt;For Maven:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;dependencies&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;spring-boot-starter-web&amp;lt;/artifactId&amp;gt;
    &amp;lt;/dependency&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;spring-boot-starter-security&amp;lt;/artifactId&amp;gt;
    &amp;lt;/dependency&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;spring-boot-starter-data-jpa&amp;lt;/artifactId&amp;gt;
    &amp;lt;/dependency&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;spring-boot-starter-mail&amp;lt;/artifactId&amp;gt;
    &amp;lt;/dependency&amp;gt;
&amp;lt;/dependencies&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 2: Create the Verification Code Generator&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A good verification code should be unique, unpredictable, and secure. You can choose to generate a code consisting of numbers, letters, or a combination of both. Here's a simple implementation using a random combination of letters and numbers:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import java.security.SecureRandom;

public class VerificationCodeGenerator {
    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    private static final int CODE_LENGTH = 6;
    private static final SecureRandom random = new SecureRandom();

    public static String generateVerificationCode() {
        StringBuilder code = new StringBuilder(CODE_LENGTH);
        for (int i = 0; i &amp;lt; CODE_LENGTH; i++) {
            code.append(CHARACTERS.charAt(random.nextInt(CHARACTERS.length())));
        }
        return code.toString();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 3: Send the Verification Email&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Next, you need to send the verification code to the user's email. Use the &lt;code&gt;JavaMailSender&lt;/code&gt; to achieve this. Create a service that will handle email sending:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class EmailService {

    @Autowired
    private JavaMailSender mailSender;

    public void sendVerificationEmail(String toEmail, String verificationCode) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(toEmail);
        message.setSubject("Email Verification Code");
        message.setText("Your verification code is: " + verificationCode);
        mailSender.send(message);
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 4: Store the Verification Code&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Store the verification code in the database associated with the user. This helps in verifying the code later when the user submits it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import javax.persistence.*;

@Entity
public class UserVerification {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String email;

    @Column(nullable = false)
    private String verificationCode;

    // Getters and Setters
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Create a repository interface for storing the verification data:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import org.springframework.data.jpa.repository.JpaRepository;

public interface UserVerificationRepository extends JpaRepository&amp;lt;UserVerification, Long&amp;gt; {
    UserVerification findByEmail(String email);
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 5: Verify the Code&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When the user submits the verification code, you need to validate it against the code stored in the database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class VerificationService {

    @Autowired
    private UserVerificationRepository verificationRepository;

    public boolean verifyCode(String email, String code) {
        UserVerification userVerification = verificationRepository.findByEmail(email);
        if (userVerification != null &amp;amp;&amp;amp; userVerification.getVerificationCode().equals(code)) {
            // Verification successful
            return true;
        }
        // Verification failed
        return false;
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 6: Testing the Implementation&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It's essential to test your implementation to ensure that it works as expected. Create unit tests to validate the verification code generation and the email sending process. You can also write integration tests to ensure that the entire flow works smoothly.&lt;/p&gt;

&lt;p&gt;Here’s an example of a simple test for the code generator:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;

public class VerificationCodeGeneratorTest {

    @Test
    public void testGenerateVerificationCode() {
        String code = VerificationCodeGenerator.generateVerificationCode();
        assertNotNull(code);
        assertEquals(6, code.length());
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For testing the email service, you might want to use mocks:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.SimpleMailMessage;

public class EmailServiceTest {

    @Test
    public void testSendVerificationEmail() {
        JavaMailSender mailSender = mock(JavaMailSender.class);
        EmailService emailService = new EmailService();
        emailService.mailSender = mailSender;

        String email = "user@example.com";
        String code = "ABC123";

        emailService.sendVerificationEmail(email, code);

        verify(mailSender, times(1)).send(any(SimpleMailMessage.class));
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Implementing email code verification in your Spring Boot application is a crucial step to secure user authentication and sensitive processes. By following the steps outlined in this blog, you can create a robust and reliable email verification system. Don't forget to test your implementation thoroughly to ensure it performs as expected under different scenarios. Whether you choose to use numeric codes, alphabetic characters, or a combination of both, the key is to make the verification process secure and user-friendly.&lt;/p&gt;

</description>
      <category>springboot</category>
      <category>springsecurity</category>
      <category>jwt</category>
      <category>backenddevelopment</category>
    </item>
  </channel>
</rss>
