OAuth 2.0 Cookbook - Adolfo Eloy Nascimento - E-Book

OAuth 2.0 Cookbook E-Book

Adolfo Eloy Nascimento

0,0
41,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Efficiently integrate OAuth 2.0 to protect your mobile, desktop, Cloud applications and APIs using Spring Security technologies.

About This Book

  • Interact with public OAuth 2.0 protected APIs such as Facebook, LinkedIn and Google.
  • Use Spring Security and Spring Security OAuth2 to implement your own OAuth 2.0 provider
  • Learn how to implement OAuth 2.0 native mobile clients for Android applications

Who This Book Is For

This book targets software engineers and security experts who are looking to develop their skills in API security and OAuth 2.0. Prior programming knowledge and a basic understanding of developing web applications are necessary. As this book's recipes mostly use Spring Security and Spring Security OAuth2, some prior experience with Spring Framework will be helpful.

What You Will Learn

  • Use Redis and relational databases to store issued access tokens and refresh tokens
  • Access resources protected by the OAuth2 Provider using Spring Security
  • Implement a web application that dynamically registers itself to the Authorization Server
  • Improve the safety of your mobile client using dynamic client registration
  • Protect your Android client with Proof Key for Code Exchange
  • Protect the Authorization Server from invalid redirection

In Detail

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.

Style and approach

With the help of real-world examples, this book provides step by step recipes for troubleshooting and extending your API security. The book also helps you with accessing and securing data on mobile, desktop, and cloud apps with OAuth 2.0.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 418

Veröffentlichungsjahr: 2017

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



OAuth 2.0 Cookbook

 

 

 

 

 

 

 

 

 

 

 

Protect your web applications using Spring Security

 

 

 

 

 

 

 

 

 

 

 

Adolfo Eloy Nascimento

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

OAuth 2.0 Cookbook

 

 

Copyright © 2017 Packt Publishing

 

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

 

First published: October 2017

Production reference: 2271117

 

 

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

 

ISBN 978-1-78829-596-3

 

www.packtpub.com

Credits

Author

Adolfo Eloy Nascimento

Copy Editors

Juliana Nair

Stuti Srivastava

Reviewer

Rafael Monteiro e Pereira

Project Coordinator

Judie Jose

Commissioning Editor

Vijin Boricha

Proofreader

Safis Editing

Acquisition Editor

Rahul Nair

Indexer

Francy Puthiry

Content Development Editor

Nikita Pawar

Graphics

Kirk D'Penha

Technical Editor

Prachi Sawant

Production Coordinator

Nilesh Mohite

About the Author

 

Adolfo Eloy Nascimento is a software engineer at Elo7, he has a Bachelors degree in Computer Science, and has been working with software development since 1999. In around 2003, he started working with web development implementing applications using ASP, PHP4/5, JavaScript, and Java (sometimes he still does some maintenance for a Ruby on Rails application). He started using OAuth 2.0 two years ago, when designing applications using microservice architectures, as well as modeling and interacting with public APIs.

As a tech enthusiast, Adolfo also likes to read and learn about programming languages and new technologies. He also believes that besides creating new applications, it is also important to share the knowledge he has acquired, which is what he does by writing for his personal blog, writing articles for Java Magazine in Brazil, and also writing tech books.

I would like to thank Janine for all her support and understanding during the writing of this book. Without her support it wouldn't have been possible. In addition, I would like to thank my parents who gave me great support in education. I would also like to thank Rafael Monteiro for accepting the reviewing of this book and improving the quality of each chapter. Finally, I would like to thank the Packt team, especially Rahul and Nikita, for helping me during the whole process of writing this book.

About the Reviewer

Rafael Monteiro e Pereira is a graduate in Computer Science from Mackenzie University in São Paulo, Brazil. He has always liked developing mission-critical and high-performance software. He also likes software security, especially playing with Kali Linux and its amazing set of tools. There is always a new vulnerability out there waiting to be discovered; this is what he believes.

He worked for the startup Elo7 as a big data/search software engineer and for companies in the finance/banking sector, such as BM&F Bovespa, developing their trading platform, and for Itaú-Unibanco as a lead software engineer on their new big data platform.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

 

https://www.packtpub.com/mapt

 

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by Packt

Copy and paste, print, and bookmark content

On demand and accessible via a web browser

Customer Feedback

Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/178829596X.

If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

Table of Contents

Preface

What this book covers

What you need for this book

Who this book is for

Sections

Getting ready

How to do it…

How it works…

There's more…

See also

Conventions

Reader feedback

Customer support

Downloading the example code

Downloading the color images of this book

Errata

Piracy

Questions

OAuth 2.0 Foundations

Introduction

Preparing the environment

Getting ready

How to do it...

See also

How it works...

There's more...

See also

Reading the user's contacts from Facebook on the client side

Getting ready

How to do it...

How it works...

There's more...

See also

Reading the user's contacts from Facebook on the server side

Getting ready

How to do it...

How it works...

There's more...

See also

Accessing OAuth 2.0 LinkedIn protected resources

Getting ready

How to do it...

How it works...

There's more...

See also

Accessing OAuth 2.0 Google protected resources bound to the user's session

Getting ready

How to do it...

How it works...

There's more...

See also

Implementing Your Own OAuth 2.0 Provider

Introduction

Protecting resources using the Authorization Code grant type

Getting ready

How to do it...

How it works...

There's more...

Supporting the Implicit grant type

Getting ready

How to do it...

How it works...

There's more...

See also

Using the Resource Owner Password Credentials grant type as an approach for OAuth 2.0 migration

Getting ready

How to do it...

How it works...

There's more...

See also

Configuring the Client Credentials grant type

Getting ready

How to do it...

How it works...

There's more...

See also

Adding support for refresh tokens

Getting ready

How to do it...

How it works...

There's more...

See also

Using a relational database to store tokens and client details

Getting ready

How to do it...

How it works...

There's more...

See also

Using Redis as a token store

Getting ready

How to do it...

How it works...

See also

Implementing client registration

Getting ready

How to do it...

How it works...

See also

Breaking the OAuth 2.0 Provider in the middle

Getting ready

How to do it...

How it works...

See also

Using Gatling to load test the token validation process using shared databases

Getting ready

How to do it...

How it works...

See also

Using OAuth 2.0 Protected APIs

Introduction

Creating an OAuth 2.0 client using the Authorization Code grant type

Getting ready

How to do it...

How it works...

Creating an OAuth 2.0 client using the Implicit grant type

Getting ready

How to do it...

How it works...

There's more...

See also

Creating an OAuth 2.0 client using the Resource Owner Password Credentials grant type

Getting ready

How to do it...

How it works...

There's more...

See also

Creating an OAuth 2.0 client using the Client Credentials grant type

Getting ready

How to do it...

How it works...

See also

Managing refresh tokens on the client side

Getting ready

How to do it...

How it works...

See also

Accessing an OAuth 2.0 protected API with RestTemplate

Getting ready

How to do it...

How it works...

See also

OAuth 2.0 Profiles

Introduction

Revoking issued tokens

Getting ready

How to do it...

How it works...

Remote validation using token introspection

Getting ready

How to do it...

How it works...

There's more...

Improving performance using cache for remote validation

Getting ready

How to do it...

How it works...

See also

Using Gatling to load test remote token validation

Getting ready

How to do it...

There's more...

See also

Dynamic client registration

Getting ready

How to do it...

How it works...

There's more...

See also

Self Contained Tokens with JWT

Introduction

Generating access tokens as JWT

Getting ready

How to do it...

How it works...

See also

Validating JWT tokens at the Resource Server side

Getting ready

How to do it...

How it works...

There's more...

See also

Adding custom claims on JWT

Getting ready

How to do it...

How it works...

See also

Asymmetric signing of a JWT token

Getting ready

How to do it...

How it works...

See also

Validating asymmetric signed JWT token

Getting ready

How to do it...

How it works...

See also

Using JWE to cryptographically protect JWT tokens

Getting ready

How to do it...

How it works...

See also

Using JWE at the Resource Server side

Getting ready

How to do it...

How it works...

See also

Using proof-of-possession key semantics on OAuth 2.0 Provider

Getting ready

How to do it...

How it works...

There's more...

See also

Using proof-of-possession key on the client side

Getting ready

How to do it...

How it works...

See also

OpenID Connect for Authentication

Introduction

Authenticating Google's users through Google OpenID Connect

Getting ready

How to do it...

How it works...

See also

Obtaining user information from Identity Provider

Getting ready

How to do it...

How it works...

There's more...

See also

Using Facebook to authenticate users

Getting ready

How to do it...

How it works...

See also

Using Google OpenID Connect with Spring Security 5

Getting ready

How to do it...

How it works...

See also

Using Microsoft and Google OpenID providers together with Spring Security 5

Getting ready

How to do it...

How it works...

See also

Implementing Mobile Clients

Introduction

Preparing an Android development environment

Getting ready

How to do it...

How it works...

Creating an Android OAuth 2.0 client using an Authorization Code with the system browser

Getting ready

How to do it...

How it works...

There's more...

See also

Creating an Android OAuth 2.0 client using the Implicit grant type with the system browser

Getting ready

How to do it...

How it works...

See also

Creating an Android OAuth 2.0 client using the embedded browser

Getting ready

How to do it...

How it works...

See also

Using the Password grant type for client apps provided by the OAuth 2 server

Getting ready

How to do it...

How it works...

There's more...

See also

Protecting an Android client with PKCE

Getting ready

How to do it...

How it works...

See also

Using dynamic client registration with mobile applications

Getting ready

How to do it...

How it works...

See also

Avoiding Common Vulnerabilities

Introduction

Validating the Resource Server audience

Getting ready

How to do it...

How it works...

Protecting Resource Server with scope validation

Getting ready

How to do it...

How it works...

Binding scopes with user roles to protect user's resources

Getting ready

How to do it...

How it works...

See also

Protecting the client against Authorization Code injection

Getting ready

How to do it...

How it works...

Protecting the Authorization Server from invalid redirection

Getting ready

How to do it...

How it works...

Preface

OAuth 2.0 is a standard protocol for authorization and it focuses on client-developer simplicity, while providing specific authorization flows for web applications, desktop applications, mobile phones, and so on. Given the documentation available for OAuth specification, you may think that it is complex; however, this book promises to help you start using OAuth 2.0 through examples in simple recipes. It focuses on providing specific authorization flows for various applications through interesting recipes. It also provides useful recipes for solving real-life problems using Spring Security and creating Android applications.

What this book covers

Chapter 1, OAuth 2.0 Foundations, contains recipes that will cover the basics of OAuth 2.0 through simple recipes that allow the reader to interact with public OAuth 2.0-protected APIs such as Facebook, LinkedIn, and Google.

Chapter 2, Implement Your Own OAuth 2.0 Provider, describes the way you can implement your own OAuth 2.0 Provider, presenting recipes that help with Authorization Server and Resource Server configurations considering different OAuth 2.0 grant types. It also presents how to effectively work with refresh tokens, using different databases to store access tokens.

Chapter 3, Using OAuth 2.0 Protected APIs, presents recipes that helps to create OAuth 2.0 client applications that are able to interact with all grant types described in the OAuth 2.0 specification. It also presents how to manage refresh tokens on the client side.

Chapter 4, OAuth 2.0 Profiles, explains some OAuth 2.0 profiles and how to implement them using Spring Security OAuth2. These profiles are specified to help with specific scenarios that aren't covered by OAuth 2.0 specifications, such as token revocation and token introspection to allow remote validation. This recipe also provides some recommendations, such as how and when to use cache when using remote validation.

Chapter 5, Self Contained Tokens with JWT, focuses on the usage of JWT as OAuth 2.0 access tokens and how to implement the main extensions for JWT, such as JWS and JWE, providing signature and encryption to protect the content conveyed by a JWT access token. This chapter also presents a nice approach to increase the security of your application by using proof-of-possession semantics on OAuth 2.0.

Chapter 6, OpenID Connect for Authentication, explains the difference between authorization and authentication, and how OAuth 2.0 can help to build an authentication protocol. To illustrate the usage of OpenID Connect, all the recipes presented in this chapter are aimed at client applications instead of building an OpenID Connect Provider.

Chapter 7, Implementing Mobile Clients, covers how to implement OAuth 2.0 native mobile clients using Android as the platform chosen for the recipes. This chapter presents some guidelines specified by the recently published specification named OAuth 2.0 for native apps.

Chapter 8 , Avoiding Common Vulnerabilities, covers ways to better protect the main components considered within an OAuth 2.0 ecosystem.

What you need for this book

To run the recipes presented in this book, you will basically need JDK 8, Maven, MySQL, and Redis. JDK 8 can be downloaded at http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html . You can download and read the installation instructions for Maven at https://maven.apache.org/download.cgi. To install MySQL, download the community version for your Operational System (OS) at https://dev.mysql.com/downloads/. Some recipes rely on Redis, which can be downloaded here: https://redis.io/download. To interact with the applications that will be created during the recipes, you also need a tool to send HTTP requests to the APIs presented. The recommended tools are CURL, which can be downloaded at https://curl.haxx.se/download.html and PostMan which can be downloaded at https://www.getpostman.com/.

In addition, so that you can write the code presented throughout the recipes, you will also need a Java IDE and Android Studio for native mobile Client recipes.

Who this book is for

This book targets software engineers and security experts who are looking at developing their skills in API security and OAuth 2.0. It is also aimed to help developers who want to pragmatically add OAuth 2.0 support for Spring Boot applications as well as Android mobile applications. Prior programming knowledge and basic understanding of web development is necessary. As this book presents the most recipes using Spring Security OAuth2, it would help to have prior experience with Spring Framework.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it…, How it works…, There's more…, and See also). To give clear instructions on how to complete a recipe, we use these sections as follows:

Getting ready

This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors .

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you. You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.

Hover the mouse pointer on the

SUPPORT

tab at the top.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box.

Select the book for which you're looking to download the code files.

Choose from the drop-down menu where you purchased this book from.

Click on

Code Download

.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account. Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for Windows

Zipeg / iZip / UnRarX for Mac

7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/OAuth-2.0-Cookbook. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/OAuth2.0Cookbook_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata is verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title. To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at [email protected] with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

OAuth 2.0 Foundations

This chapter covers the following recipes:

Preparing the environment

Reading the user's contacts from Facebook on the client side

Reading the user's contacts from Facebook on the server side

Accessing OAuth 2.0 LinkedIn protected resources

Accessing OAuth 2.0 Google protected resources bound to the user's session

Introduction

The main purpose of this chapter is to help you integrate with popular web applications and social media, although at the same time allow you to get familiarized with the foundational principles of OAuth 2.0 specification.

Before diving into the recipes for several use cases, let's look at the big picture of the most scenarios which will be covered. This will give you the opportunity to review some important concepts about OAuth 2.0 specification so we can stay on the same page with the terminologies used throughout the book.

The preceding diagram shows the four main components of the OAuth 2.0 specification:

Resource Owner

Authorization Server

Resource Server

Client

Just to review the purpose of these components, remember that the Resource Owner is the user which delegates authority for third-party applications to use resources on its behalf. The third-party application mentioned is represented by the client which I depicted as Mobile client and Web Client. The user's resources are usually maintained and protected by the Resource Server which might be implemented together with the Authorization Server as a single component, for example. The composition of the Authorization Server and Resource Server are referred to as the OAuth 2.0 Provider to simplify the terminology given to the application which is protected by OAuth 2.0.

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.

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:

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.

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.

At

Project Metadata

, change the value of the field

Group

to

com.packt.example

.

Still on

Project Metadata

, change the name of the

Artifact

to

simplemvc

.

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:

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.

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.

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); } }

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); } }

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!"); }

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.

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)

Execute the following command to know if your application works properly (just check if the output prints

Hello

):

curl "http://localhost:8080/message"

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

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

.

After the file has downloaded, just unpack it into any folder you want and start running Maven commands.

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

pwd

at the command line to discover the full path.

After that, you must add the path for Maven's directory to the

PATH

environment variable. If you are using Linux or macOS, create the variable

MVN_HOME

within the

.bash_profile

file and append the content of

MVN_HOME

to the end of the

PATH

environment variable, as presented in the following code:

MVN_HOME=/Users/{your_user_name}/maven-3.5.0 export PATH=$PATH:$MVN_HOME/bin

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.

After editing this file, run the command

source ~/.bash_profile

to reload all the contents.

To check if Maven is perfectly running on your environment, run the following command:

mvn --version.

See also

The OAuth 2.0 specification is available as RFC 6749 at

https://tools.ietf.org/html/rfc6749

You can read more about Spring Boot at

https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/

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.

Reading the user's contacts from Facebook on the client side

This recipe will present you with how you can integrate with Facebook using the Implicit grant type which is the better choice for public clients and runs directly on the user's web browser.

Grant types as you may already know, defines different methods for an application to retrieve access tokens from an Authorization Server. A grant type may apply for a given scenario regarding the client type being developed. Just as a reminder, OAuth 2.0 specification defines two types of client types: public and confidential.

Getting ready

To run this recipe, you must create a web application using Spring Boot, which will help the development of the application. In addition, we also need to register our application on Facebook. That's one important step when using OAuth 2.0, because as an OAuth Provider, Facebook needs to know which clients are asking for access token and, of course, the Resource Owner (the user) would want to know who is to be granted access to her profile.

There's more...

As an exercise, you might try to use Facebook SDK, which should be simpler to use for abstracting what we did into the SDK's API. Besides, using the SDK or not, one important thing that should be added to our code is the usage of the state parameter to avoid Cross Site Request Forgery (CSRF) attacks.

A CSRF attack allows a malicious user to execute operations in the name of another user (a victim). Regarding web applications, a valid approach to avoid CSRF is to make the client send a variable to the server with some random string which might be checked after receiving it back from the server's response, so the first value and the second (received) must be the same.

Regarding security issues, one other valuable suggestion is to send the access_token to the server side so you don't have to request a new access token on every web page of your application (but take care with the expiration time).

All the recipes that follow in this chapter will be using Spring Social project. For more information about the project, you can read the official documents at https://projects.spring.io/spring-social/.

See also

Preparing the environment

Reading the user's contacts from Facebook on the server side

Reading the user's contacts from Facebook on the server side

Now you are perfectly familiarized with the Facebook login process and Graph API usage. But to allow for a safer approach to get user authorization to retrieve contacts (or friends) from Facebook, this chapter presents how to use the server side approach which maps directly to the Authorization Code grant type from the OAuth 2.0 specifications.

Getting ready

For this recipe, we need to create a simple web application in the same way we did for client-implicit. As we will develop an application which interacts with Facebook at the server side, we are supposed to write a lot of code. But instead of writing too much code, let's use the Spring Social Facebook project.

There is an important step to perform, similar to what we did for client-implicit; as the application is a Facebook client we need to register a new application.

How to do it...

Follow the steps below to create a client application to integrate with Facebook using the server-side flow from OAuth 2.0:

Go to

https://developers.facebook.com/apps/

and add a new application by clicking on

Add a New App

.

Register a new client application on Facebook with the

Display Name

social-authcode

.

You will be guided to select one Facebook product. So, choose

Facebook Login

by clicking on

Set Up

and then choose

Web

as a platform.

You will be asked to enter the site URL, which might be

http://socialauthcode.test/

.

After creating the application on Facebook, click on

Facebook Login

on the left panel to configure a valid redirect URI, which should be

http://localhost:8080/connect/facebook

.

Click on

Dashboard

on the left panel so you can retrieve the App ID and App Secret which map to

client_id

and

client_secret

, as you may already know, and grab the credentials to use later when implementing the client application.

Now let's create the initial project using Spring Initializr, as we did for other recipes in this book. Go to

https://start.spring.io/

and define the following data:

Set up the

Group

as

com.packt.example

Define the

Artifact

as

social-authcode

Add

Web

and

Thymeleaf

as the dependencies for this project