Spring Boot Login example
Tags: spring, webdev, java, todayilearned
Published: 2021-12-15 03:01:00

In this tutorial, we're gonna build a Spring Boot Login and Registration example (Rest API) that supports JWT with HttpOnly Cookies. You'll know:
<ul>
	<li>Appropriate Flow for User Login and Registration with JWT and Cookies</li>
	<li>Spring Boot Rest Api Architecture with Spring Security</li>
	<li>How to configure Spring Security to work with JWT</li>
	<li>How to define Data Models and association for Authentication and Authorization</li>
	<li>Way to use Spring Data JPA to interact with MySQL Database</li>
</ul>

Full Article: [Spring Boot Login example with JWT and MySQL](https://www.bezkoder.com/spring-boot-login-example-mysql/)

<h2><span id="Overview">Overview of Spring Boot Login example</span></h2>
We will build a Spring Boot application in that:
<ul>
    	<li>User can signup new account (registration), or login with username & password.</li>
    	<li>By User's role (admin, moderator, user), we authorize the User to access resources.</li>
</ul>

These are APIs that we need to provide:
<div class="table-responsive">
<table class="table table-hover  table table-hover" width="100%">
<thead>
<tr>
<th>Methods</th>
<th>Urls</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>POST</td>
<td>/api/auth/signup</td>
<td>signup new account</td>
</tr>
<tr>
<td>POST</td>
<td>/api/auth/signin</td>
<td>login an account</td>
</tr>
<tr>
<td>POST</td>
<td>/api/auth/signout</td>
<td>logout the account</td>
</tr>
<tr>
<td>GET</td>
<td>/api/test/all</td>
<td>retrieve public content</td>
</tr>
<tr>
<td>GET</td>
<td>/api/test/user</td>
<td>access User's content</td>
</tr>
<tr>
<td>GET</td>
<td>/api/test/mod</td>
<td>access Moderator's content</td>
</tr>
<tr>
<td>GET</td>
<td>/api/test/admin</td>
<td>access Admin's content</td>
</tr>
</tbody>
</table>
</div>

The database we will use is MySQL by configuring project dependency & datasource.

<h2><span id="Flow">Flow of Spring Boot Login and Registration example</span></h2>
The diagram shows flow of how we implement User Registration, User Login and Authorization process.

![spring-boot-login-example-jwt-mysql-flow](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5f40bqgmv6t959orrcze.png)

A legal JWT must be stored in <strong>Cookies</strong> if Client accesses protected resources.

You will need to implement Refresh Token:

<img src="https://bezkoder.com/wp-content/uploads/2021/04/spring-boot-refresh-token-jwt-example-flow.png" alt="spring-boot-refresh-token-jwt-example-flow" width="700" height="480" class="alignnone size-full wp-image-7113" />

More details at: <a href="https://bezkoder.com/spring-boot-refresh-token-jwt/">Spring Boot Refresh Token with JWT example</a>

<h2><span id="Architecture">Spring Boot Rest API Server Architecture with Spring Security</span></h2>
You can have an overview of our Spring Boot Login example with the diagram below:

![spring-boot-login-example-jwt-mysql-spring-security-architecture](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wf6non1inu3f8iysn5tl.png)

Now I will explain it briefly.

<strong>Spring Security</strong>

- <code><a href="https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurerAdapter.html">WebSecurityConfigurerAdapter</a></code> is the crux of our security implementation. It provides <code><a href="https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#jc-httpsecurity">HttpSecurity</a></code> configurations to configure cors, csrf, session management, rules for protected resources. We can also extend and customize the default configuration that contains the elements below.

- <code><a href="https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#tech-userdetailsservice">UserDetailsService</a></code> interface has a method to load User by <em>username</em> and returns a <code>UserDetails</code> object that Spring Security can use for authentication and validation.

- <code>UserDetails</code> contains necessary information (such as: username, password, authorities) to build an Authentication object.

- <code><a href="https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/authentication/UsernamePasswordAuthenticationToken.html">UsernamePasswordAuthenticationToken</a></code> gets {username, password} from login Request, <code>AuthenticationManager</code> will use it to authenticate a login account.

- <code><a href="https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#core-services-authentication-manager">AuthenticationManager</a></code> has a <code>DaoAuthenticationProvider</code> (with help of <code>UserDetailsService</code> & <code>PasswordEncoder</code>) to validate <code>UsernamePasswordAuthenticationToken</code> object. If successful, <code>AuthenticationManager</code> returns a fully populated Authentication object (including granted authorities).

- <code><a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/filter/OncePerRequestFilter.html">OncePerRequestFilter</a></code> makes a single execution for each request to our API. It provides a <code>doFilterInternal()</code> method that we will implement parsing & validating JWT, loading User details (using <code>UserDetailsService</code>), checking Authorizaion (using <code>UsernamePasswordAuthenticationToken</code>).

- <code><a href="https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/AuthenticationEntryPoint.html">AuthenticationEntryPoint</a></code> will catch authentication error.

<strong>Repository</strong> contains <code>UserRepository</code> & <code>RoleRepository</code> to work with Database, will be imported into <strong>Controller</strong>.

<strong>Controller</strong> receives and handles request after it was filtered by <code>OncePerRequestFilter</code>.

- <code>AuthController</code> handles signup/login requests

- <code>TestController</code> has accessing protected resource methods with role based validations.

Understand the architecture deeply and grasp the overview more easier:
<a href="https://bezkoder.com/spring-boot-jwt-mysql-spring-security-architecture/">Spring Boot Architecture for JWT with Spring Security</a>

<h2><span id="Technology">Technology</span></h2>
<ul>
	<li>Java 8</li>
	<li>Spring Boot 2.6.1 (with Spring Security, Spring Web, Spring Data JPA)</li>
	<li>jjwt 0.9.1</li>
	<li>MySQL</li>
	<li>Maven 3.6.1</li>
</ul>

<h2><span id="Project_Structure">Project Structure</span></h2>
This is folders & files structure for our Spring Boot Login example:

![spring-boot-login-example-jwt-project-structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pveuztp5p2dsqj5fk5co.png)

<strong>security</strong>: we configure Spring Security & implement Security Objects here.
<ul>
	<li><code>WebSecurityConfig</code> extends <code>WebSecurityConfigurerAdapter</code></li>
	<li><code>UserDetailsServiceImpl</code> implements <code>UserDetailsService</code></li>
	<li><code>UserDetailsImpl</code> implements <code>UserDetails</code></li>
	<li><code>AuthEntryPointJwt</code> implements <code>AuthenticationEntryPoint</code></li>
	<li><code>AuthTokenFilter</code> extends <code>OncePerRequestFilter</code></li>
	<li><code>JwtUtils</code> provides methods for generating, parsing, validating JWT</li>
</ul>

<strong>controllers</strong> handle signup/login requests & authorized requests.
<ul>
	<li><code>AuthController</code>: @PostMapping('/signup'), @PostMapping('/signin'), @PostMapping('/signout')</li>
	<li><code>TestController</code>: @GetMapping('/api/test/all'), @GetMapping('/api/test/[role]')</li>
</ul>

<strong>repository</strong> has interfaces that extend Spring Data JPA <code>JpaRepository</code> to interact with MySQL Database.
<ul>
	<li><code>UserRepository</code> extends <code>JpaRepository&lt;User, Long></code></li>
	<li><code>RoleRepository</code> extends <code>JpaRepository&lt;Role, Long></code></li>
</ul>

<strong>models</strong> defines two main models for Authentication (<code>User</code>) & Authorization (<code>Role</code>). They have many-to-many relationship.
<ul>
	<li><code>User</code>: id, username, email, password, roles</li>
	<li><code>Role</code>: id, name</li>
</ul>

<strong>payload</strong> defines classes for Request and Response objects

We also have <strong>application.properties</strong> for configuring Spring Datasource, Spring Data JPA and App properties (such as JWT Secret string or Token expiration time).

For step by step instruction and Github, please visit:
[Spring Boot Login example with JWT and MySQL](https://www.bezkoder.com/spring-boot-login-example-mysql/)

<h2><span id="Further_Reading">Further Reading</span></h2>
<ul>
	<li><a href="https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/">Spring Security Reference</a></li>
	<li><a href="https://bezkoder.com/jwt-json-web-token/">In-depth Introduction to JWT-JSON Web Token</a></li>
	<li><a href="https://www.bezkoder.com/spring-boot-jwt-mysql-spring-security-architecture/">Architecture: Spring Boot 2 JWT Authentication with Spring Security</a></li>
</ul>

Related Posts:
<ul>
	<li><a href="https://bezkoder.com/spring-boot-jpa-crud-rest-api/">Spring Boot, Spring Data JPA – Building Rest CRUD API example</a></li>
	<li><a href="https://bezkoder.com/spring-boot-pagination-filter-jpa-pageable/">Spring Boot Pagination & Filter example | Spring JPA, Pageable</a></li>
	<li><a href="https://bezkoder.com/spring-boot-graphql-mysql-jpa/">CRUD GraphQL APIs example with Spring Boot, MySQL & Spring JPA</a></li>
	<li><a href="https://bezkoder.com/spring-boot-rest-xml/">Spring Boot Rest XML example – Web service with XML Response</a></li>
	<li><a href="https://bezkoder.com/spring-boot-file-upload/">Spring Boot File upload example with Multipart File</a></li>
	<li><a href="https://bezkoder.com/spring-boot-restcontrolleradvice/">@RestControllerAdvice example in Spring Boot</a></li>
	<li><a href="https://bezkoder.com/spring-boot-controlleradvice-exceptionhandler/">Spring Boot @ControllerAdvice & @ExceptionHandler example</a></li>
	<li><a href="https://bezkoder.com/spring-boot-unit-test-jpa-repo-datajpatest/">@DataJpaTest example for Spring Data Repositiory Unit Test</a></li>
</ul>

Deployment:
<ul>
	<li><a href="https://www.bezkoder.com/deploy-spring-boot-aws-eb/">Deploy Spring Boot App on AWS – Elastic Beanstalk</a></li>
	<li><a href="https://www.bezkoder.com/docker-compose-spring-boot-mysql/">Docker Compose: Spring Boot and MySQL example</a></li>
</ul>

Fullstack CRUD App:
- <a href="https://bezkoder.com/spring-boot-vue-js-crud-example/">Spring Boot + Vue.js example</a>
- <a href="https://bezkoder.com/angular-spring-boot-crud/">Angular 8 + Spring Boot example</a>
- <a href="https://bezkoder.com/angular-10-spring-boot-crud/">Angular 10 + Spring Boot example</a>
- <a href="https://bezkoder.com/angular-11-spring-boot-crud/">Angular 11 + Spring Boot example</a>
- <a href="https://www.bezkoder.com/angular-12-spring-boot-crud/">Angular 12 + Spring Boot example</a>
- [Angular 13 + Spring Boot example](https://www.bezkoder.com/spring-boot-angular-13-crud/)
- [Angular 14 + Spring Boot example](https://www.bezkoder.com/spring-boot-angular-14-crud/)
- [Angular 15 + Spring Boot example](https://www.bezkoder.com/spring-boot-angular-15-crud/)
- <a href="https://bezkoder.com/react-spring-boot-crud/">React + Spring Boot example</a>

If you need a working front-end for this back-end, you can find Client App in the posts:
(just modify using Local Storage to HttpOnly Cookies)
- <a href="https://www.bezkoder.com/jwt-vue-vuex-authentication/">Vue</a>
- <a href="https://www.bezkoder.com/angular-jwt-authentication/">Angular 8</a> / <a href="https://www.bezkoder.com/angular-10-jwt-auth/">Angular 10</a> / <a href="https://www.bezkoder.com/angular-11-jwt-auth/">Angular 11</a> / <a href="https://www.bezkoder.com/angular-12-jwt-auth/">Angular 12</a> / <a href="https://www.bezkoder.com/angular-13-jwt-auth/">Angular 13</a> / <a href="https://www.bezkoder.com/angular-14-jwt-auth/">Angular 14</a> / <a href="https://www.bezkoder.com/angular-15-jwt-auth/">Angular 15</a>
- <a href="https://www.bezkoder.com/react-jwt-auth/">React</a> / <a href="https://www.bezkoder.com/react-hooks-jwt-auth/">React Hooks</a> / <a href="https://www.bezkoder.com/react-redux-jwt-auth/">React + Redux</a>