DEV Community

Cover image for Spring Security with Oauth 2.0
Zeki
Zeki

Posted on • Updated on • Originally published at codeline24.com

Spring Security with Oauth 2.0

Spring Security, a popular security framework for Java applications, integrates seamlessly with OAuth 2.0, an industry-standard authorization protocol. This combination empowers developers to implement secure and user-friendly login experiences in their web applications.

What is Oauth 2.0?

OAuth 2.0 is an authorization framework that enables third-party applications to access a user’s resources without divulging the user’s credentials.

It provides a standardized way for users to grant limited access to their resources stored on one site (the resource server) to another site (the client application), without sharing their credentials.

Image description
OAuth 2.0 works by facilitating the exchange of tokens between the client application, the resource server, and an authorization server.

The main components of OAuth 2.0 are:

Resource Owner: The user who owns the resources being accessed. For example, a user’s photos on a photo-sharing website.
Client: The application that wants to access the user’s resources. This could be a web application, mobile app, or desktop application.
Resource Server: The server hosting the user’s resources. It verifies and provides access to the requested resources based on the tokens provided by the client.
Authorization Server: The server responsible for authenticating the user and issuing access tokens to the client after the user grants consent.
OAuth 2.0 operates using different grant types(permissions), each suited for specific use cases, including:

Authorization Code Grant: Suitable for web applications where the client can securely store a client secret.
Implicit Grant: Designed for client-side applications, such as JavaScript apps running in a web browser.
Client Credentials Grant: Used when the client application is the resource owner and doesn’t need user consent.
Resource Owner Password Credentials Grant: Allows the client to authenticate with the resource owner’s credentials directly.
OAuth 2.0 is widely adopted across various platforms and services, including social media platforms, cloud services, and APIs, enabling secure and controlled access to user data while maintaining user privacy and security.

Oauth 2.0 Practical Example

Imagine you’re building a fitness app that wants to access a user’s workout data stored on a separate fitness tracker platform.

Image description

User Initiates Login: The user wants to connect your fitness app to their fitness tracker account. They click a “Connect with Fitness Tracker” button within your app.
Authorization Request: The authorization server displays a login page to the user. Once the user logs in successfully, the server presents a consent screen asking the user if they want to grant your app access to their workout data.
User Grants Consent: If the user agrees, they click “Allow” on the consent screen. This indicates their approval for your app to access their data.
Authorization Code Issued: Upon user consent, the authorization server generates a unique authorization code and redirects the user’s browser back to your app. This code is like a temporary key that your app can exchange for an access token.
Token Request to Token Endpoint: Your app sends a request to the fitness tracker platform’s token endpoint.
Access Token Granted: The token endpoint verifies the authorization code and your app’s credentials. If everything is valid, it generates an access token and (optionally) a refresh token and sends them back to your app.
Request Resources: Your app stores the access token securely and uses it to make API calls to the fitness tracker platform to retrieve the user’s workout data.
Token Validated: Resource Server validate access token again Auth. Server.
Resources Returned: With the access token, your app can now access the user’s workout data from the fitness tracker platform and display it within your app.

Spring Security

Spring Security is a powerful and customizable authentication and access control framework for Java applications, particularly those built using the Spring Framework.

It provides comprehensive security features to address authentication, authorization, session management, and protection against common security threats.

The main requirement to run Spring Security is a Java 8 or higher Runtime Environment (JRE). Spring Security is designed to be self-contained within your application, so you don’t need any additional configuration on the JRE itself.

Image description

Spring Security utilizes a filter chain, a series of filters, to intercept and process incoming HTTP requests in a web application.

This chain acts like a security assembly line, with each filter performing a specific task related to authentication and authorization.

The AuthenticationManager serves as the heart of authentication in Spring Security. It acts as a central coordinator, delegating the verification process to specific providers while maintaining a clean separation of concerns. This approach offers flexibility and simplifies managing authentication logic within your secure Spring applications.

UserDetailsService is a core interface that acts as the bridge between your application and the source of user authentication information. It’s responsible for loading a user’s details (username, password, authorities) when presented with a username during the authentication process

Spring Security Context, in the context of Spring Security, is a fundamental component that holds information about the currently authenticated user. It acts like a temporary storage unit for security details specific to the current thread or request.

Authentication
Spring Security provides comprehensive support for authentication. Authentication refers to the process of verifying someone’s claimed identity. Spring Security offers robust support for various authentication mechanisms, including form-based authentication, HTTP basic authentication, OAuth, OpenID, and more.

It integrates seamlessly with user databases, LDAP servers, and third-party authentication providers.

Authorization
Spring Security provides comprehensive support for authorization. Authorization is determining who is allowed to access a particular resource. With Spring Security, you can define fine-grained access control rules to restrict or permit access to different parts of your application based on roles, privileges, or other criteria.

It supports role-based access control (RBAC), expression-based access control, and method-level security.

Session Management
Spring Security provides features for managing user sessions securely, including session fixation protection, session concurrency control, and session timeout handling. It ensures that sessions are managed securely to prevent session-related attacks.

Security Threats Protection
Spring Security includes built-in protection against common security vulnerabilities, such as cross-site request forgery (CSRF), cross-site scripting (XSS), clickjacking, and session fixation attacks. It helps developers build applications that are resilient to security threats.

Spring Framework Integration
Spring Security seamlessly integrates with other components of the Spring ecosystem, such as Spring MVC, Spring Boot, and Spring Data. This integration simplifies the implementation of security features and enables developers to leverage the power of both Spring Security and other Spring modules.

Customization
Spring Security is highly customizable and extensible, allowing developers to tailor security configurations to meet the specific requirements of their applications. It provides extension points for integrating custom authentication providers, access decision voters, and security filters.

Overall, Spring Security is a comprehensive and flexible security framework that empowers developers to build secure, resilient, and compliant Java applications with ease. Whether you’re developing a web application, a RESTful API, or a microservices architecture, Spring Security provides the necessary tools and capabilities to ensure the security of your application and protect your users’ data.

Spring Boot Oauth 2.0 Google Login

In this section, we’ll create a minimal application that uses Google for authentication. Spring Boot’s auto configuration capabilities significantly simplify this step.

Setup the Project
Visit start.spring.io to create a new Spring Boot project.
Select Maven as your build tool and Java as your language.
Name your project, like Google Login.
Choose JDK 21 (or the latest available).
Add dependencies: web and oauth2-client. Spring Security will be added as a transitive dependency.
Generate and download the project. This will provide a zip file.
To make the application secure, you can simply add Spring Security as a dependency. Since you’re wanting to do a “social” login (delegate to Google), you include the Spring Security OAuth 2.0 Client starter.

Create google oauth credentials
Firstly, follow this Google Help to create Google OAuth Client ID in order to get the access keys of Google single sign on API (Client ID and Client Secret).

Provide a descriptive name and a brief explanation of what your app does.

Enter the URL of your application’s main page (e.g., http://localhost:8080 in this example).

Redirect URL is where users will be redirected after logging in with Google. Enter the specific path for your application’s login callback, for example, http://localhost:8080/login/oauth2/code/google.

This URL is a handshake between your app and Google. After users log in with Google credentials, they’ll be sent back to this specific URL within your application to confirm their login and grant access.

Then, to make the link to Google, add the following to your application.yml:

spring:
security:
oauth2:
client:
registration:
google:
clientId: google-client-id
clientSecret: google-client-secret
scope:
- email
- profile

Simply use the OAuth 2.0 credentials you created in previous step, replacing google-client-id with the client id and google-client-secret with the client secret.

Save the changes you made to your app and restart your application.

Now, when you visit your app’s home page at http://localhost:8080, you should see a login screen for Google account.

Go through the Google login process, granting any permissions your app needs.

After successfully logging in, you’ll be automatically directed back to your app’s home page, and you should be logged in!

How Does it Work?

Following the OAuth 2.0 standard, your app functions as a client application.

It uses the “authorization code grant” flow to obtain an access token from Google Console, which acts as the authorization server.

Once you’ve logged in with Google account, your app receives a special access token.

This access token facilitates secure communication between your app and Google Console, acting also as a resource server.

The app can then use the token to request specific user information authorized during the login process. It can only access the specific details you approved during login, such as your email and profile.

Conclusion

Spring Security OAuth2.0 empowers developers to implement secure and user-friendly login experiences in their applications.

It leverages the OAuth2.0 standard, enabling users to sign in with existing credentials from various providers like Google, GitHub, or Facebook. This not only simplifies the login process but also eliminates the need to manage user passwords within your application, enhancing overall security.

OAuth2.0’s token-based approach facilitates secure access control between different microservices. Secure communication and authorization between microservices within a larger application.

An OAuth2-based microservices architecture can be structured with a single client application for user interaction.

This client communicates with multiple backend resource servers offering RESTful APIs. A separate authorization server, managed by a third party, handles user authentication and authorization for secure access to resources.

Furthermore, Spring Boot’s autoconfiguration features make setting up Spring Security OAuth2.0 a breeze. Developers can focus on core application functionalities, while the framework handles the complexities of OAuth2.0 communication.

In conclusion, Spring Security OAuth2.0 offers a compelling solution for integrating secure and efficient user login into your web applications.

It simplifies the process, strengthens security, and provides a flexible solution for a variety of authentication providers.

Previously published On My Blog where you can find more articles about Java and Spring Framework

For more in-depth discussions follow me on:

Top comments (1)

Collapse
 
sherrydays profile image
Sherry Day

Could you further explain the differences between the various OAuth 2.0 grant types? It might also be interesting to see a comparison of their practical use cases in different types of applications.