Applying Spring Security Framework with KeyCloak-Based OAuth2 to Protect Microservice Architecture APIs: A Case Study

In this study, we implemented an integrated security solution with Spring Security and Keycloak open-access platform (SSK) to secure data collection and exchange over microservice architecture application programming interfaces (APIs). The adopted solution implemented the following security features: open authorization, multi-factor authentication, identity brokering, and user management to safeguard microservice APIs. Then, we extended the security solution with a virtual private network (VPN), Blowfish and crypt (Bcrypt) hash, encryption method, API key, network firewall, and secure socket layer (SSL) to build up a digital infrastructure. To accomplish and describe the adopted SSK solution, we utilized a web engineering security method. As a case study, we designed and developed an electronic health coaching (eCoach) prototype system and hosted the system in the expanded digital secure infrastructure to collect and exchange personal health data over microservice APIs. We further described our adopted security solution’s procedural, technical, and practical considerations. We validated our SSK solution implementation by theoretical evaluation and experimental testing. We have compared the test outcomes with related studies qualitatively to determine the efficacy of the hybrid security solution in digital infrastructure. The SSK implementation and configuration in the eCoach prototype system has effectively secured its microservice APIs from an attack in all the considered scenarios with 100% accuracy. The developed digital infrastructure with SSK solution efficiently sustained a load of (≈)300 concurrent users. In addition, we have performed a qualitative comparison among the following security solutions: Spring-based security, Keycloak-based security, and their combination (our utilized hybrid security solution), where SSK showed a promising outcome.


Overview and Motivation
Security in the healthcare system has been an emerging trend for the past few years. It defines the interconnection of communication-enabled medical-grade devices (e.g., wearable and non-wearable), web services, software applications, and their integration with wider-scale health systems and services to improve patients' wellbeing [1,2]. However, the growth and widespread adoption of the health security ecosystem has benefited sensorbased remote monitoring (including wearable and stand-alone devices) with the management of personal and person-generated health data [1,2].
Articles related to eHealth security research unveil the following security and privacy requirements in healthcare systems (both on-premises and cloud-based) [1,2]: data security, user authentication, regulatory compliance, authorized access, confidentiality, ethical consent, legal issues, the relevance of data access, data ownership, data consistency, data separation, audits, archiving, third-party certificates (such as SAS70 Type II, Payment Table 1. Selected list of core security components of Spring Security Framework.

SecurityContextHolder
It gives access to the SecurityContext.

SecurityContext
It contains the Authentication class and request-specific security information.
Authentication This class stores user information for representing the principal in a way unique to Spring Security.

GrantedAuthority
The application-wide permissions given to a principal are to be reflected with this class.

UserDetails
It gives necessary information to create an authentication object from DAOs or other security data sources.
UserDetailsService It helps to build UserDetails when a String-based username is passed (or certificate ID or similar).

AuthenticationManager
It loads the user authentication data (credentials or user store's information) to verify authenticity of the users.

AuthenticationManagerBuilder
It is used to set up user information in memory, Java Database Connection (JDBC), Lightweight Directory Access Protocol (LDAP), or adding a custom UserDetailsService.
AbstractSecurityInterceptor A central class of authorization helps to intercept secured resource access.

SecurityMetedataSource
It provides details about the current user and the item being protected along with SecurityContext class.

AccessDecisionManager
To decide dynamically if access can be granted to a user.

AbstractSecurityInterceptor
To perform access decisions.

WebSecurityConfig
It enables http security to access the HTTP Endpoints with basic authentication by extending WebSecurityConfigurerAdapter and overriding configure method.

PasswordEncoder
The PasswordEncoder interface of Spring Security is used to convert a password in a single way to allow the password to be securely stored. It can use any of the following encryption algorithms-MD5, SHA-256, and Bcrypt (recommended).

Components Description
AuthenticationProvider It helps to protect application with Spring Security and Basic Auth.

CorsRegistry
To set up global support for CORS configuration for the Spring Boot application.

HttpSecurity
It is like the Extensible Markup Language (XML) <http> feature of Spring Protection in the namespace configuration. It enables web-based authentication for individual http requests to be configured. It will apply to all requests by default.
Authentication is used to verify personal identity; authentication is about validating credentials. The scheme decides whether the person is a legal consumer. Authorization is the mechanism used to determine if specific services are available to the authenticated user. It verifies users' rights to have personal access to resources such as records, databases, and files. Typically, authorization comes after authentication to verify user privileges. Encryption is a mechanism that encodes a document or file such that only some individuals can read it. Encryption uses an algorithm to encrypt data at the sender side and a key to decrypt the encrypted data into original form at the receiver side. External threats refer to attacks from external systems using malicious software, hacking technologies, social engineering, and attempts to exploit system vulnerabilities. Healthcare research [2][3][4][5][6][7][8][9][10][11][12] shows multiple studies associated with API security, protection of Electronic Health Records (EHR), secure Internet-of-Medical-Things (IoMT) system, security protocols and authentication scheme, methods for healthcare security, healthcare cloud and big data security, healthcare security compliance, security performance, challenges, and success factors.
Salibindla et al. [13] conducted a study on microservice API security focusing on the security for communication protocols. Xie et al. [14] published a report on Spring Security architecture and its implementation. However, these studies were performed separately without verifying the efficacy of the Spring Framework (SF), SSF, and OAuth2 when these technologies were used on MSA endpoint authentication and authorization. Nguyen et al. [15] created a proof-of-concept (PoC) MSA application using SF, spring protection, and OAuth2 to reduce the information gap on MSA and API security. They did not test how the solution would work after integrating with a third-party IAM platform. Dikanski et al. [16] performed a conceptual study to identify and implement authentication and authorization patterns in the SSF to reduce the difference between design and implementation of pattern-based protection to incorporate high-quality security features in software systems. However, the study suffered from SSF's actual implementation to protect MSA at the API endpoint level with integration with the IAM platform. Aloufi et al. [17] proposed a secure and cost-effective model based on Message Queue Telemetry Transport (MQTT) protocol to secure IoT resources with access control mechanisms over RESTful web services. Beer et al. [18] proposed a neural network-based adaptive security architecture to protect RESTful web services in an enterprise computing environment with the following three functional principles: predict, prevent, and learn an intelligent approach to detect future threats. The core of their proposed security solution was based on the public key infrastructure (PKI) and its related encryption technology to protect HTTP transactions. The results were compared with supported network/transport layer security, and it was discovered that the proposed security solution is suitable for REST APIs and is better than the Simple Object Access Protocol (SOAP)-based web services. Since RESTful web services are stateless, they usually do not have any sessions to perform challenge-response mechanisms. Transport layer security/secure socket layer (Transport Layer Security (TLS)/Secure Socket Layer (SSL)) provides secure peer-to-peer authentication. Still, when the authentication request is based on delegation, this mechanism is inadequate to allow sites to authenticate Keycloak [27] is an open-access IAM platform that secures web applications and RESTful web services using standard protocols such as OAuth2, OpenID Link, and SAML 2.0. It offers flexible login, registration, administration, CORS support, and account management user interfaces. We configured Keycloak as a separate sever to secure our eCoach APIs using the standard security assertion markup language 2.0 (SAML 2.0) integration with SSF. SAML 2.0 is a variant of the SAML standard that allows security domains to share authentication and authorization identities. SAML 2.0 is an XML-based protocol that uses security tokens containing assertions between an SAML authority, an Identity Provider, and an SAML client, called a Service Provider, to transfer information about a principal (usually an end-user). SAML 2.0 allows SSO, web-based, cross-domain, and helps minimize the administrative overhead of transmitting multiple authentication tokens to the user. These tokens may have identity details, such as username, address, email, and other information about the profile. They can also keep permission data so that users can make authorization decisions. These tokens can also be used on REST-based services to render stable invocations. The following core concepts and terms are generally used in Keycloak to secure web application and REST APIs [23]: users, authentication, authorization, credentials, roles, user role mapping, composite roles, groups, realms (to manage a set of users, credentials, their functions, and groups), clients, client adapters, client role, identity token, access token, session, user federation provider, and identity provider mappers. Table 2 describes the selected list of components of Keycloak for SSF integration to protect our eCoach REST APIs.
Microservice Architecture (MSA) [29][30][31][32][33][34][35][36][37] has arisen to describe a specific way of developing software systems for independently deployable services. The traditional monolithic software development approach suffers from the following drawbacks: bundled deployment as a single stack, intransigent scalability, high cost of resources and refactoring efforts, and DevOps challenges among dispersed teams [15,16]. In contrast, MSA handles such concerns with the following measures: task decomposition into services, service communication using APIs with the smallest granularity, agility, independent deployment, and execution of services. REST and SOAP are two HTTP-based communication protocols used for data exchange between microservice APIs in multiple formats, such as XML and JSON [15]. We used REST for eCoach API implementation in this study due to its lightweight nature. There are numerous methods to secure REST APIs. Still, the following four are the most popular: • HTTP-based authentication scheme (basic and bearer token), • API keys, • OAuth2 (access token and refresh token), and • OpenID (e.g., Keycloak OpenID, BankID).
OAuth2 is intended for authorization only, to grant access from one program to another to data and features. OpenID Connect (OIDC) is a thin layer on top of OAuth2 that adds details about logging into the user profile. We used Keycloak generic OpenID connect relying party and SAML service provider libraries in this study. The reliability and credibility of eHealth scientific research and associated services rely on the health data protection plans and guidelines regarding security, privacy, and confidentiality. For this study, we received ethical approval from The Norwegian Centre for Research Data (NSD) for managing data for our eHealth research in Norway.

System Architecture
Personal health and wellness data are generally collected through wearable sensors, interactions, interviews, web-based interactions, mobile apps, questionnaires, and feedback forms [23,25]. For ubiquitous tracking, high-end, time-dependent activity data collection with wearable BLE devices has become accessible and feasible. Wearable activity sensors can be connected via Bluetooth short-range communication technology (BLE) to a smartphone. With a machine intelligence module, the computing device can calculate and transfer high-resolution raw acceleration data and multiple operation parameters to safe storage seamlessly to process the data further. Some activity data are questionnairedependent, such as non-wear time and intense activity information. Either invasive (e.g., glycemic response, cholesterol level) or non-invasive physiological data (e.g., weight, blood pressure, heart rate, body assessment data) can be collected. Food data based on the questionnaire can be collected either regularly or on an alternating daily or weekly basis. Baseline data (medical background, habit, preference, personal knowledge, initial weight and height, initial blood pressure, and initial body assessment data) are being collected for demographic statistics or population clustering or individual target assessment during the participant's initial recruitment or every month.
In this context, we developed a digital infrastructure after extending the SSK features with VPN, Bcrypt hash, API key, firewall, and SSL, as depicted in Figure 1. Moreover, we deployed an electronic health coaching (eCoach) prototype system in the developed infrastructure to execute a formal security testing of the SSK solution scheme, and it is depicted in Figure 2. We maintained a modular structure for our eCoach prototype system for an obesity case study with the following modules [25]: activity, contextual, questionnaire, user interface (eCoachUX), and eCoach business (for user management, performance monitoring, database management, scheduling, user support, user communication, decision support, and recommendation generation).
In this context, we developed a digital infrastructure after extending the SSK features with VPN, Bcrypt hash, API key, firewall, and SSL, as depicted in Figure 1. Moreover, we deployed an electronic health coaching (eCoach) prototype system in the developed infrastructure to execute a formal security testing of the SSK solution scheme, and it is depicted in Figure 2. We maintained a modular structure for our eCoach prototype system for an obesity case study with the following modules [25]: activity, contextual, questionnaire, user interface (eCoachUX), and eCoach business (for user management, performance monitoring, database management, scheduling, user support, user communication, decision support, and recommendation generation).   In this context, we developed a digital infrastructure after extending the SSK features with VPN, Bcrypt hash, API key, firewall, and SSL, as depicted in Figure 1. Moreover, we deployed an electronic health coaching (eCoach) prototype system in the developed infrastructure to execute a formal security testing of the SSK solution scheme, and it is depicted in Figure 2. We maintained a modular structure for our eCoach prototype system for an obesity case study with the following modules [25]: activity, contextual, questionnaire, user interface (eCoachUX), and eCoach business (for user management, performance monitoring, database management, scheduling, user support, user communication, decision support, and recommendation generation).

Data Collection
We used a wearable MOX-2 [38] activity monitor to collect personal activity data for the following measurement parameters:

•
Physical activity classification (low intensity, medium intensity, and high intensity), The activity module is responsible for activity device registration, device allocation, seamless collection of sensor observations, and sending it back to the eCoach business module for storing data in a PostgreSQL database.
MOX-2 is an activity monitor based on an embedded BLE accelerometer with low power consumption. The device can seamlessly measure and transmit high-resolution raw acceleration data and multiple activity parameters per second for seven consecutive days (up to 60 days).
In Stage 1, data collected from the activity sensor are sent back to the MOX mobile app to be stored temporarily in CSV format on the smartphone over BLE protocol. In Stage 2, a schedular running at the backend of our eCoach app collects activity data periodically from the smartphone location and sends it to the activity module using the HTTP-POST service (see Figure 3). The contextual module periodically contains context updates from OpenWeather REST APIs (e.g., latest and hourly) with API-Key authentication and sends them back to eCoach business logic for stable storage. The questionnaire module consists of six question sets: daily, alternative day, weekly, interview, baseline (monthly), and feedback form. The participant submits the questionnaire, which is stored in the database through the eCoach business logic.
We used a wearable MOX-2 [38] activity monitor to collect personal activity data for the following measurement parameters: • Physical activity classification (low intensity, medium intensity, and high intensity), • Posture detection (sedentary, standing, and weight-bearing), • Physical activity intensity (counts per minute), • The activity module is responsible for activity device registration, device allocation seamless collection of sensor observations, and sending it back to the eCoach business module for storing data in a PostgreSQL database.
MOX-2 is an activity monitor based on an embedded BLE accelerometer with low power consumption. The device can seamlessly measure and transmit high-resolution raw acceleration data and multiple activity parameters per second for seven consecutive days (up to 60 days).
In Stage 1, data collected from the activity sensor are sent back to the MOX mobile app to be stored temporarily in CSV format on the smartphone over BLE protocol. In Stage 2, a schedular running at the backend of our eCoach app collects activity data periodically from the smartphone location and sends it to the activity module using the HTTP-POST service (see Figure 3). The contextual module periodically contains context updates from OpenWeather REST APIs (e.g., latest and hourly) with API-Key authentication and sends them back to eCoach business logic for stable storage. The questionnaire module consists of six question sets: daily, alternative day, weekly, interview, baseline (monthly), and feedback form. The participant submits the questionnaire, which is stored in the database through the eCoach business logic.

eCoach System (App. Version vs. Web Version)
The "/eCoachUX/home" API is exposed to the external user (protected with VPN access, a firewall, and SSL). Other APIs are protected with the access-role as configured in the Keycloak authorization server. If participants forget the password for authentication they need to raise a request through "/eCoachUX/complaint" REST API. The Actuator provides secure endpoints for controlling, handling, and monitoring Spring Boot modules, such as /metrics, /env, /beans, /health, /info, and /trace, which are protected by role-based authorization. The user interface module is responsible for app view, web view, and data visualization based on individual access roles. Figure 1 depicts how the SSK security solution for the eCoach system has been implemented with the KeyCloak third-party IAM platform. This study concentrated only on the eCoach API security and

eCoach System (App. Version vs. Web Version)
The "/eCoachUX/home" API is exposed to the external user (protected with VPN access, a firewall, and SSL). Other APIs are protected with the access-role as configured in the Keycloak authorization server. If participants forget the password for authentication, they need to raise a request through "/eCoachUX/complaint" REST API. The Actuator provides secure endpoints for controlling, handling, and monitoring Spring Boot modules, such as /metrics, /env, /beans, /health, /info, and /trace, which are protected by rolebased authorization. The user interface module is responsible for app view, web view, and data visualization based on individual access roles. Figure 1 depicts how the SSK security solution for the eCoach system has been implemented with the KeyCloak third-party IAM platform. This study concentrated only on the eCoach API security and its implementation with SSK. Other core eCoach concepts, such as sensor specification, decision support principles, AI incorporation for the analysis of EHRs, data visualization, and personalized recommendation generation for a healthy lifestyle, are beyond this study's scope.
The eCoach system has been hosted in a VPN-protected ubuntu infrastructure provided by The University, and the provided network ("EduNet") is strictly firewall protected. Its internal IP addresses are not published to external Domain Name Services (DNS). Networks inside EduNet should be accessible; however, they must go through the proxy for external access from the eCoach server. We implemented an extra layer of basic (formbased) authentication on top of KeyCloak's two-factor (password and One-Time Password (OTP)) authentication to authenticate participants on the eCoach mobile app to transfer activity data from the MOX-activity smartphone app. Basic authentication consists of a system-generated unique user ID (UUID) and a modifiable password. No personal data (such as national id, email, mobile or phone no, or similar personal identifiers) are unveiled in the basic user authentication step. KeyCloak's two-factor user authentications consist of google authenticator (auto-id generator app) and credentials. Collected data are stored in a PostgreSQL database in JSON format for faster data processing. Furthermore, we created a self-signed SSL certificate with Keytool to secure confidential web information using public key (RSA) encryption. The eCoach system has five user categories: researcher, developer, system admin, health professional (nurse), and participants. They are further grouped into "ADMIN" (researcher, developer, system admin) and "USER" (health professional or nurse, and participants) for role-specific access control. Researchers and developers are responsible for the feasibility study, methodology adoption, system design, development, system configuration, deployment, test, and performance evaluation. They have full access to the system. System admin is accountable for infrastructure support. However, they do not have access to the participant's health and wellness data. Trained health professionals, such as nurses, are responsible for interviewing (participant screening, recruitment, and the assessment of health condition), thereby collecting initial and baseline data through a pre-defined questionnaire set. Furthermore, they have access to a visualizing dashboard to monitor the participant's processed health and wellness data. Participants have access to the personal data collection endpoints, feedback forms, and personal health and wellness monitoring dashboard. The system is protected from disclosing any personal data, and questionnaire forms are restricted from submitting any unique identifiers. The Secure Shell (SSH) access to the ubuntu and database servers is protected with authentication and authorization rules. The proposed eCoach system can be accessed through a web portal and/or a smartphone android application.

Methods for Security Implementation and Performance Evaluation
There is no single protection method to meet all the security requirements and design specifications for our distributed eCoach system. To implement and validate the SSK security solution, we utilized the web engineering security methodology by Aljawarneh et al. [39]. The software engineering principles inspire the method and build on top of the standard waterfall software development life cycle (SDLC) (see Table 3). The methodology helped to eliminate substantial threat exposures during all the SDLC phases by integrating security and evaluation components at each SDLC phase. Both software engineers and security professionals verified each stage.
To determine the performance of the hybrid security method, we evaluated the scalability of the API. Throughput (S) and latency (L) are considered to measure API scalability [39][40][41][42]. Network throughput refers to the average data rate at which data or messages are successfully transmitted on a specific communication link. It is measured in bits per second (bps). The maximum network throughput equals the Transmission Control Protocol (TCP) window size divided by the communication packet's round-trip time (RTT). This method does not consider communication overhead, such as network receiver window size, machine limitations, or network delay [39][40][41][42]. Network latency is the time it takes for a packet to be captured, transmitted, processed through multiple devices, and then received and decoded at the destination [39][40][41][42]. We use Apache open-source software JMeter (V 5.4.1) to generate HTTP request load (l) to check API scalability as a "thread group" and capture the corresponding throughput and latency. The following three attributes for load testing using JMeter [39] are critical:

•
The number of threads or users; • The acceleration period in seconds; • The loop count sets the test count.
We set the cycle count value of a single load to 5 repeated experiments and take the average throughput and latency. Low latency and high throughput are good performance indicators for supporting real-time critical applications. Table 3. Importance of the SDLC processes in eCoach context.

Process
Importance in eCoach context

Requirement Specification
Defining of eCoach scope, eCoach target audiences, user needs, functional requirements, external interface requirements (user, hardware, software, communications), system features, authentication, and authorization requirements to handle internal and/or external attacks, requirements for data integrity, and storage, and other non-functional requirements (performance, safety, security, and quality).
Design Sufficient attention to role creation, data federation, password management, system modulation, API design, security configuration to integrate SSF with KeyCloak, UML modeling, database design, server configuration, and consideration for security vulnerabilities.

Implementation (development)
Development of APIs using Spring Boot Framework, coding for UI design, data collection, data storage, password management, authentication, and authorization.
Functional Testing (unit testing) In two levels, which are unit testing (unit testing) and non-functional penetration testing, we break down security testing of the eCoach system.

Maintenance
This phase involves bug fixing, infrastructure support, support to participants, addition/deletion of users, and upgradation.

Adopted Security Scheme
This section describes how we adopted the security method for our security implementation with SSF and Keycloak and, afterward, the solution validation. Then, we describe security configuration, password management, and security testing to check the SSK security solution's effectiveness to protect MSA APIs only. We tested the security performance of the system in both real-time and simulated environments.

Hybrid Security Scheme-SSK
In this study, we built a Spring Boot application and integrated it with Keycloak [27] to protect the REST APIs from unauthorized calls. We created users in Keycloak, login and generated a JWT token [43] to access the secured REST APIs. We configured the KeyCloak server with the following steps: a. download and run the KeyCloak server in stand-alone mode; b. configure the server with the master realm, new eCoach specific realm, login configuration, email settings, theme and internationalization, creation and management of clients, and realm level roles; c. add Keycloak Spring maven dependencies (keycloakspring-boot-starter) and configuration of respective key-value pairs; and d. create and configure Java class with the Spring security (@EnableWebSecurity), Spring Security global method security (@EnableGlobalMethodSecurity), and extension of Keycloak web security configuring adapter class.
Clients are services and applications that can request the authentication of users through Keycloak. There are two types of clients [27]. The first kind of client is Keycloak applications that want to encrypt themselves and use SSO. The second category of clients are applications that request an access token to use that access token to access protected resources. Client ID is used in the request to identify the client. We used OpenID Connect (OIDC) as a client protocol in KeyCloak to secure eCoach APIs. There are three access types [27]: public, confidential, and bearer-only under the OIDC client to grant access. Here, we set access type confidential to obtain client secret and turned-on features, such as Standard Flow Enabled, Direct Access Grants Enabled, Service Accounts Enabled, Authorization Enabled options [27]. Confidential access type is used for server-side clients to perform login using a client secret and request access tokens to access resources. A service that can authenticate a user is an identity provider (IDP). Keycloak is an IDP [27] and acts as an authorization server (AS) (@EnableAuthorizationServer) in the OAuth2 workflow. An authorization point works on the AS, allowing our applications and HTTP endpoints to define our system's features. In our eCoach system, two actors who interact with the AS are-ADMIN (resource owner) and USER (client registered with AS) as the fundamental use cases depicted in Figure 4. The resource server (@EnableResourceServer) is an application that provides clients with an access token to access the HTTP endpoint resource server. It is a library set that includes HTTP endpoints, static tools, and interactive web pages. Our implemented microservices are depicted in Figure 5 as use cases of resource servers. OAuth2 is a mechanism for authorization to allow access to the client resources. We focused on the grant form (authorization code), client ID, and client secret to creating an OAuth2 application.
(keycloak-spring-boot-starter) and configuration of respective key-value pairs; and create and configure Java class with the Spring security (@EnableWebSecurity), Spri Security global method security (@EnableGlobalMethodSecurity), and extension Keycloak web security configuring adapter class.
Clients are services and applications that can request the authentication of use through Keycloak. There are two types of clients [27]. The first kind of client is Keyclo applications that want to encrypt themselves and use SSO. The second category of clien are applications that request an access token to use that access token to access protect resources. Client ID is used in the request to identify the client. We used OpenID Conne (OIDC) as a client protocol in KeyCloak to secure eCoach APIs. There are three acce types [27]: public, confidential, and bearer-only under the OIDC client to grant acce Here, we set access type confidential to obtain client secret and turned-on features, su as Standard Flow Enabled, Direct Access Grants Enabled, Service Accounts Enable Authorization Enabled options [27]. Confidential access type is used for server-side clien to perform login using a client secret and request access tokens to access resources. service that can authenticate a user is an identity provider (IDP). Keycloak is an IDP [2 and acts as an authorization server (AS) (@EnableAuthorizationServer) in the OAut workflow. An authorization point works on the AS, allowing our applications and HTT endpoints to define our system's features. In our eCoach system, two actors who intera with the AS are-ADMIN (resource owner) and USER (client registered with AS) as t fundamental use cases depicted in Figure 4. The resource server (@EnableResourceServe is an application that provides clients with an access token to access the HTTP endpoi resource server. It is a library set that includes HTTP endpoints, static tools, an interactive web pages. Our implemented microservices are depicted in Figure 5 as u cases of resource servers. OAuth2 is a mechanism for authorization to allow access to t client resources. We focused on the grant form (authorization code), client ID, and clie secret to creating an OAuth2 application.  JavaScript Object Notation Web Token (JWT) represents the claims between parties in a JSON Web Token [14][15][16]. Such tokens are of two types: identity token of the OpenID Connect specification that is a client-dedicated function namespace access token (part of the OpenID Connect and OAuth2 specification and allows H request that grants access to the service). We used ES256 to create a JWT signature. A tokens are typically short-lived and frequently expire after only minutes. The addit refresh token sent by the login protocol allows a new access token to be accessed b application after it expires (see Figure 6). Our Spring application security configur expands the KeyCloak's built-in KeycloakWebSecurityConfigurerAdapter, to includ following features: configure and configureGlobal methods with HttpSecurity to pr application APIs from external attack, authorization, and authentication of an H request, password management with the pbkdf2-sha256 algorithm, session authentic strategy, filter registration, and Keycloak-Springboot configuration resolver. eCo OAuth configuration extends the core classes of the KeyCloak library in SSF for creation, authentication, and retrieval of role-specific access tokens based on authoriz server Uniform Resource Locator (URL), realm, client ID, role, and client secret. The details and their tokens are stored in the in-memory H2 database [27]. JavaScript Object Notation Web Token (JWT) represents the claims between two parties in a JSON Web Token [14][15][16]. Such tokens are of two types: identity token (part of the OpenID Connect specification that is a client-dedicated function namespace) and access token (part of the OpenID Connect and OAuth2 specification and allows HTTP request that grants access to the service). We used ES256 to create a JWT signature. Access tokens are typically short-lived and frequently expire after only minutes. The additional refresh token sent by the login protocol allows a new access token to be accessed by the application after it expires (see Figure 6). Our Spring application security configuration expands the KeyCloak's built-in KeycloakWebSecurityConfigurerAdapter, to include the following features: configure and configureGlobal methods with HttpSecurity to protect application APIs from external attack, authorization, and authentication of an HTTP request, password management with the pbkdf2-sha256 algorithm, session authentication strategy, filter registration, and Keycloak-Springboot configuration resolver. eCoach's OAuth configuration extends the core classes of the KeyCloak library in SSF for user creation, authentication, and retrieval of role-specific access tokens based on authorization server Uniform Resource Locator (URL), realm, client ID, role, and client secret. The user details and their tokens are stored in the in-memory H2 database [27].

Developing SSK in an Architecture
We deployed the SSK security scheme in our digital architecture with extended security features (see Figure 2). Cross-Origin Resource Sharing (CORS) is a protection principle that enables resources implemented in web browsers to be restricted. It keeps the external code from creating or consuming requests from unwanted sources. Our eCoach's RESTful APIs support the CORS on SSL-enabled tomcat port 8443 with @CrossOrigin annotation. By design, the Spring Boot application uses the HTTP 8080 port when the application begins. However, we created a self-signed SSL certificate to enable HTTPS and port 8443 with the code-keytool-genkey-alias apachetomcat-storetype PKCS12-keyalg RSA-keysize 2048-keystore eCoachKey.p12-validity 3650. The Keystore file path was then added to the configuration file of the Apache-tomcat webserver to change the application startup port from 8080 to 8443. Port 8443 is the default configuration in the Apache-tomcat webserver to allow HTTPS traffic. Moreover, the port number can be customized.
Passay [44] is a password generation and validation library based on the Java programming language. It offers a comprehensive list of features for validating/generating passwords and is highly configurable. Its API has the following three core components: Rule (defines password generation policy), PasswordGenerator (password generation with defined ruleset), and PasswordValidator (validates password against a defined rule). We used Passay to generate an initial (system-generated) alphanumeric password of 10-letters and Bcrypt [45] for form-based authentication on the eCoach mobile application to upload activity data from the mobile to the eCoach server. In the sign-up process, the user will enter email, mobile, and role as input, and the system will create their UUID, default encrypted password for basic and Keycloak authentication. The user must change their default password after successful account creation and enable the google authenticator on their mobile phone for 6-digit OTP generation with the SHA512 algorithm for the two-factor authentication process at Keycloak. Figure 7 illustrates the sequence diagram of the SSK-based authentication and authorization process flow on the eCoach prototype system. The scoped software, libraries, respective versions, and their purpose of usage are described in Tables 4 and 5.

Developing SSK in an Architecture
We deployed the SSK security scheme in our digital architecture with extended security features (see Figure 2). Cross-Origin Resource Sharing (CORS) is a protection principle that enables resources implemented in web browsers to be restricted. It keeps the external code from creating or consuming requests from unwanted sources. Our eCoach's RESTful APIs support the CORS on SSL-enabled tomcat port 8443 with @CrossOrigin annotation. By design, the Spring Boot application uses the HTTP 8080 port when the application begins. However, we created a self-signed SSL certificate to enable HTTPS and port 8443 with the code-keytool-genkey-alias apachetomcat-storetype PKCS12-keyalg RSA-keysize 2048-keystore eCoachKey.p12-validity 3650. The Keystore file path was then added to the configuration file of the Apache-tomcat webserver to change the application startup port from 8080 to 8443. Port 8443 is the default configuration in the Apache-tomcat webserver to allow HTTPS traffic. Moreover, the port number can be customized.
Passay [44] is a password generation and validation library based on the Java programming language. It offers a comprehensive list of features for validating/generating passwords and is highly configurable. Its API has the following three core components: Rule (defines password generation policy), PasswordGenerator (password generation with defined ruleset), and PasswordValidator (validates password against a defined rule). We used Passay to generate an initial (system-generated) alphanumeric password of 10-letters and Bcrypt [45] for form-based authentication on the eCoach mobile application to upload activity data from the mobile to the eCoach server. In the sign-up process, the user will enter email, mobile, and role as input, and the system will create their UUID, default encrypted password for basic and Keycloak authentication. The user must change their default password after successful account creation and enable the google authenticator on their mobile phone for 6-digit OTP generation with the SHA512 algorithm for the two-factor authentication process at Keycloak. Figure 7 illustrates the sequence diagram of the SSK-based authentication and authorization process flow on the eCoach prototype system. The scoped software, libraries, respective versions, and their purpose of usage are described in Tables 4 and 5.

Experimental Setup
A security testing method is designed to expose weaknesses in an information system's security mechanisms that safeguard data and preserve functionality as expected. It can normally be broken down into measures that are functional and non-functional [46]. Security checks are carried out in many ways, each of which is intended to verify the security principles [46,47]. We used unit testing and non-functional penetration (pen) testing as security testing methods. Unit testing was performed with Postman, web-browser, and Mock MVC (Mockito) [48] to check security intended functionalities. Penetration testing facilitates finding out the weaknesses of a computer system, a web application, or a network. It can be of three types-black box testing, white box testing, and gray box testing. The most common penetration testing method is to scan the target for vulnerabilities. The target of penetration testing can be an operating system, database system, application, or network environment. This study has focused on the security of the MSA APIs and concentrated on penetration testing for network environments. Therefore, we used Wireshark software only for gray box penetration testing for web application tests that checked the security vulnerabilities (e.g., DoS, DDoS, IP spoofing, port scan) at the network side.
We implemented the SSK security solution first in an unprotected windows environment. We then deployed the codebase in a Linux environment (see Table 6), protected with VPN and network firewall to compare pen testing's [47,48] performance in two scenarios. In addition, we set up Apache JMeter to perform a scalability testing of the adopted approach.

Experimental Results
All the simulated attacking parameters, outcomes, and network protocol analysis report results are described and discussed in this section. Experiments related to CSRF, XSS, Clickjacking, content sniffing, and brute force were conducted with Mockito, Keycloak UI, and Postman. DoS, DDoS, IP spoofing, MITM, and port scanning were performed with simulated code, Wireshark network analyzer, based on explicit filter patterns (see Table 7), system commands in Windows and Linux (Ubuntu) environments. In the Spring codebase, we created eight unit-test cases with Mockito for test user creation with role assignment, basic (HTTP form-based) user authentication, two-factor user authentication (password + OTP), and role-based authorization (OAuth2) with an access token. We executed a negative test scenario where the user received an expected error response code (HTTP 401) due to prohibited access to an unauthorized resource API endpoint. Table 8 defines the combined result of Mockito test performance in a vanilla test setting where we compared our API response time with preferred, acceptable, and delayed response time. The response metrics can be classified into the following categories-mean response time, peak response time, and error rate. We have considered the mean response time in this study.   Spring boot application extends default spring security class WebSecurityConfig to allow protection against CSRF attacks. CSRF tokens are powerful and unpredictable, created as session tokens with specific properties that the attacker cannot calculate or predict. Both post forms in the "Java Server Page (JSP)" or template files need to include the CSRF token. If it is a JSON call, the token must be added to the header. Initially, we disabled KeyCloak token-based security setup and extended Spring's default web security configuration. Subsequently, we executed the following four test cases for CSRF attack with Postman-CSRF disabled (valid credential, invalid credential), and CSRF enabled (valid credential and valid _csrf token, valid credential, and invalid _csrf token). Successful authentication resulted in an HTTP status code 200 or 201. However, we disabled the CSRF token generation in actual security solution implementation. The reason for disabling CSRF is that our developed spring boot application is available to the public. Therefore, we replicated similar and more robust web security measures with KeyCloak's two-factor authentication and access token-based authorization. The successful test results are captured in Table 9. To ensure protection against XSS, Clickjacking, and content sniffing, we facilitated KeyCloak's configurable security defense. We tested the attack with a client's HTTP POST request with Postman for new user creation and investigated whether XSS, Clickjacking, and content sniffing securities are allowed in the response header. Setup data and documented response headers as shown in Table 9. To ensure protection against brute force attacks, we enabled KeyCloak's configurable security defense. According to our Keycloak security configuration, the user will get a chance of a maximum of six login failures before their account gets locked. The failure reset time is 12 h. Our analysis uses Spring Security with KeyCloak to model the case attacker using the password dictionary to execute the brute force attack. We set up the data in Postman and recorded the response headers. The brute force attack's unit test with Postman is presented in Table 10. We first tested the DoS and DDoS attack in an unprotected windows server, where we configured the KeyCloak server and Apache-tomcat web server to deploy the eCoach prototype system. Then, we wrote a Java multi-threading code [49] to create parallel HTTP calls to an example exposed API. For checking the DoS attack, we executed the java code from a single JVM, and for simulating DDoS, we executed the code from multiple JVMs in parallel. After an average of 3-5 min of parallel URL connection request traffic, the server produced high utilization of CPU and memory high network throughput, and thus, resulting in unresponsive API.
We used tcp.flags.syn == 1 and tcp.flags.ack == 1 and tcp.flags.syn == 1 and tcp.flags.ack == 0 filter in Wireshark to detect TCP SYN floods due to DoS attack and found how the windows server IP was flooded with incoming packets. We replicated the experiment in the Linux server protected with VPN and network firewall. We observed that packets outside of the VPN were blocked. We utilized other filters specified in Table 7 to analyze incoming network packets to detect attacks, such as IP spoofing and MITM with Wireshark. To detect network packet sniffing with Wireshark, we studied source and destination IP, ports, and protocols, such as Media Access Control (MAC), Dynamic Host Configuration Protocol (DHCP), DNS, TCP, User Datagram Protocol (UDP), and Address Resolution Protocol (ARP) with the following metrics: packet count, rate (milliseconds or Milli sec.), percent, burst rate, and burst start. We found that VPN protects the eCoach E-2-E network communication. A network firewall, and an SSL certificate on top of the API endpoint access security, made the eCoach API endpoint safe from major external vulnerabilities, such as DoS, DDoS, IP spoofing, and MITM. API endpoint security indirectly ensures the privacy of personal health data inside of our eCoach prototype system.
To perform scalability testing in JMeter, we selected an eCoach REST service with an approximated 257 Bytes of a request body, 43.42 Kilobytes of the response body, and a response time of 141 msec. (see Figure 8). Using JMeter "Thread Group" feature, concurrent threads, or loads (X) had been created with three different values of ramp-up seconds (Y) and a loop count value of five (Z). At each iteration, X × Z number of loads were created to capture mean throughput and mean latency time. The results are described in Tables 11-13. The result shows a direct proportion between throughput and load (S α l) and latency time and load (L α l). However, achieving a certain threshold, the throughput sinks with increased load (S α 1 l ). We have considered the following values for scalability testing; however, the range can be increased for the upcoming studies.

Discussion
Using the SSK security solution, personal health data governance has fulfilled the General Data Protection Regulation (GDPR) compliance checklist as specified in Table 14. It is three-fold research: • First, we implemented a security solution with SSF, basic authentication, two-factor authentication, and authorization (OAuth2) with an open-source KeyCloak server (IDP), VPN, network firewall, and SSL. • Second, we implemented the solution for developing a digital infrastructure where we deployed an eCoach prototype system. • Third, we performed testing of the prototype APIs against the common external vulnerabilities, as described in Table 15. Table 14. GDPR compliance checklist for SSK.

GDPR Checklist [50,51] Addressed
Lawful basis and transparency Yes Data security Yes Accountability and governance Yes Privacy rights Yes Table 15. Summary of the adopted functional and non-functional testing.

Basic authentication
Access with a valid credential Yes Access with an invalid credential Yes Two-factor authentication Access with a valid credential + OTP Yes Access with an invalid credential/an incorrect OTP Yes New user creation and role assignment Creation request with a valid role assignment Yes

Role-based API access
Access with a valid access key Yes Access with an invalid access key Yes CSRF disabled Access with a valid credential Yes We created 22 test cases for 16 test scenarios to replicate external attacks as our SSK security solution. SSK security implementation and configuration in the prototype system successfully secured the eCoach APIs from an attack in all scenarios with 100% test accuracy. Furthermore, we performed a qualitative analysis on the effectiveness of SSK in Table 16 after comparing SSK with Spring Security and Keycloak against certain security features.