Book Image

OAuth 2.0 Cookbook

By : Adolfo Eloy Nascimento
Book Image

OAuth 2.0 Cookbook

By: Adolfo Eloy Nascimento

Overview of this book

OAuth 2.0 is a standard protocol for authorization and focuses on client development simplicity while providing specific authorization flows for web applications, desktop applications, mobile phones, and so on. This book also provides useful recipes for solving real-life problems using Spring Security and creating Android applications. The book starts by presenting you how to interact with some public OAuth 2.0 protected APIs such as Facebook, LinkedIn and Google. You will also be able to implement your own OAuth 2.0 provider with Spring Security OAuth2. Next, the book will cover practical scenarios regarding some important OAuth 2.0 profiles such as Dynamic Client Registration, Token Introspection and how to revoke issued access tokens. You will then be introduced to the usage of JWT, OpenID Connect, and how to safely implement native mobile OAuth 2.0 Clients. By the end of this book, you will be able to ensure that both the server and client are protected against common vulnerabilities.
Table of Contents (16 chapters)
Title Page
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface
Index

Preparing the environment


As most examples are written in Java, we will also need an Integrated Development Environment (IDE) and a good framework to help us write simple web applications (as the OAuth 2.0 protocol was designed for HTTP usage), which will be Spring. To simplify the usage of Spring related technologies, this recipe will help you prepare an application using Spring Boot, providing an example endpoint and how to run this project using Maven.

Getting ready

As I previously mentioned, we will run most of the recipes using the Spring Boot Framework which eases the development of applications based on the Spring Framework. So to run this recipe, you just need an environment where you can download some files from the internet, Java 8 properly configured on your machine, and the CURL tool.

Note

CURL is a tool which allows you to run HTTP requests through the command line. It is available by default in Linux and Mac OS environments, so if you are running the recipes on Windows you should install it first. This tool can be downloaded fromhttps://curl.haxx.se/download.htmland to install it, you just have to unpack it and add the path for binaries to the PATH environment variable of Windows.

How to do it...

The following steps describe how to prepare the environment and show how to generate a simple project from the Spring Initializr website which will be executed using the appropriate Maven commands:

  1. Generate a project using Spring Initializr service by visiting https://start.spring.io/. Spring Initializr provides lots of options to start setting up your project, such as if you want to use Maven or Gradle to manage your project dependencies, which version of Spring Boot to use, which dependencies to use, and even changing the language from Java to Groovy or Kotlin.
  2. For this simple test, just use the default values for the project manager, Maven Project, with Java language and version 1.5.7 of the Spring Boot.
  3. AtProject Metadata, change the value of the fieldGrouptocom.packt.example.
  4. Still on Project Metadata, change the name of the Artifact to simplemvc.
  5. In the Dependencies section, type web and select Full-stack web development with Tomcat and Spring MVC. After selecting the right choice, you will see the tag Web underneath Selected Dependencies as follows:
  1. After setting up all the requirements for this simple example, click on the Generate Project button and your browser will start downloading the ZIP file into your Downloads folder.
  2. After downloading this file, you can unzip it and import it to your IDE just to explore the structure of the created project. For Eclipse users, just import the project as a Maven project.
  1. Open the class SimplemvcApplication and you would see the following code in your IDE:
@SpringBootApplication 
public class SimplemvcApplication { 
   public static void main(String[] args) { 
         SpringApplication.run(SimplemvcApplication.class, args); 
   } 
} 
  1. Let's turn the class SimplemvcApplication into a controller by adding the annotation @Controller as presented in the following code:
@Controller @SpringBootApplication 
public class SimplemvcApplication { 
   public static void main(String[] args) { 
         SpringApplication.run(SimplemvcApplication.class, args); 
   } 
} 
  1. Now that our class is declared as a controller, we can define an endpoint so we can see if the project is running properly. Add the method getMessage as follows, within the class SimplemvcApplication:
@GetMapping("/message") 
public ResponseEntity<String> getMessage() { 
   return ResponseEntity.ok("Hello!"); 
} 
  1. If you want to run your project inside the Eclipse IDE, you should just run the class SimplemvcApplication as a Java application by right-clicking at the class and selecting the menu option Run As |Java Application.
  2. After the application is started you should see something like the following message at the end of the output presented in your console:
Started SimplemvcApplication in 13.558 seconds (JVM running for 14.011)
  1. Execute the following command to know if your application works properly (just check if the output prints Hello):

 

curl "http://localhost:8080/message"
  1. If you would like to use the command line you can also start your application by running the following Maven command (to run the application with Maven through the command line, you must install Maven, as explained in the next sections):
mvn spring-boot:run
  1. If you don't have Maven installed on your machine, the first thing to do is to start downloading the latest version from https://maven.apache.org/download.cgi which at the time of this writing was apache-maven-3.5.0-bin.tar.gz.
  2. After the file has downloaded, just unpack it into any folder you want and start running Maven commands.
  3. Copy the full path of the Maven directory, which was created when you unpacked the downloaded file from the Maven website. If you are running macOS or Linux, run pwdat the command line to discover the full path.
  4. After that, you must add the path for Maven's directory to the PATHenvironment variable. If you are using Linux or macOS, create the variableMVN_HOMEwithin the.bash_profilefile and append the content ofMVN_HOMEto the end of thePATHenvironment variable, as presented in the following code:
MVN_HOME=/Users/{your_user_name}/maven-3.5.0 
export PATH=$PATH:$MVN_HOME/bin 

Note

The file.bash_profileshould be found at the user's directory. So, to edit this file, you should open the file/Users/{your_user_name}/.bash_profile, or in a shorter way, by using~/.bash_profile.If you are using Windows, all the environment variables can be edited through the visual interface.

  1. After editing this file, run the command source ~/.bash_profile to reload all the contents.
  2. To check if Maven is perfectly running on your environment, run the following command:
mvn --version.

See also

How it works...

Because of the usage of Spring Boot we can take advantage of projects like Spring MVC and Spring Security. These Spring projects help us to write web applications, REST APIs, and help us to secure our applications. By using the Spring Security OAuth2 project, for example, we can configure our own OAuth 2.0 Providers in addition, to act like clients. This is important because someone trying to write his own OAuth Provider will have to deal with too many details which could easily lead to an insecure OAuth Provider. Spring Security OAuth2 already addresses the main concerns any developer would have to think about.

In addition, Spring Boot eases the initial steps for the bootstrap of the application. When creating a Spring project without Spring Boot we need to deal with dependencies manually by taking care of possible library conflicts. To solve this problem, Spring Boot has some pre-configured modules provided by starters. As an example of a useful starter, let's consider an application with Spring Data JPA. Instead of declaring all the dependencies for hibernate, entity-manager, and transaction-api, just by declaring spring-boot-starter-data-jpa all the dependencies will be imported automatically.

While starting using Spring Boot, things can still become easier by using the Spring Initializr service provided by Pivotal (the Spring maintainer now).

There's more...

All the examples presented in Java can be imported and executed on any Java IDE, but we will use Eclipse just because it is a large, accepted tool among developers around the world. Although this book presents recipes using Eclipse, you can also stick with your preferred tool if you want.

Nowadays, many projects have been designed using Gradle, but many developers are still used to creating their projects using Maven to manage dependencies and the project itself. So, to avoid trick bugs with IDE plugins or any other kind of issue, the recipes using Spring Boot will be managed by Maven. In addition, Eclipse IDE already comes with a Maven plugin which at the time of writing this book was not true for Gradle. To run projects with Gradle in Eclipse, you must install a specific plugin.

See also

Spring Boot provides a lot of starters to help you develop applications using a plethora of tools and libraries. If you want to search for more just go to http://docs.spring.io/spring-boot/docs/1.5.7.RELEASE/reference/htmlsingle/#using-boot-starter.