In this tutorial, we will learn how to build a full stack Spring Boot + Vue.js Authentication example. The back-end server uses Spring Boot with Spring Security for JWT authentication and Spring Data JPA for interacting with database. The front-end will be created with Vue and Vuex. We’ll also use vee-validate
to perform Form validation and vue-fontawesome
for make our UI more comfortable to view.
It will be pretty long, but interesting. Let’s get started.
Related Post: Spring Boot + Vue.js example: Build a CRUD App
More Practice:
– CRUD GraphQL APIs example with Spring Boot, MySQL & Spring JPA
– Vue + Spring Boot: File Upload example
Run both Project on same server/port:
How to integrate Vue.js with Spring Boot
Contents
JWT (JSON Web Token)
Nowaday, JWT is popular for Authentication and Information Exchange. Instead of creating a Session (Session-based Authentication), Server encodes data into a JSON Web Token and send it to the Client. The Client saves the JWT, then every Request from Client to protected routes or resources should be attached that JWT (commonly at header). The Server will validate that JWT and return the Response.
Comparing with Session-based Authentication that need to store Session on Cookie, the big advantage of JWT (Token-based Authentication) is that we store the Token on Client side: Local Storage for Browser, Keychain for IOS and SharedPreferences for Android… So we don’t need to build another backend project that supports Native Apps or an additional Authentication module for Native App users.
There are three important parts of a JWT: Header, Payload, Signature. Together they are combined to a standard structure: header.payload.signature
.
The Client typically attact JWT in Authorization header with Bearer prefix:
Authorization: Bearer [header].[payload].[signature]
For more details, you can visit:
In-depth Introduction to JWT-JSON Web Token
Spring Boot Vue.js Authentication example
It will be a full stack, with Spring Boot for back-end and Vue.js for front-end. The system is secured by Spring Security with JWT Authentication.
- User can signup new account, login with username & password.
- Authorization by the role of the User (admin, moderator, user)
Screenshots
The images below shows screenshots of our Vue.js App.
– Anyone can access a public page before logging in:
– A new User can signup:
– After signup is successful, User can login. When it’s done, App directs the User to Profile page:
– UI for admin login:
– If a User who doesn’t have Admin role tries to access Admin/Moderator Board page:
Demo
This is full Spring Boot + Vue.js authentication demo (with form validation, check signup username/email duplicates, test authorization with 3 roles: Admin, Moderator, User):
Flow for User Registration and User Login
The diagram shows flow for User Registration process and User Login process.
I think it’s not too difficult to understand. We have 2 endpoints for authentication:
api/auth/signup
for User Registrationapi/auth/signin
for User Login
If Client wants to send request to protected data/endpoints, a legal JWT must be added to HTTP Authorization Header.
Back-end with Spring Boot & Spring Security
Overview
Our Spring Boot Application can be summarized in the diagram below:
Let me explain it.
Spring Security
– WebSecurityConfigurerAdapter
is the crux of our security implementation. It provides HttpSecurity
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.
– UserDetailsService
interface has a method to load User by username and returns a UserDetails
object that Spring Security can use for authentication and validation.
– UserDetails
contains necessary information (such as: username, password, authorities) to build an Authentication object.
– UsernamePasswordAuthenticationToken
gets {username, password} from login Request, AuthenticationManager
will use it to authenticate a login account.
– AuthenticationManager
has a DaoAuthenticationProvider
(with help of UserDetailsService
& PasswordEncoder
) to validate UsernamePasswordAuthenticationToken
object. If successful, AuthenticationManager
returns a fully populated Authentication object (including granted authorities).
– OncePerRequestFilter
makes a single execution for each request to our API. It provides a doFilterInternal()
method that we will implement parsing & validating JWT, loading User details (using UserDetailsService
), checking Authorizaion (using UsernamePasswordAuthenticationToken
).
– AuthenticationEntryPoint
will catch unauthorized error and return a 401 when Clients access protected resources without authentication.
Repository contains UserRepository
& RoleRepository
to work with Database, will be imported into Controller.
Controller receives and handles request after it was filtered by OncePerRequestFilter
.
– AuthController
handles signup/login requests
– TestController
has accessing protected resource methods with role based validations.
Technology
To implement the server with concept above, we will use:
– Java 8
– Spring Boot 2.1.8.RELEASE (with Spring Security, Spring Web, Spring Data JPA)
– jjwt 0.9.1
– PostgreSQL/MySQL
– Maven 3.6.1
Project Structure
The structure of Spring Boot back-end project is pretty complicated:
You can see that there are 5 packages:
security: we configure Spring Security & implement Security Objects here.
WebSecurityConfig
extendsWebSecurityConfigurerAdapter
UserDetailsServiceImpl
implementsUserDetailsService
UserDetailsImpl
implementsUserDetails
AuthEntryPointJwt
implementsAuthenticationEntryPoint
AuthTokenFilter
extendsOncePerRequestFilter
JwtUtils
provides methods for generating, parsing, validating JWT
controllers handle signup/login requests & authorized requests.
AuthController
: @PostMapping(‘/signin’), @PostMapping(‘/signup’)TestController
: @GetMapping(‘/api/test/all’), @GetMapping(‘/api/test/[role]’)
repository has intefaces that extend Spring Data JPA JpaRepository
to interact with Database.
UserRepository
extendsJpaRepository
RoleRepository
extendsJpaRepository
models defines two main models for Authentication (User
) & Authorization (Role
). They have many-to-many relationship.
User
: id, username, email, password, rolesRole
: id, name
payload defines classes for Request and Response objects
We also have application.properties for configuring Spring Datasource, Spring Data JPA and App properties (such as JWT Secret string or Token expiration time).
Implementation
You can find step by step to implement this Spring Boot – Spring Security App in the post:
Secure Spring Boot App with Spring Security & JWT Authentication
For working with MongoDB:
Spring Boot, MongoDB: JWT Authentication with Spring Security
Or PostgreSQL:
Spring Boot, Spring Security, PostgreSQL: JWT Authentication example
Front-end with Vue.js & Vuex
Overview
Our Vue.js App can be summarized in component diagram below:
Let me explain it right now.
– The App
component is a container with Router
. It gets app state from Vuex store/auth
. Then the navbar now can display based on the state. App
component also passes state to its child components.
– Login
& Register
components have form for submission data (with support of vee-validate
). We call Vuex store dispatch()
function to make login/register actions.
– Our Vuex actions call auth.service
methods which use axios
to make HTTP requests. We also store or get JWT from Browser Local Storage inside these methods.
– Home
component is public for all visitor.
– Profile
component get user
data from its parent component and display user information.
– BoardUser
, BoardModerator
, BoardAdmin
components will be displayed by Vuex state user.roles
. In these components, we use user.service
to get protected resources from API.
– user.service
uses auth-header()
helper function to add JWT to HTTP Authorization header. auth-header()
returns an object containing the JWT of the currently logged in user from Local Storage.
Technology
– vue: 2.6.10
– vue-router: 3.0.3
– vuex: 3.0.1
– axios: 0.19.0
– vee-validate: 2.2.15
– bootstrap: 4.3.1
– vue-fontawesome: 0.1.7
Vue 3 version at:
Vue 3 Authentication with JWT, Vuex, Axios and Vue Router
Project Structure
The structure of Vue front-end project is simple:
You can understand it properly without any explanation.
Implementation
You can find step by step to implement this Vue – Vuex App in the post:
Vue.js JWT Authentication with Vuex and Vue Router
Typescript version: Vue/Vuex Typescript: JWT Authentication example
Vue 3 version: Vue 3 Authentication with JWT, Vuex, Axios and Vue Router
Source Code
The complete source code for this tutorial can be found at Spring Boot with Vue.js Github.
Conclusion
Now we have an overview of Spring Boot Vue.js Authentication example using JWT, Spring Security and Vuex along with flow for signup/login actions.
We also take a look at Spring Boot server architecture for JWT Authentication using Spring Sercurity & Spring Data JPA, as well as Vue.js project structure for building a front-end app working with JWT.
Next tutorials will show you more details about how to implement this interesting system:
– Back-end:
– Front-end:
Run both Project on same server/port:
How to integrate Vue.js with Spring Boot
The best!
Please share source code with me both front-end & back-end. I don’t find on this site.
Thanks
Udit
Hi, they are inside the tutorials at Conclusion section.
Thanks
I want to create a user by selecting roles(one or multiple roles on front side). Could you please help me? I tried to do it, but strRoles gets null and only create a user with strRoles== null option.
Thank you
Can you do it without jwt token
Hi there, I want to subscribe for this fullstack Spring + Vue tutorial. Thanks!
Great stuff! Thanks a lot for sharing it!
hi, this is awesome… clear explanation. hopefully you’ll always be productives to share such as this awesome things.
Excellent tutorial about Spring and Vue Authentication! Thank you so much!
Most complete explanation of how to use SpringBoot + Vue.js. Thanks a lot.
Nice explanation!. Could you please share the source code link also?
Hi, you can find it in the links to Back-end and Front-end tutorials.
how can download this source code??!!
Hi, you can visit links in the post for more details and download source code from Github.
thanks bro.
Great article and thanks for your knowledge sharing! 🙂
It’ѕ impressive that you integrate Spring Boot and Vue.js in a good approach to JWT authentication. Thanks a lot!
Thank you so much! It works.
Great article! I have a question, how do you manage token refresh?
Hi, I’ll write the tutorial with Refresh Token when having time.
I’ll be waiting, your tutorials are really really helpful ❤
Could you please write with a refresh token?
Hi, you can read Refresh Token for backend first: Spring Boot Refresh Token with JWT example.
Can you please please please share the source code, I’m really desperate.
Oh yeah, I will 🙂
Please wait for the next tutorial. Thanks.
Thank you 🙂 do you already know when you will upload the next tutorial?
Within the next 2 days 😀
Very useful article, tho. It would be great if you share the front-end source code link, please!
Sure, I will 🙂
I’m impressed, I must say. This is one of the most helpful post I’ve ever read about Spring Boot & Vue.js.
Thank you. I’m so proud to hear this 🙂
Hi,
Nice explanation. Could you please share the source code link also?
Hi, I will share source code in the next tutorial 🙂
where is code source you ?
you said in the next tutorial !!!!!!
You can find next tutorials’ links in the post.
I can not find the source code
can you reply the link to source code?
Hi, you can find github source code for back-end and front-end in the referenced links (at Conclusion section) 🙂