Session 9.4: Spring Boot Security - Authorization with OAuth2 - [Extra - not part of the course]
1. Clone the following repository
$ git clone https://github.com/M-Gharib/ESI-W9.4.git
If you want to create a new Spring Boot project from scratch, you need to install the following dependencies for both the Product and Inventory services:
- Spring Web
- Spring Security
- Oauth2 Client
- Thymeleaf
OAuth2 key actors
There are four key actors in OAuth2 :
- Resource Owner: owns the resource in the resource server.
- Resource Server: stores the resource that an application wants to access.
- Client: the application that wants to access the resource.
- Authorization Server: manages the authentication process.
How OAuth2 function
- The Client sends an authorization request to the Authorization Server.
- The Authorization Server requests permission from the Owner.
- If the Owner consents, the Authorization Server provides a token to the Client.
- The Client can use the token to obtain the Resource from the Resource Server.
Create a GitHub OAuth2 App
You must have an account on GitHub.com
to complete this task. You can create a new OAuth App as follows:
2. GitHub (logged in) -> settings -> Developers Settings -> OAuth App -> new OAuth App
3. You need to insert the Application name
and choose the name you want, you also need to insert Homepage URL
and Authorization callback URL
, they are the same as the URI where your app is running (e.g., for our example http://localhost:8090). Then, press the register application button.
4. When you finalize your app, you will be able to see the client-id
and client-secret
, which you need when you configure your OAuth in Spring Boot. To do that, you need to add the client-id
and client-secret
to applicatio.property
of your app, as follows:
# applicatio.property spring.security.oauth2.client.registration.github.client-id= # add client-id here spring.security.oauth2.client.registration.github.client-secret= # add client-secret here
5. We have created a simple webpage (index.html
) that can be found under the resources/templates
directory. It will just printout "Oauth2 example" if the user is successfully authenticated.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Just Testing</title> </head> <body> <h1>Oauth2 example</h1> </body> </html>
6. Run your application, and try to visit http://localhost:8090, you will be redirected to the GitHub login page, where you will be prompted to enter your credentials. After logging in, you be redirected to the protected page/website.
Note If you are already logged in GitHub, you'll not be redirected to the GitHub login page. Therefore, log out from GitHub before visiting http://localhost:8090