Spring Security using JWT Token

Arjun Sunil Kumar
Software Engineering
2 min readMar 5, 2019

“A JSON Web Token (JWT), pronounced ‘jot’, is a compact URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is digitally signed using JSON Web Signature (JWS)”.

JWT based authentication (https://medium.com/p/2193f383e963)

Download:

Please fork the complete spring project from Github.

Code Dive:

  1. Project Structure:

2. Maven Dependency:

3. JwtSecurityConfig contains the configuration information for JWT authentication/authorization.

4. CustomUserDetailsService.java ( Overloading loadUserByUsername)

5. JwtAuthenticationHandlerUnauthorized contains authentication failure handlers.

Returns 401 status code, if authentication exception occurs. This can be handled in the front-end side to display “Not authorized exception” or Auto Logout.

6. JwtAuthenticationFilter contains authentication and authorization info.

7. AuthController.java

Contains the sign-in handler.

7. UserPrincipal.java (Contains user-id info etc for the logged in user). Used by spring security.

8. JwtTokenProvider.java (Contains helper functions for JWT)

9. JwtConfig.java (Class having JWT specific values)

DTO:

Request & Response Data Transfer Object

Entities:

RoleEntity.java

UserEntity.java

Repository:

Usage:

hasRole(‘ADMIN’)

ANGULAR (+6) PART:

Front-end will initially send the credentials and based on the authenticity, the server will respond a JWT token. The token is thereby saved locally in localStorage, and send in the header of subsequent requests.

Login Page:

SERVICE:

MAIN parts:

  1. Auth Guard. Prevent routing to the page, if localStorage doesn’t contain token.

2. APP ROUTING:

3. INTERCEPTORS:

Intercepts the HTTP request/response and checks the header information etc.

4. App.module

Finally, import HTTP_INTERCEPTORS and AuthGuard.

Packaging for Angular 6+

Follow the packaging structure for angular.

ng g component components/headerng g component pages/projectRegistrationPageng g pipe pipes/objectToArray/objectToArrayng g service services/Api/Api

`

--

--

Arjun Sunil Kumar
Software Engineering

Writes on Database Kernel, Distributed Systems, Cloud Technology, Data Engineering & SDE Paradigm. github.com/arjunsk