Securing Your Microservices: A Comprehensive Guide
There are new considerations for managing authentication and authorization in microservice environments. With a monolithic application, it is common to have fine grained roles, or at least role associated groups in a central user repository. With the emphasis on independent lifecycles for microservices, however, this dependency is an anti-pattern. Development of an independent microservice is then constrained by and coupled with updates to the centralized resource.
It is common to have authentication (establishing the user’s identity) performed by a dedicated, centralized service or even an API gateway. This central service can then further delegate user authentication to a third party.
When working with authorization (establishing a user’s authority or permission to access a secured resource), in a microservices environment keep group or role definitions coarse grained in common, cross cutting services. Allow individual services to maintain their own fine grained controls. The guiding principle again is independence. A balance must be found between what can be defined in common authorization service to meet requirements for the application as a whole, and what authorization requirements are implementation details for a particular service.
OAuth 2.0
The OAuth 2.0 authorization framework enables a third-party application to obtain limited access to an HTTP service, either on behalf of a resource owner by orchestrating an approval interaction between the resource owner and the HTTP service, or by allowing the third-party application to obtain access on its own behalf.
The service interaction goes through these steps:
The front end (web client or mobile application) makes a request to the Auth service on behalf of the user.
The Auth service returns a forwarding response that is automatically handled by the browser to forward the user to the selected OAuth provider with the application identifier.
After the user has authenticated and granted permission, the OAuth provider returns an authorization code in another redirect response. The browser automatically handles the redirect to invoke a callback on the Auth service with the authorization code.
The Auth service then contacts the OAuth provider to exchange the authorization code for an access token.
The Auth service then converts data from that token into a Signed JSON Web Tokens (JWTs), which allows you to verify the identity of the user over subsequent inter-service calls without going back to the OAuth provider.
Spring Boot and OAuth2 Implementation
JWT
JWTs are designed for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed.
Although JWTs can be encrypted to also provide secrecy between parties, we will focus on signed tokens. Signed tokens can verify the integrity of the claims contained within it, while encrypted tokens hide those claims from other parties. When tokens are signed using public/private key pairs, the signature also certifies that only the party holding the private key is the one that signed it.
Structure : A JWT is composed of three parts separated by dots (`.`):
Header
The header typically consists of two parts: the type of the token, which is JWT, and the signing algorithm being used, such as HMAC SHA256 or RSA.
For example:
{ "alg": "HS256", "typ": "JWT" }
Payload
The second part of the token is the payload, which contains the claims. Claims are statements about an entity (typically, the user) and additional data. There are three types of claims: registered, public, and private claims.
Registered claims: These are a set of predefined claims which are not mandatory but recommended, to provide a set of useful, interoperable claims. Some of them are: iss (issuer), exp (expiration time), sub (subject), aud (audience).
Public claims: These can be defined at will by those using JWTs. But to avoid collisions they should be defined in the IANA JSON Web Token Registry or be defined as a URI that contains a collision resistant namespace.
Private claims: These are the custom claims created to share information between parties that agree on using them and are neither registered or public claims.
Example Paylod :
{
"sub": "1234567890",
"name": "John Doe",
"admin": true
}
Signature:
To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.
For example if you want to use the HMAC SHA256 algorithm, the signature will be created in the following way:
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret)
Complete JWT Example
A complete JWT looks like this:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
How do JSON Web Tokens work?
In authentication, when the user successfully logs in using their credentials, a JSON Web Token will be returned. Since tokens are credentials, great care must be taken to prevent security issues. In general, you should not keep tokens longer than required.
You also should not store sensitive session data in browser storage due to lack of security.
Whenever the user wants to access a protected route or resource, the user agent should send the JWT, typically in the Authorization header using the Bearer schema. The content of the header should look like the following:
Authorization: Bearer <token>
When Should you use Json Web Tokens?
Here are few scenarios on when should we consider using the Json Web tokens.
Authentication
One of the most common scenario of using JWT is authentication. When an user logs in with the credentials like username and password, each subsequent request will include the JWT, which allows the user to access routes, services and resources. JWT has been widely used in a function called Single Sign On (SSO) because of its small overhead and also it can be easily used across different domains.
Information Exchange
Any kind of data can be transmitted securely between parties since they can be signed, which means you will know who the senders are and furthermore the structure of JWT allows users to verify whether the transmitted data has been tampered with or not.
Rate Limiting
Rate limiting is a feature that can be implemented in a service to prevent consumers from diminishing stability by making too many requests. Consumers can be given a limit on the number of requests they make. This limit could be per consumer, per user per consumer, or whatever you decide. If limits are per consumer, then depending on how much your server trusts the consumer, the limits could be higher. Some services even offer a subscription fee for increasing this limit.
Rate limiting should not be enforced if your service is consumed only internally. It should be enforced only at the furthest point downstream where user requests first enter your organization.
If your service makes use of rate limits, be sure information about the limit can be accessed programmatically.
Below is an example of how GitHub conveys rate limit information to third parties with the introduction of X-RateLimit headers. The Limit header represents the total limit per period of time, Remaining is how many requests remain to be made during this period of time, and Reset is a timestamp for when the period resets.
Example of Exceeding GitHub’s Rate Limit
HTTP/1.1 403 Forbidden
Date: Tue, 20 Aug 2013 14:50:41 GMT
Status: 403 Forbidden
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1377013266
{
"message": "API rate limit exceeded. \
See http://developer.github.com/v3/ \
#rate-limiting for details."
}
API Gateways
An API Gateway is essentially a single entry point, or a Reverse proxy, that sits between client applications and a collection of backend services.
By funneling all traffic through a single point, API Gateways can enforce security policies, manage SSL/TLS, and handle authentication. This not only reduces the attack surface but also simplifies compliance with various standards.
What API Gateway Do ?
RateLimiting
The Gateway can limit the number of requests from clients to prevent overloading the backend services. This is useful for controlling abusive traffic and ensuring fair usage of resources.
SSL Termination :
SSL Termination is a crucial function of an API Gateway that involves handling and decrypting incoming HTTPS (SSL/TLS) traffic. This process removes the encryption layer, allowing internal services to handle requests as regular HTTP traffic.
Authentication
The Gateway acts as a security layer, handling authentication (e.g., OAuth, JWT, API keys) and enforcing access control policies. It ensures only authorized requests reach the services.
IP-Whitelisting
IP Whitelisting is a security measure that restricts access to services by allowing only certain pre-approved IP addresses to communicate with an application or network resource. This technique ensures that only trusted users or systems, originating from the specified IP addresses, can access the protected resource.
Serving Static Content
API Gateways can serve static content such as HTML, JavaScript, images, and CSS directly from a cloud storage service (e.g., AWS S3, Azure Blob Storage) or from a cache without routing to backend services. This improves performance and reduces the load on application servers.
Secure Headers
Secure headers are an essential aspect of web application security, providing an extra layer of defense against common vulnerabilities. Here's a brief explanation of the commonly used secure headers and how they improve API security:
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.headers()
// X-XSS-Protection
.xssProtection()
.block(true)
.and()
// X-Frame-Options
.frameOptions()
.deny()
.and()
// Strict-Transport-Security (HSTS)
.httpStrictTransportSecurity()
.includeSubDomains(true)
.maxAgeInSeconds(31536000)
.and()
// X-Content-Type-Options
.contentTypeOptions()
.and()
// Content-Security-Policy (CSP)
.contentSecurityPolicy("default-src 'self'; script-src 'self' https://trusted-scripts.com")
.and()
// Referrer-Policy
.referrerPolicy(ReferrerPolicyHeaderWriter.ReferrerPolicy.NO_REFERRER)
.and()
.and()
.csrf().disable(); // CSRF disabled just for this example, adjust as needed
}
}
1. X-XSS-Protection:
Purpose: Enables the browser’s XSS filter, helping prevent cross-site scripting (XSS) attacks.
Example:
X-XSS-Protection: 1; mode=block
Benefit: It blocks the page when an XSS attack is detected, reducing the risk of malicious script execution.
2. X-Frame-Options:
Purpose: Controls whether a web page can be embedded in an
<iframe>
.Example:
X-Frame-Options: DENY
Benefit: Prevents clickjacking attacks by ensuring the page cannot be loaded in a frame or iframe.
3. Strict-Transport-Security (HSTS):
Purpose: Enforces the use of secure (HTTPS) connections, protecting against man-in-the-middle attacks.
Example:
Strict-Transport-Security: max-age=31536000; includeSubDomains
Benefit: Ensures that browsers only connect via HTTPS, even if users attempt to access a resource using HTTP.
4. Content-Security-Policy (CSP):
Purpose: Specifies which resources can be loaded on a web page, controlling scripts, images, styles, and more.
Example:
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted-scripts.com
Benefit: Helps prevent various types of injection attacks, such as XSS, by restricting what content the browser can load.
5. X-Content-Type-Options:
Purpose: Prevents the browser from guessing the MIME type and forces it to respect the server's declared content type.
Example:
X-Content-Type-Options: nosniff
Benefit: Protects against MIME-sniffing attacks, reducing the risk of drive-by downloads or unintended content execution.
6. Referrer-Policy:
Purpose: Controls how much referrer information should be sent with requests to other sites.
Example:
Referrer-Policy: no-referrer
Benefit: Prevents sensitive information from being exposed in the referrer header when navigating between pages.
HTTPS and SSL/TLS
HTTPS
HTTP is a protocol or set of communication rules for client-server communication over any network. HTTPS is the practice of establishing a secure SSL/TLS protocol on an insecure HTTP connection.
Before it connects with a website, your browser uses TLS to check the website’s TLS or SSL certificate. TLS and SSL certificates show that a server adheres to the current security standards. You can find evidence about the certificate within the browser address bar. An authentic and encrypted connection displays https:// instead of http://. The additional s stands for secure.
Why is HTTPS important? What happens if a website doesn’t have HTTPS?
HTTPS prevents websites from having their information broadcast in a way that’s easily viewed by anyone snooping on the network. When information is sent over regular HTTP, the information is broken into packets of data that can be easily “sniffed” using free software. This makes communication over the an unsecure medium, such as public Wi-Fi, highly vulnerable to interception. In fact, all communications that occur over HTTP occur in plain text, making them highly accessible to anyone with the correct tools, and vulnerable to on-path attacks.
With HTTPS, traffic is encrypted such that even if the packets are sniffed or otherwise intercepted, they will come across as nonsensical characters. Let’s look at an example:
Before encryption:
This is a string of text that is completely readable
After encryption:
ITM0IRyiEhVpa6VnKyExMiEgNveroyWBPlgGyfkflYjDaaFf/Kn3bo3OfghBPDWo6AfSHlNtL8N7I
SSL/TLS
SSL stands for Secure Sockets Layer, and it refers to a protocol for encrypting, securing, and authenticating communications that take place on the Internet. Although SSL was replaced by an updated protocol called TLS (Transport Layer Security) some time ago, "SSL" is still a commonly used term for this technology.
The main use case for SSL/TLS is securing communications between a client and a server, but it can also secure email, VoIP, and other communications over unsecured networks.
What is the difference between SSL certificates and TLS certificates?
At present, all SSL certificates are no longer in use. TLS certificates are the industry standard. However, the industry continues to use the term SSL to refer to TLS certificates.
TLS certificates have iterated upon SSL certificates and improved them over time. The final function of SSL certificates and TLS certificates hasn’t changed.
Implement SSL certificates in Spring Boot Application .
If you find this article useful Please leave a like , subscribe and share my blog .
Follow me on LinkedIn | X