Introduction
This blog is your shortcut to understand the essentials of OAuth 2.0, so you can confidently build secure Kotlin applications. We’ll cover the essentials in three sections: basic theory, SSO implementation, and enhancement of our basic Kotlin Application. Let’s dive in and create a secure app with ease.
Section 1 : OAuth Basics
Authentication Vs Authorization
Authentication is about verifying “who you are,” confirming your identity. Whereas Authorization is concerned with “what you’re allowed to do,” specifying the actions and resources you have permission to access or perform.
Friend’s House Access Analogy : When visiting your friend’s house, them recognizing you and allowing entry based on their familiarity is authentication. Later, permitting access to their television while denying access to their phone showcases a distinct level of authorization.
Friend’s House Access Analogy
Technical example : Website login : You provide a username and password to authenticate. After verifying your identity, the system checks your authorization and allows you to perform task based on that, like, admins can modify settings, whereas regular users can only view content.
OAuth : Open Authorization
OAuth is an open protocol to allow secure authorization between services. It allows applications to access resources on behalf of a user without exposing the user’s credentials to the application.Valet Key Analogy : Imagine you have a fancy car and you want to let the valet park your car, but you don’t want to give them your main car key, which could give them access to your entire car. Instead, you have a special “valet key” that only allows the valet to drive and park the car. This key doesn’t open the trunk or give access to the car’s interior compartments.
Valet Key Analogy
Technical example : Photo Printing Service : Imagine you’re using Photo Printing Service, which wants the access to some photos from your google drive. Just as you wouldn’t want to hand over your main car key to a valet, you don’t want to share your Google login credentials with the Photo Printing Service, which could grant them access to all your data. Instead, OAuth allows you to provide a limited-access “valet key” to the service. This valet key permits them to access and print specific photos from your Google Drive, but it doesn’t grant access to the rest of your Google account or files.
Terminologies
Some of the important terminologies of OAuth that are involved in this scenario :
- Resource : Photos on Google Drive : Something that needs to be accessed and is protected.
- Resource Owner : User : An entity capable of granting access to the resource.
- Resource Server : Google Drive : The server hosting the protected resource.
- Client : Photo printing service : An application making protected resource requests on behalf of the resource owner and with its authorization.
- Authorization Server : The server issuing access tokens to the client.
OAuth 2.0 Flow
OAuth 2.0 replaced OAuth 1.0 as the industry standard for online authorization around 2012. In OAuth 2.0, authorization flows, also known as grant types, define the specific ways that an application can obtain an access token. These flows dictate the interaction between the client , the user, the authorization server , and the resource server.
The choice of flow depends on factors like the application type, security requirements, and user experience considerations.
Three common OAuth 2.0 authorization grant flows are:
- Authorization code flow
- Implicit Flow
- Client Credential Flow
Authorization code flow :
This flow involves several steps, for our Photo Printing Service Scenario :
- User Request: User wants photo printing service to access photos on their Google Drive.
- Authorization Request: Service redirects user to Google’s OAuth for permission.
- User Approval: User confirms permissions on Google’s consent screen.
- Authorization Code: Google sends a code to service.
- Access Token Request: Service exchanges code for an access token.
- Access Token Issued: Google grants access token to service.
- Resource Access: Service uses token to access user’s Google Drive.
- Resource Validation: Google Drive validates the token.
- Resource Provided: Google Drive sends requested photos to service
Implicit Flow :
Implicit Flow involves similar steps as Authorization Code Flow, except that, steps 4( Authorization Code) and 5(Access Token Request) are omitted.
Access tokens are directly issued to the client after user consent, which increases exposure risk compared to the Authorization Code Flow where an authorization code is exchanged for tokens.
The Implicit Flow often uses shorter-lived access tokens, which can be more secure. It is commonly used with JavaScript-based applications, such as Single-Page Applications.
Implicit Flow Illustration
Client Credential Flow
This flow is suitable when the client is trusted and has permission to access certain resources. It’s common in server-to-server interactions, such as microservices within an application’s back-end, without user involvement.Then the flow would be :
- Access Request (ms1 to Auth Server): ms1 contacts the authentication server and provides a special key for identification.
- Access Token Issuance (Auth Server): The authentication server validates ms1 and issues an access token.
- Resource Request (ms1 to ms2): Using the access token, ms1 requests profile info from ms2.
- Authorized Data Access (ms2 to ms1): ms2 verifies the access token and provides the requested profile information.
Unauthorized Data Access (ms2 to ms1): If the access token is invalid or lacks the required permissions, then ms2 denies the request. For instance, if ms1 tries to access payroll info, ms2’s access control denies it due to insufficient token permissions.
Section 2 : SSO Implementation
Single Sign On Using OAuth 2.0
OAuth is a tool that was initially created to handle permissions for accessing data, but it’s become useful for confirming identities too, making it a valuable tool for Single Sign-On (SSO) scenarios.
In terms of setting things up, you’ve got two options:
- You can create your own way for people to log into your app.
- You can use OAuth to fetch user info from any identity provider like Google, which is often simpler.For instance, after doing the OAuth process with Google and getting a user’s email, you can link that Google-authenticated account to one on your own service.
Setting Up OAuth 2.0 Single Sign-On (SSO) in a Basic Kotlin Spring Boot Application
Step 1 : Create an OAuth2 application
- Select Identity Provider: Common options include GitHub, Google, Facebook, etc. We will move forward with Github.
- Create a New Application:
- Log in to the identity provider’s management console or dashboard.
- Look for an option to create a new application or OAuth 2 client
- For Github : go to “Settings” > “Developer settings” > “OAuth Apps” > “New OAuth App”
OAuth Application creation on Github
Provide Application Details: Enter a name for your application and other necessary fields. If applicable, provide a description and logo.
Application Details
Obtain Client ID and Secret: After registering your OAuth application, you’ll receive a Client ID and Client Secret. Store these securely, as they will be used for authentication.
Get client id and secret
Step 2 : Setting Up API Authentication on the Application Side
- Add dependency in configuration file : When working on a Kotlin Spring Boot app, either add the OAuth dependency in the build.gradle.kts file or choose both the OAuth2 client and Web dependencies from Spring Initializer during the project setup.
implementation(“org.springframework.boot:spring-boot-starter-oauth2-client”)
- Configuration in application.properties : Enter the client id and secret that was obtained from github.
spring.security.oauth2.client.registration.github.client-id=CLIENT-ID
spring.security.oauth2.client.registration.github.client-secret=CLIENT-SECRET
Step 3 : Run the application
That was the simple application, with a root endpoint, so if we try to access the endpoint, the user will be prompted to authorize first.
Authorization screen
Access to the endpoint is granted only after the user completes the authentication process. And if you stay logged in to GitHub, you won’t have to re-authenticate with this local app.
Section 3 : Application Enhancement
Now, we will enhance the basic application that we have created, by adding an custom endpoint, that will show the authorized user’s info via HTML template.
Step 1 : Controller Class
Add the controller class that retrieves the authenticated user’s login ID and adds it to the model.
@Controller
class SecureController {
@GetMapping("/")
fun main(@AuthenticationPrincipal oauth2User: OAuth2User, model: Model): String {
val loginId = oauth2User.getAttribute<String>("login") ?: "unknown-login"
model.addAttribute("loginId", loginId)
return "home_page.html"
}
}
Step 2 : Add dependency
Add the following dependency that integrates Thymeleaf for rendering HTML views in our application.
implementation("org.springframework.boot:spring-boot-starter-thymeleaf")
Step 3 : Create View (HTML Template)
Create the home_page.html file within the resources/templates directory to exhibit user information following authentication.
<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<title>Welcome to Our App</title>
</head>
<body>
<div class="container">
<h1>Welcome to Our Application : OAuthDemoWithKotlin</h1>
<p>This is the home page of our application.</p>
<p>User Information:</p>
<p>Login ID: <span th:text="${loginId}"></span></p>
<p>If you are seeing this page, it means you have successfully authenticated using OAuth.</p>
<p>Feel free to explore the features and functionality of our app!</p>
</div>
</body>
</html>
Step 4 : Run the application
OAuthDemoWithKotlin
Conclusion
- We covered the fundamentals of OAuth, its terminologies, and various flows used for secure authentication and authorization.
- We then demonstrated our knowledge by building a simple application that showcased OAuth authentication.
- We started with a basic back-end app, evolved it to include a front-end view, and displayed user info on the view.
- This journey highlighted OAuth’s role in securing applications and enhancing user experiences.
- With this understanding, we’re better equipped to navigate secure application development using OAuth.
Get full code on Github
Nadra Ibrahim is the owner of this article, you can find this article on her linkedin click me to check. Connect with her on LinkedIn.