Angular, Spring Boot: JWT Authentication with Spring Security example
Last updated
Last updated
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 Registration
api/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.
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.
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) β jjwt 0.9.1 β PostgreSQL/MySQL β Maven 3.6.1
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
extends WebSecurityConfigurerAdapter
UserDetailsServiceImpl
implements UserDetailsService
UserDetailsImpl
implements UserDetails
AuthEntryPointJwt
implements AuthenticationEntryPoint
AuthTokenFilter
extends OncePerRequestFilter
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
extends JpaRepository
RoleRepository
extends JpaRepository
models defines two main models for Authentication (User
) & Authorization (Role
). They have many-to-many relationship.
User
: id, username, email, password, roles
Role
: 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).
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
Our Angular 8 App can be summarized in component diagram below:
Letβs try to understand it right now.
β The App
component is a container using Router
. It gets user token & user information from Browser Session Storage via token-storage.service
. Then the navbar now can display based on the user login state & roles.
β Login
& Register
components have form for submission data (with support of Form Validation). They use token-storage.service
for checking state and auth.service
for sending signin/signup requests.
β auth.service
uses Angular HttpClient ($http
service) to make authentication requests.
β every HTTP request by $http
service will be inspected and transformed before being sent by auth-interceptor
.
β Home
component is public for all visitor.
β Profile
component get user
data from Session Storage.
β BoardUser
, BoardModerator
, BoardAdmin
components will be displayed depending on roles
from Session Storage. In these components, we use user.service
to get protected resources from API.
β Angular 8 β RxJS 6
This is the folder structure of our Angular front-end project:
You can understand it properly without any explanation because weβve looked at the overview before.
You can find step by step to implement this Angular 8 App in the post: Angular 8 JWT Authentication with HttpInterceptor and Router