top of page
Writer's picturePatel Harsh

Authentication in SpringBoot Using JWT and OAuth 2.0.

Understanding JWT (JSON Web Tokens)

In today's interconnected web ecosystem, secure authentication is paramount. JSON Web Tokens (JWT) have emerged as a popular method for securely transmitting information between parties in a compact and verifiable format. Let's dive into what JWTs are, how they work, and why they are widely used in modern web development.

What is JWT?

JWT, or JSON Web Token, is an open standard that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.

JWT Structure

A JWT consists of three parts separated by dots (.):

  1. Header: Contains metadata about the type of token and the signing algorithm being used.

  2. Payload: Contains claims (statements) about an entity (typically the user) and additional data.

  3. Signature: Used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn't changed along the way.

How JWT Works

  1. Authentication: When a user logs in to a system, the server generates a JWT and sends it back to the client and stores on client browser.

  2. Authorization: The client includes the JWT (Acces from browser's local storage) in subsequent requests to the server. The server verifies the JWT's signature and decodes the payload to authorize the user.

Benefits of Using JWT

  • Compact: JWTs are compact in size, making them efficient for transmission over networks.

  • Stateless: Since JWTs contain all necessary information, servers don't need to store session state.

  • Versatile: JWTs can be used for authentication and information exchange in various scenarios, including single sign-on (SSO).

Implementing JWT in Web Applications

Here's a simplified example of how JWT can be implemented in a web application using a hypothetical scenario:

Scenario:

Imagine a blogging platform where users can authenticate and create posts.

Implementation Steps:

  1. Authentication: User logs in with username and password.

  2. JWT Generation: Upon successful authentication, the server generates a JWT containing user ID and roles.

  3. JWT Usage: The client stores the JWT securely (typically in local storage or cookies) and sends it with each subsequent request.

  4. JWT Verification: Server verifies the JWT's signature and decodes the user information from the payload to authorize access to resources (e.g., creating a new blog post).

In our previous discussion on JWT (JSON Web Tokens), we explored how JWTs provide a secure and efficient method for transmitting information between parties in a web application. Now, let's delve into OAuth, another vital component in modern web authentication frameworks.

Why is OAuth Needed?

In today's interconnected digital landscape, users often access multiple services and applications using their credentials from various platforms (e.g., signing into a website using Google or Facebook credentials). OAuth addresses several critical challenges:

  • Security: OAuth eliminates the need for applications to store user credentials, reducing the risk of unauthorized access or data breaches.

  • User Experience: It enables seamless single sign-on (SSO) experiences across different services, enhancing user convenience.

  • Integration: OAuth allows developers to integrate their applications with third-party services (like social media platforms or APIs) without requiring users to share their passwords.

Enter OAuth: A Secure and Convenient Solution

OAuth provides a secure way for users to grant third-party applications access to their data on other platforms. Here's the basic flow:

  • User Initiates Login: You want to log in to a new website using your existing social media account.

  • Redirection to Authorization Server: The website redirects you to the authorization server (e.g., Facebook or Google).

  • Login and Consent: You log in to the authorization server and grant permission to the website to access specific data (photos, email, etc.).

  • Authorization Code Grant: The authorization server sends a temporary authorization code back to the website.

  • Token Request: The website exchanges the authorization code for an access token from the authorization server.

Access Granted (or Denied): The website uses the access token to access your data on the authorization server, granting access to the requested resource or denying it if permission wasn't granted.


Now, Lets understand how we can use OAuth 2.0 with Google Authentication in Spring Boot Application. This will allow users to sign in using their Google credentials and access protected resources within our application.

Prerequisites

Before we begin, ensure you have the following:

  1. Basic knowledge of Spring Boot and Spring Security.

  2. Java Development Kit (JDK) installed on your machine.

  3. A Google Developer account to create OAuth 2.0 credentials.

Step 1: Set Up a Spring Boot Application


If you haven't already, set up a Spring Boot application using Maven. You can use Spring Initializr (https://start.spring.io/) to generate a new project with dependencies with Spring Web and OAuth2 Client. Step 2: Configure OAuth 2.0 with Google

  1. Create OAuth 2.0 Credentials on Google Developer Console:

  • Go to the Google Developer Console and create a new project.

  • Navigate to APIs & Services -> Credentials and click Create Credentials -> OAuth client ID.

  • Select Web application as the application type.

  • Add your Spring Boot application's base URL (e.g., http://localhost:8080/login/oauth2/code/google) as an authorized redirect URI.

  1. Configure Application Properties

Step 3: Create OAuth 2.0 Login Configuration

Configure Security:

  • Create a security configuration class annotated with @EnableWebSecurity, @Configuration  and configure OAuth 2.0 login:

Code snippet for Configuration.

Breakdown of the Code

1. http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())

  • Purpose: This part defines authorization rules for HTTP requests.

  • Explanation:

  • http.authorizeHttpRequests() configures authorization for HTTP requests in Spring Security.

  • .anyRequest().authenticated() specifies that any HTTP request to the application's endpoints must be authenticated. This means users must be logged in to access any endpoint.

2. oauth2Login(Customizer.withDefaults())

  • Purpose: Configures OAuth 2.0 login functionality.

  • Explanation:

  • .oauth2Login() sets up OAuth 2.0 login support in Spring Security, allowing users to authenticate using OAuth 2.0 providers like Google, Facebook, etc.

  • Customizer.withDefaults() is a convenient method provided by Spring Security that applies default settings for OAuth 2.0 login configuration. It sets up the necessary filters and handlers to initiate OAuth 2.0 authentication flows and handle callbacks.

3. return http.build()

  • Purpose: Constructs and returns a SecurityFilterChain.

Explanation:

  • http.build() finalizes the configuration defined in the HttpSecurity object (http) and constructs a SecurityFilterChain.

  • SecurityFilterChain represents a chain of security filters that intercept requests, enforce security rules, and handle authentication and authorization processes.


Step 4: Implement OAuth 2.0 Login and Authorization Flows

Implement controllers and views to handle OAuth 2.0 login and secure access to your application resources. Here's a simplified example:

Code Snippest for simple get request.


Step 5: Run and Test Your Application

  1. Run Your Application:

  • Start your Spring Boot application.

  1. Test OAuth 2.0 Login:

  • Access http://localhost:8080 in your browser.

  • Click on the "Login with Google" link to initiate the OAuth 2.0 flow.

  • Authenticate with your Google account. Upon successful authentication, you'll be redirected back to your application.


Conclusion

By setting up a Spring Boot application with OAuth 2.0 dependencies and configuring OAuth 2.0 client for Google, you can enable secure and seamless authentication using Google credentials. This approach simplifies integration with OAuth 2.0 providers and enhances user experience by leveraging existing authentication infrastructure.


OAuth 2.0 in Spring Boot applications facilitates robust and scalable authentication solutions, making it an essential tool for modern web development.

24 views0 comments

Recent Posts

See All

Battle of the Backends: Java vs Node.js

Comparing Java and Node.js involves contrasting two distinct platforms commonly used in backend development. Here’s a breakdown of their...

Comments


bottom of page