Table of Contents
JSON Web Tokens
are an open, industry standard RFC 7519
method for representing claims securely between two parties. When we create REST APIs
, then we don't want that any one can access those apis. REST APIs
, will only be accessed by the authenticated user. We authenticate
our user with the help of jwt
.
These are the terms we need to address:
Authentication
refers to the process of verifying the identity of a user, based on provided credentials. A common example is entering a username and a password when you log in to a website. You can think of it as an answer to the question Who are you?.Authorization
refers to the process of determining if a user has proper permission to perform a particular action or read particular data, assuming that the user is successfully authenticated. You can think of it as an answer to the question Can a user do/read this?.Principle
refers to the currently authenticated user.Granted authority
refers to the permission of the authenticated user.Role
refers to a group of permissions of the authenticated user.
WebSecurityConfig
is the crux of our security implementation. It configures cors, csrf, session management, rules for protected resources.UserDetailsService
interface has a method to load User by username and returns aUserDetails
object that Spring Security can use for authentication and validation.UserDetails
contains necessary information (such as: username, password, authorities) to build anAuthentication
object.UsernamePasswordAuthenticationToken
gets {username, password} from login Request,AuthenticationManager
will use it to authenticate a login account.AuthenticationManager
has aDaoAuthenticationProvider
(with help ofUserDetailsService
&PasswordEncoder
) to validateUsernamePasswordAuthenticationToken
object. If successful,AuthenticationManager
returns a fully populatedAuthentication
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), checkingAuthorization
(usingUsernamePasswordAuthenticationToken
).AuthenticationEntryPoint
will catch authentication error. Repository containsUserRepository
&RoleRepository
to work with Database, will be imported intoController
.Controller receives and handles request after it was filtered byOncePerRequestFilter
.AuthController
handles signup/login requestsTestController
has accessing protected resource methods with role based validations.
Spring Security maintains a filter chain internally where each of the filters has a particular responsibility and filters are added or removed from the configuration depending on which services are required. The ordering of the filters is important as there are dependencies between them.
The client sends a request to the application, and the container creates a FilterChain
,
which contains the Filter
instances and Servlet
that should process the HttpServletRequest
,
based on the path of the request URI. In a Spring MVC application, the Servlet
is an instance of DispatcherServlet
.
At most, one Servlet
can handle a single HttpServletRequest
and HttpServletResponse
. However, more than one Filter
can be used to:
-
Prevent downstream
Filter
instances or theServlet
from being invoked. In this case, theFilter
typically writes theHttpServletResponse
. -
Modify the
HttpServletRequest
orHttpServletResponse
used by the downstreamFilter
instances and theServlet
.
The power of the Filter
comes from the FilterChain
that is passed into it.
When you add the Spring Security framework to your application, it automatically registers a filters chain that intercepts all incoming requests. This chain consists of various filters, and each of them handles a particular use case.
For example:
- Check if the requested URL is publicly accessible, based on configuration.
- In case of session-based authentication, check if the user is already authenticated in the current session.
- Check if the user is authorized to perform the requested action, and so on.
Below is a screenshot of the project user creation and authentication restful api endpoints and the HTTP Method supported by each endpoint
System uses a single user table for user creation and authentication
Sequence diagram showing how you can create an account, login and access a secured restfull endpoint/resource
using a jwt token
you get when you authenticate
your account.
Used Java
spring boot
, MySQL
and Jason Web Token
to build the rest api, including postman for testing.
You should have the below software installed in your pc :
- JDK 20 and JRE
- MySQL
- and your preferred IDE or text editor
-
Get a free API Key at https://github.com/settings/tokens
-
Clone the repo
git clone https://github.com/kudzaiprichard/springboot-jwt-auth
-
Open project in IDE or text editor
-
Let maven download all necessary dependency for the project to run
If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again!
- Fork the Project
- Create your Feature Branch (
git checkout -b feature/ExampleFeature
) - Commit your Changes (
git commit -m 'Add some ExampleFeature'
) - Push to the Branch (
git push origin feature/ExampleFeature
) - Open a Pull Request
Your contributions are always welcome and appreciated. Following are the things you can do to contribute to this project.
-
Report a bug
If you think you have encountered a bug, and I should know about it, feel free to report it here and I will take care of it. -
Request a feature
You can also request for a feature here, and if it will viable, it will be picked for development. -
Create a pull request
It can't get better than this, your pull request will be appreciated by the community. You can get started by picking up any open issues from here and make a pull request.
If you are new to open-source, make sure to check read more about it here and learn more about creating a pull request here.
Distributed under the MIT License. See
LICENSE.txt
for more information.
Kudzai P Matizirofa - linkedin.com/in/kudzai-prichard - [email protected]
Project Link: https://github.com/kudzaiprichard/springboot-jwt-auth
list of resources I found helpful and would like to give credit to.