Tuesday, December 31, 2024

Securing Microservices with JWT Authentication and Data Encryption

Securing Microservices with JWT Authentication and Data Encryption

Securing Microservices with JWT Authentication and Data Encryption

In modern microservices architectures, securing communication and data integrity are paramount. This article explores how JWT (JSON Web Token) authentication and data encryption can bolster security, ensuring that data exchanges between services remain confidential and trusted.

What is JWT Authentication?

JWT is a compact, URL-safe token format that securely transmits information between parties as a JSON object. It is widely used in microservices for its simplicity and efficiency.

Parts of a JWT Token

A JSON Web Token (JWT) consists of three parts, separated by periods (.):

  • Header: Specifies the token type (JWT) and signing algorithm (e.g., HS256 or RS256).
  • Example: { "alg": "HS256", "typ": "JWT" }
  • Payload: Contains claims about the user or the token itself. Claims can be:
    • Registered claims: Predefined fields like iss (issuer), sub (subject), exp (expiration time), etc.
    • Public claims: Custom claims, such as user roles or permissions.
    • Private claims: Claims specific to the application, like user IDs.
    Example: { "sub": "1234567890", "name": "John Doe", "admin": true, "iat": 1516239022 }
  • Signature: Ensures the token's integrity and authenticity. It is generated by signing the encoded header and payload with a secret or private key.
    Example for HMAC-SHA256:
    HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret )
A full JWT might look like this: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Shared Key vs. Public Key JWT in Microservices

Shared Key-Based JWT:

  1. How It Works:
    • A single secret key is used for both signing and verifying the token.
    • This secret must be shared between the microservices.
  2. Advantages:
    • Simple setup.
    • Suitable for small-scale systems with fewer services.
  3. Disadvantages:
    • Security Risk: If the key is compromised, all services relying on it are at risk.
    • Key Distribution: Sharing the key securely across multiple services can be challenging.

Public Key-Based JWT in Microservice

  1. How It Works:
    • The authentication server uses a private key to sign the JWT.
    • Microservices use a public key to verify the token's signature.
  2. Advantages:
    • Better Security: The private key remains on the authentication server, and only the public key is distributed.
    • Scalability: New services can independently verify tokens without needing access to the private key.
    • No Shared Secrets: Eliminates the need to distribute a secret key.
  3. Disadvantages:
    • Slightly more complex setup due to key management.
    • Requires a system to distribute the public key, like a JWKS (JSON Web Key Set) endpoint.
    • No Shared Secrets: Eliminates the need to distribute a secret key.

Data Encryption in Microservices

Encryption ensures sensitive data remains confidential and secure during transmission and storage.

Types of Encryption

  • Symmetric Encryption: Uses the same key for encryption and decryption.
  • Asymmetric Encryption: Utilizes a public key for encryption and a private key for decryption.

Encryption in Microservices Communication

  • Transport-Level Encryption: Secures data in transit using TLS (HTTPS).
  • Message-Level Encryption: Encrypts specific message payloads for added confidentiality.

Combining JWT and Encryption

  • Token Encryption: Adds a layer of security to JWTs by making intercepted tokens unreadable.
  • Public Key Infrastructure: Manages keys securely for token validation and encrypted communication.

Best Practices

  • Set reasonable expiration times for tokens and use refresh tokens for longer sessions.
  • Rotate encryption keys periodically to minimize security risks.
  • Audit and log token usage to detect anomalies.

Conclusion

JWT authentication and encryption are foundational to building secure microservices. By combining these technologies, you can ensure robust authentication, data confidentiality, and integrity across your system. Follow best practices to simplify implementation and focus on delivering high-quality services.

Tuesday, November 15, 2022

Android aar deployment in Maven - 2022

Introduction

If you are working on android library project, you might be wondering how to publish it on Maven like this. Earlier it was done using Android studio plugin maven, but with gradle v 7.0+ it does not work. Now we have to use maven-publish. This post gives you more insights of this procedure.

Generally, there are two types of repositories: local and remote.

A local repository is the repository Maven creates on the computer it is building on. It is usually located under the $HOME/.m2/repository directory.

Remote repository is located on maven server. When any user wants to use our library, they will enter groupId and version of library they want to use.
We will create and deploy a new android aar artifact on maven.
The process can be summarized as
1. Create Account and repository on Nexus sonatype
2. Configure gradle to create, sign and upload aar file to sonatype.
3. Let sonatype verify the artifacts as per maven requirement (Close operation)
4. Release artifacts to maven.

Let's go through the steps one by one.

1. Create account on sonatype at https://issues.sonatype.org/secure/Dashboard.jspa. Register new project by creating new jira ticket. It will create new repository in sonatype
Create → Create Issue → Community Support - Open Source Project Repository Hosting → New Project → with groupid io.bitbucket.swapnilcpublic e.g. OSSRH-85813

2. You will be asked to prove that you own the domain mentioned in Jira ticket. (e.g. https://bitbucket.org/swapnilcpublic). You will be asked to place a file or create git repo under the domain to prove that it really belongs to you. Since I do not own a domain name, I created empty bitbucket repo under bitbucket repo. Here ossrh-85813 is the JIRA ticket id. For more details follow how-to-set-txt-record and personal groupId. If required a static web site can be created using bitbucket.

3. Signing: One of the requirements for publishing your artifacts to the Central Repository, is that they have been signed with PGP. Here is how tosetup signing with gpg.
Create new key with details like

Name: SwapnilGpg
Email: email@id.com
Pass: password
After creation, see created keys with
Export secret keys using
We need short key. It will be referred from gradle script. It appears after `rsa4096/` in output. Find short KeyId using
Once the GPG keys are generated, publish these keys to an open key server. Run the following command to do so. YYYYYYYY is the short key generated using previous step (E72FECF1 in my case).

Verify these keys using

4. Update build.gradle in ProjectRoot/swapnilCalculator/build.gradle with following

5. Add details below in ProjectRoot/gradle.properties In ProjectRoot/swapnilCalculator/gradle.properties

6. Upload aar, jar and signatures using
./gradlew clean publishReleasePublicationToMavenRepository After a successful deployment to OSSRH your components are stored in a separate, temporary repository, that is private to your projects members. In order to get these components published you will have to 'close' & release' them. 'Close' operation checks whether all artifacts are as specified by Maven. 'Close' operation takes few minutes to finish. Once that is successful, proceed with 'release' operation. If there is error, please resolve them and re-upload the library.
After uploading & releasing all artifacts, it takes 4-10 hours for maven to show the library.

7. Find the published library using

  1. Sonatype staging repository
  2. Maven repository
  3. Maven repository
  4. Sonatype staging repository
  5. Sonatype nexus

8. References

  1. https://gist.github.com/lopspower/6f62fe1492726d848d6d
  2. https://central.sonatype.org/publish/
  3. https://central.sonatype.org/publish/requirements/coordinates/
  4. https://central.sonatype.org/publish/publish-guide/
  5. https://shahsurajk.medium.com/technical-publishing-aars-to-maven-central-7e9c603f9ea1
  6. https://www.baeldung.com/maven-snapshot-release-repository
  7. https://docs.gradle.org/current/userguide/signing_plugin.html#sec:signatory_credentials
  8. https://docs.gradle.org/current/userguide/publishing_maven.html

Securing Microservices with JWT Authentication and Data Encryption

Securing Microservices with JWT Authentication and Data Encryption Securing Microservices with JWT A...