=Paper=
{{Paper
|id=Vol-3676/BISEC_paper_9
|storemode=property
|title=Advanced Security Mechanisms in the Spring Framework: JWT, OAuth, LDAP and Keycloak
|pdfUrl=https://ceur-ws.org/Vol-3676/short_09.pdf
|volume=Vol-3676
|authors=Nikola Dimitrijević,Nemanja Zdravković,Milena Bogdanović,Aleksandar Mesterovic
|dblpUrl=https://dblp.org/rec/conf/bisec/DimitrijevicZBM23
}}
==Advanced Security Mechanisms in the Spring Framework: JWT, OAuth, LDAP and Keycloak==
Advanced Security Mechanisms in the Spring Framework:
JWT, OAuth, LDAP and Keycloak
Nikola Dimitrijević1,* , Nemanja Zdravković1 , Milena Bogdanović1 and Aleksandar Mesterovic2
1
Faculty of Information Technology, Belgrade Metropolitan University, Tadeuša Košćuška 63, 11000 Belgrade, Serbia
2
Department of Security Studies and Criminology, Faculty of Art, Macquarie University, Sydney, Australia
Abstract
The security of software applications is a critical concern in modern software development, especially with the prevalence of
distributed systems and microservices. The Spring Framework stands out as a premier Java ecosystem development platform
that offers an extensive range of options for implementing robust security mechanisms. This paper will shift its focus to
explore advanced approaches to securing enterprise environments using the Spring Framework; specifically discussing topics
such as JSON Web Token (JWT), OAuth 2.0, Lightweight Directory Access Protocol (LDAP) and Keycloak-based solutions.
The use of JWT is pivotal for the secure communication of information between disparate parties, particularly in the
context of stateless authentication inherent to micro-service architectures. OAuth 2.0 serves as a standard for authorization that
permits users access to shared resources while safeguarding sensitive user credentials from being exposed unnecessarily. LDAP
finds practical applicability by facilitating centralized management and governance over identities and privileged accesses,
chiefly advantageous when dealing with complex organizational structures at scale. As an open-source platform solution
specifically tailored towards identity recognition and managed authorizations, Keycloak offers integration opportunities
within Spring applications ecosystem where it introduces support services catering to commonly accepted protocols such as
OpenID Connect or SAML; providing sound solutions essential in ensuring well-regulated confidential interactions akin
during situations demanding trusted validations occasioned by both internal needs or external supply chain partners alike.
In this, paper, we investigate the manner in which advanced technologies can be suitably employed within the Spring
Framework for creating secure and scalable applications. The analysis delves into each of these mechanisms, outlining
their advantages and challenges along with integration considerations when complex business scenarios arise. Ultimately,
this exploration is intended to enhance comprehension surrounding progressive security measures applicable to the Spring
environment thereby equipping developers with improved capacity for constructing more resilient application solutions.
Keywords
Spring framework, Security awareness, JWT, OAuth, LDAP, Keycloak
1. Introduction ing concept has evolved over time with the inclusion of
various modules designed to cater to different aspects
The Spring Framework has become a fundamental com- of enterprise application development. Notably among
ponent in the development of contemporary Java-based these arrangements is the Spring Security module that
applications. This is particularly attributed to its exten- plays an important role in securing applications through
sive infrastructure support for application building [1]. its provision of comprehensive security services tailored
A core feature within this framework is Spring Security; for Java EE-based enterprise software applications [2].
an influential and personalized authentication and access According to [3, 4] 44.1% of respondents use the free
control system that plays a critical role in safeguarding AdoptOpenJDK distribution in production. However, Or-
applications against prevalent security threats. acle still has a significant presence, with 28% for their
The Spring Framework, which was first introduced OpenJDK build and 23% for the commercial Oracle JDK.
in 2003, brought about a significant transformation to The JSON Web Token (JWT) represents a widely
Java development by introducing an Inversion of Control adopted and established medium of securely exchanging
(IoC) container that is lightweight and simplified the man- information as JSON objects among entities. These to-
agement of application components. This groundbreak- kens stand out for their compactness, compatibility with
URLs, digital signature support resulting in enhanced
BISEC’23: 14th International Conference on Business Information
security features, therefore constituting an ideal option
Security, November 24, 2023, Niš, Serbia
*
Corresponding author. in stateless authentication contexts within contemporary
$ nikola.dimitrijevic@metropolitan.ac.rs (N. Dimitrijević); web applications [5]. When merged into Spring Security
nemanja.zdravkovic@metropolitan.ac.rs (N. Zdravković); System Architecture , JWTs provide reliable and uninter-
milenaBogdanovic@metropolitan.ac.rs (M. Bogdanović); rupted mechanisms compatible with the overall design
aleksandar.mesterovic@students.mq.edu.au (A. Mesterovic)
of secure non-session-based functionalities instructured
0000-0002-6595-9277 (N. Dimitrijević); 0000-0002-0707-5174
(N. Zdravković); 0000-0003-0316-4484 (M. Bogdanović) developments derived from spring programming method-
© 2024 Copyright for this paper by its authors. Use permitted under Creative Commons License ology.
Attribution 4.0 International (CC BY 4.0).
CEUR
Workshop
Proceedings
http://ceur-ws.org
ISSN 1613-0073
CEUR Workshop Proceedings (CEUR-WS.org)
CEUR
ceur-ws.org
Workshop ISSN 1613-0073
Proceedings
0 5 10 15 20 25 30 35 40 45 50
AdoptOpenJDK builds of OpenJDK
Oracle OpenJDK
Oracle JDK
Azul Zulu builds of OpenJDK
Amazon Corretto builds of OpenJDK
The Linux Distro's bundled OpenJDK package
Red Hat builds of openJDK
Oracle GraalVM Community Edition
IBM Java SDK
Azul Zing
Alibaba Dragonwell builds of OpenJDK
Bellsoft Liberica builds of OpenJDK
Eclipse Adoptium builds of OpenJDK
Oracle GraalVM Enterprise Edition
SAP SapMachine builds of OpenJDK
Other
None
Figure 1: JDKs in production.
The OAuth 2.0 framework serves as a means of au- 2. JWT and Its Implementation in
thorization that allows applications to acquire restricted
access to user accounts on an HTTP service. This process
Spring Framework
involves the delegation of user authentication tasks to The use of JWT has garnered considerable significance
the hosting service, as described by Hardt in 2012. In rela- in contemporary web security practices as it provides a
tion to Spring Security, OAuth 2.0 presents a formidable concise and autonomous approach for transferring in-
technique for safeguarding RESTful services and APIs formation between participants via a JSON object that
through outsourcing user authentication functions to- facilitates high-level confidentiality. JWTs are designed
wards an external authorization server. to enable signing mechanisms, which can be achieved by
The Lightweight Directory Access Protocol (LDAP) is employing either secret key cryptography utilizing the
a commonly utilized protocol for accessing and maintain- HMAC algorithm or public-private encryption with RSA
ing distributed directory information services over an or ECDSA algorithms, thereby assuring data integrity
Internet Protocol (IP) network. Within Spring Security, during transmission [7]. With such authentication pro-
LDAP assumes a pivotal role in managing user identi- tocols in place that do not rely on session state storage,
ties and access control - particularly within extensive JWT serves aptly suited scenarios like RESTful APIs.
enterprise environments as flagged by Rouse’s research A JWT generally comprises of three components: a
findings in 2005. header, a payload and a signature. The header typically
Keycloak is an open-source solution for Identity and encompasses two parts that comprise the kind of token
Access Management that caters to contemporary appli- - which is JWT - and the algorithm for signing being
cations and services. It harbors a vast array of features utilized. The payload entails claims regarding an entity
including Single-Sign On (SSO), identity brokering, as (usually the user) alongside supplementary data. Finally,
well as social login capabilities. Keycloak effectively inte- to guarantee that no changes have been made after is-
grates with Spring Security platforms allowing develop- suance, we use signatures in order to ensure authenticity
ers seamless access to diverse authentication mechanisms over time lapse periods.
alongside authorization protocols which enhance the se- Spring Security offers comprehensive backing to JWT.
curity parameters over their application environment The incorporation of JWT within Spring Security facil-
[6]. itates developers with an opportunity to address user
The incorporation of sophisticated security mecha- authentication and authorization in a non-persistent ap-
nisms, namely JWT, OAuth, LDAP and Keycloak into proach, thereby proving significantly advantageous for
the Spring Framework via Spring Security epitomizes a RESTful applications. With the help of the Spring Secu-
noteworthy progression towards creating secure Java ap- rity framework, validation procedures for JWTs are made
plications. This amalgamation not only streamlines the accessible; ensuring that they possess proper formation
implementation process for intricate security requisites whilst verifying their signature as well as claims’ validity
but also guarantees that these applications are resilient [8].
against an extensive gamut of adversarial incursions. When incorporating JWT into a Spring appli-
cation, developers commonly rely on established
libraries such as spring-security-oauth2 or
spring-security-jwt. These libraries contain the
in addition to outlining security restrictions placed upon
endpoints utilized by said application instance.
The JWT protocol is especially advantageous in situa-
tions where it is essential to establish the authenticity of a
user and their requisite authorizations for accessing des-
ignated resources. It serves as an added advantage within
microservices architecture, wherein secure inter-service
communication becomes imperative. To optimally uti-
lize JWT with Spring framework, established guidelines
comprise deployment of HTTPS to safeguard token in-
terception threats, setting realistic expiration timeframes
for tokens and judicious management pertaining infor-
mation contained in payload sections so that sensitive
data may not get exposed inadvertently.
The incorporation of JSON into Spring Security pro-
vides a dependable and efficient approach to managing
authentication and authorization in an immutable fash-
ion. Its versatility combined with its user-friendliness
render it an optimal alternative for safeguarding applica-
tions based on the Spring framework, specifically those
structured around micro-services as well as RESTful ser-
Figure 2: JSON Web Token Structure - Encoded. vices.
3. OAuth 2.0
OAuth 2.0 is an authorization framework that grants
third-party applications limited access to an HTTP ser-
vice, whether through representation of a resource owner
or autonomous acquisition of access privileges. Its dis-
tinction from authentication renders it indispensable in
situations wherein user data must be requested from
other services without compromising their respective
credentials [9]. OAuth 2.0 introduces several roles:
• Resource Owner: The user who authorizes an
application to access their account.
• Resource Server: Hosts the protected user data.
• Client: The application requesting access to the
user’s account.
• Authorization Server: Validates the identity of
the resource owner and issues access tokens.
OAuth 2.0 specifies four primary grant types, catering
to different application types:
Figure 3: JSON Web Token Structure - Decoded. • Authorization Code Grant: Ideal for clients that
can securely store client secrets.
• Implicit Grant: Designed for clients that are un-
essential resources required to efficiently generate, able to securely store client secrets.
analyze and authenticate JWTs. The implementation • Resource Owner Password Credentials Grant:
process entails configuring a JwtTokenStore and Suitable for highly trusted clients.
JwtAccessTokenConverter while providing an • Client Credentials Grant: Used for applications
optional TokenEnhancer for supplementing additional accessing their own resources.
information within the JWT. Furthermore, it is impera- Spring Security’s OAuth 2.0 support simplifies the im-
tive that developers configure an authentication manager plementation of these grant types:
authorization protocols in applications. Through the
User
(Resource Owner)
strategic employment of Spring’s configuration and cus-
tomization capabilities, developers possess the ability to
tailor OAuth 2.0 implementation to address diverse appli-
1. User Authorization Request cation requirements while ensuring optimal functionality
User agent
2. User Authorizes Application
and security measures are upheld.
(Web browser)
3. Authorization Code Grant
Application
(Client)
Auth Server
(Service API)
4. LDAP
4. Access Token Request The Lightweight Directory Access Protocol (LDAP) is
a prominently utilized protocol designed for accessing
5. Access Tokent Grant
and sustaining the functionality of dispersed directory
information services on an Internet Protocol (IP) net-
work. LDAP serves various purposes, including but not
Figure 4: OAuth five-way handshake. limited to email lookup, authentication processes as well
as organization of company data. It has emerged par-
ticularly advantageous in facilitating user information
management alongside enabling seamless authentication
• Configuration: Utilize and authorization capabilities within vast enterprise en-
EnableAuthorizationServer and vironments [10].
EnableResourceServer annotations to In the sphere of Spring Security, LDAP functions as a
set up the authorization and resource servers. fundamental source for both user data and authentication.
• Client Details Service: Configure client details, With its extensive support for LDAP, Spring Security
including client_id, client_secret, and effectively facilitates seamless integration with already-
scopes. existing LDAP servers. Consequently, this synergy con-
• Token Management: Implement token store and fers upon applications the ability to validate users whilst
token services to manage token generation, expi- retrieving pertinent user role information that has been
ration, and refresh. preserved in an independent directory within an LDAP
• Security Configuration: Define security con- database.
straints for different endpoints, specifying which Implementing LDAP authentication in a Spring appli-
are protected and which are publicly accessible. cation typically involves several steps:
Spring Security OAuth 2.0 also supports advanced fea- • Dependency Management: Include Spring LDAP
tures like: and Spring Security LDAP dependencies in your
• Custom Token Enhancers: To add additional in- project.
formation to the OAuth tokens. • LDAP Context Source Configuration: Configure
• Approval Handlers: To manage user approvals an LdapContextSource to specify the URL and
for token grants. base suffix of the LDAP server.
• Redirection and User Information Endpoints: To • LDAP Authentication Provider: Set up an
LdapAuthenticationProvider to handle au-
handle user redirection after authentication and
to provide user information to clients. thentication requests. This involves specifying a
user search base, user search filter, and optionally
Key best practices include: a group search base and group search filter.
• User Details Mapping: Map LDAP attributes to
• Securing Client Secrets: Store client secrets se- user details in Spring Security. This can be done
curely and never expose them in client-side code. using DefaultLdapAuthoritiesPopulator
• Validating Redirect URIs: Ensure that all redirect for role retrieval and PersonContextMapper
URIs are pre-registered and validated to prevent for user information mapping.
unauthorized redirection. • Security Configuration: Define security con-
• Token Security: Use HTTPS for all communica- straints in the Spring Security configuration, spec-
tions involving tokens and credentials. Imple- ifying which endpoints are protected and which
ment token revocation and rotation strategies. are publicly accessible.
The utilization of OAuth 2.0 within Spring Security
Advanced LDAP configurations in Spring can include:
presents a sturdy architecture for establishing secure
• Custom User Details Service: Implementing a • Dependency Management: Include the Keycloak
custom user details service for more complex user Spring Boot adapter dependency in your project.
information retrieval. • Keycloak Server Setup: Set up and configure a
• Password Policies: Configuring password policies Keycloak server, defining realms, clients, roles,
and handling password exceptions. and users.
• LDAP Templates: Using LdapTemplate for more • Spring Boot Application Configuration: Config-
complex LDAP operations beyond authentication. ure the Spring Boot application to use Keycloak
for authentication and authorization. This in-
When implementing LDAP in Spring, it’s important to
volves setting up Keycloak properties in the ap-
follow best practices:
plication.properties or application.yml file.
• Secure Communication: Use LDAPS (LDAP over • Security Configuration: Configure Spring Secu-
SSL) for secure communication with the LDAP rity to use Keycloak’s adapter for authentication.
server. This includes defining security constraints and
• Password Handling: Ensure that passwords are specifying protected resources in the application.
not logged or stored in an insecure manner. • User and Role Management: Utilize Keycloak’s
• Injection Protection: Guard against LDAP injec- administration console to manage users and roles,
tion attacks by validating and sanitizing input. which can be mapped to Spring Security authori-
The incorporation of LDAP into Spring Security ties.
presents a highly effective approach to managing user Keycloak’s integration with Spring allows for ad-
authentication and authorization across enterprise appli- vanced customizations, such as:
cations. Through the advantageous utilization of Spring’s
inherent support for LDAP, software developers can • Custom User Attributes: Adding and managing
establish seamless connectivity with LDAP directories custom user attributes in Keycloak.
while concurrently fortifying security and scalability • Identity Brokering: Configuring Keycloak to act
within their respective application frameworks. as an identity broker between different identity
providers.
• Theme Customization: Customizing the look and
5. Keycloak feel of login pages and emails.
Keycloak is a state-of-the-art solution for Identity and When integrating Keycloak with Spring, it’s important
Access Management, developed by Red Hat as an open- to follow best practices:
source software. Its primary objective lies in streamlin-
ing the integration of standard protocols such as OpenID • Secure Communication: Ensure that all communi-
Connect and SAML 2.0 into authentication processes cations between the Spring application and Key-
while facilitating authorization procedures. In addition cloak server are secured using HTTPS.
to centralized management console capabilities concern- • Client Secrets: Securely manage and store client
ing user identities, Keycloak enables features that ensure secrets used for communication with Keycloak.
SSO, two-factor authentication, and social login function- • Token Validation: Implement proper token vali-
alities are supported efficiently. These advanced security dation in the Spring application to prevent unau-
provisions make it particularly suited for safeguarding thorized access.
modern applications’ integrity within diverse service
Keycloak’s integration into Spring Security offers a
environments where tailored identity management solu-
powerful and flexible solution for managing authenti-
tions are highly valued [11].
cation and authorization in applications. By leveraging
In the context of Spring Security, Keycloak presents
Keycloak, developers can enhance the security of their
itself as a viable choice for an authentication and autho-
Spring applications, taking advantage of features like
rization server. As such, it affords Spring applications the
SSO, token-based authentication, and user federation.
option to delegate their user authentication and autho-
rization protocols directly to Keycloak—a dynamic that
subsequently streamlines security management efforts. 6. Literature overview
This integration furthermore empowers said applications
with access to advanced features exclusive to Keycloak; JWTs have now become a critical component for ensur-
examples include SSO, token-based authentication mea- ing web security in contemporary times. In the context of
sures, in addition to user federation capabilities. this, a scholarly research titled "Enhancing JWT Authen-
Implementing Keycloak in a Spring application typi- tication and Authorization in Web Applications Based on
cally involves several steps: User Behavior History" published in 2022 underlines the
vital significance of incorporating user behavior history or theft risk. OAuth 2.0 serves as an extensive yet adapt-
while utilizing JWT to optimize overall application secu- able authorization framework suitable across diverse ap-
rity. It is noteworthy that Spring Security endorses such plication types such IoT implementations; nevertheless
an approach via providing robust support for implement- complexity may present challenges during implementa-
ing stateless authentication and authorization features tion while strict adherence to best practice guidelines
using JWT [12]. must be maintained continuously throughout operation.
Furthermore, it is highlighted in a study in 2017 that LDAP excels at managing user identities within vast
the significance of JWTs extends across various sectors. operational environments through centralized authenti-
The research exhibits the versatility of JWT usage in cation mechanisms but setting up can pose significant
multiple contexts such as smart home environments, logistical hurdles especially when confronted by rapidly
thereby accentuating its efficacy specifically with regard changing data sets needing constant adjustments com-
to Spring-based applications [13]. pared to alternate solutions available. Finally integrating
The utilization of OAuth 2.0 in Spring is indispensable Keycloak into microservice architectures enables sim-
for ensuring sound authorization measures [14]. The pler handling of comprehensive identity access manage-
paper scrutinizes the intricacies and methods pertinent ment features significantly simplifying administration
to microservices architecture encompassing OAuth 2.0 needs albeit simultaneously placing additional demands
as a core part thereof. This approach coincides with the on server configuration requirements possibly introduc-
aid provided by Spring Security’s advanced support for ing performance reduction issues without careful op-
OAuth 2.0 protocols aimed at streamlining diverse grant timization attention being given determining effective
types within applications built on this platform. trade-offs relative required specific infrastructure capa-
The well-established function of LDAP in the man- bility constraints.
agement of user authentication and authorization can The cumulative package delivered via incorporation
be further enhanced through its integration with Spring all these methods launched efficiently using Spring af-
Security by taking into account the principles expounded fords robust overall system protection ensuring mitiga-
upon in [15]. The paper’s elucidation on context-aware tion maximization against detrimental vulnerabilities
authorization within IoT and blockchain domains is arisen from optimal deployment following exhaustive
highly informative for LDAP implementation within com- comprehension fundamental principles defining reliable
plex enterprise environments operating under Spring. secure ecosystem operations governance broadly applica-
The integration of Keycloak with Spring Security pro- ble many industry type verticals benefiting handsomely
vides a potent means to manage the authentication and therefrom upon successful implementation completion
authorization process. A recent study [16] serves as an achieving strategic business objectives intending busi-
illustrative example of how combining Keycloak and nesses reaping profitable outcomes thereof gaining com-
Spring Security can effectively secure APIs within a petitive advantage over peers not leveraging innovative
microservice-based structure. This study highlights the approaches towards future-proofing their information
efficacy of utilizing Keycloak alongside Spring Security technology systems accordingly
for ensuring resolute application security mechanisms.
Finally, the research paper entitled "Exploring the Uti-
lization of JWT in MQTT" published on arXiv in 2019 Acknowledgment
delves into the versatile application of JWT within MQTT,
This paper was supported in part by the Blockchain Tech-
a lightweight communication protocol. This study em-
nology Laboratory at Belgrade Metropolitan University,
phasizes that JWT can be extended to various protocols
Belgrade, Serbia and in part by the Ministry of Educa-
and applications, including those developed with Spring
tion, Science and Technological Development, Republic
Framework [5].
of Serbia ref. no. 451-03-47/2023-01/200029.
7. Conclusion References
The Spring Framework encompasses the integration of
[1] R. Johnson, J. Hoeller, K. Donald, C. Sampaleanu,
JWT, OAuth 2.0, LDAP and Keycloak for a multi-layered
R. Harrop, T. Risberg, A. Arendsen, D. Davison,
approach to security, with each component possessing
D. Kopylenko, M. Pollack, et al., The spring
its own advantages and drawbacks. In particular, JWT
framework-reference documentation, interface 21
boasts stateless functionality as well as scalability suitabil-
(2004) 27.
ity which renders it fitting for contemporary web applica-
[2] C. Walls, Spring in action, 4th edition, Manning
tions; however meticulous monitoring of token security
Publications, 2013.
is critical in order to prevent any potential vulnerability
[3] Snyk, JVM Ecosystem Report 2021, https://snyk.io/
reports/jvm-ecosystem-report-2021/, 2022.
[4] Ł. Wyciślik, Ł. Latusik, A. M. Kamińska, A com-
parative assessment of jvm frameworks to develop
microservices, Applied Sciences 13 (2023) 1343.
[5] K. Shingala, JSON web token (JWT) based client
authentication in message queuing telemetry trans-
port (MQTT), arXiv preprint arXiv:1903.02895
(2019).
[6] S. Thorgersen, P. I. Silva, Keycloak-identity and
access management for modern applications: har-
ness the power of Keycloak, OpenID Connect, and
OAuth 2.0 protocols to secure applications, Packt
Publishing Ltd, 2021.
[7] M. Jones, J. Bradley, N. Sakimura, RFC 7519: JSON
Web Token (JWT), 2015.
[8] M. Knutson, R. Winch, P. Mularien, Spring Security:
Secure your web applications, RESTful services, and
microservice architectures, Packt Publishing Ltd,
2017.
[9] D. Hardt, RFC 6749: The OAuth 2.0 authorization
framework, 2012.
[10] M. Rouse, Ldap (lightweight directory access pro-
tocol), Enterprise Mobile Computing news and
information (2019).
[11] R. Hat, Keycloak–open source identity and access
management, 2021.
[12] A. Bucko, K. Vishi, B. Krasniqi, B. Rexha, Enhancing
jwt authentication and authorization in web appli-
cations based on user behavior history, Computers
12 (2023).
[13] N. Hong, M. Kim, M.-S. Jun, J. Kang, A study on a
jwt-based user authentication and api assessment
scheme using imei in a smart home environment,
Sustainability 9 (2017).
[14] M. G. de Almeida, E. D. Canedo, Authentication
and authorization in microservices architecture: A
systematic literature review, Applied Sciences 12
(2022).
[15] T. Sylla, L. Mendiboure, M. A. Chalouf, F. Krief,
Blockchain-based context-aware authorization
management as a service in iot, Sensors 21 (2021)
7656.
[16] A. Chatterjee, A. Prinz, Applying spring security
framework with keycloak-based oauth2 to protect
microservice architecture apis: A case study, Sen-
sors 22 (2022) 1703.