Spring boot oauth2 client example

Spring boot oauth2 client example DEFAULT

In this tutorial, you’ll migrate Spring Boot with OAuth 2.0 support from version 1.5.x to 2.1.x. Spring Boot 2.1.x promotes OpenID Connect to a first-class citizen in the stack, making implementation more accessible than ever. We’ll start with integrating Okta’s OAuth service using Spring Boot 1.5.19 and Spring Security 4.2.x and then replicate the same motion using Spring Boot 2.1.3 and Spring Security 5.1. To make the process even simpler, we’ll minimize the code and configuration even further with Okta’s Spring Boot Starter with Spring Boot 2.1.3. 

Three Minute Overview of OpenID Connect and OAuth 2.0

In the beginning, there were siloed web sites that didn’t talk to each other, and it was sad.

Sites like Yelp started wanting access to the contact information you had in your Google Contacts. So, Yelp naturally collected your Google username and password so that it could access your contacts. You gave Yelp your permission, so this was all good, Yes? No!

With your username and password, Yelp could access your email, your docs —everything you had in Google — not just your contacts. And, worse, Yelp had to store your password in a way that it could use it in plaintext, and there was no standard way to revoke your consent to Yelp to access your Google account.

We needed an authorization framework that would allow you to grant access to certain information without you giving up your password — cue OAuth.

You may also like: What the Heck Is OAuth?

Three revisions later, we’re at OAuth 2.0 (there was 1.0 and 1.0a before it), and all’s right with the world. Now, an application like Yelp (a ) can request an  from a service like Google (an ).

You (the ) log into Google with your credentials and give your  to Yelp to access your contacts (and only your contacts).  in hand, Yelp makes a request of the Google Contacts API (the ) and gets your contacts. Yelp never sees your password and never has access to anything more than you’ve consented to. And, you can withdraw your consent at any time.

In this new world of consent and authorization, only one thing was missing: identity. Cue OpenID Connect. OIDC is a thin layer on top of OAuth 2.0 that introduces a new type of token: the Identity Token. Encoded within these cryptographically signed tokens in JWT format, is information about the authenticated user. This opened the door to a new level of interoperability and Single SignOn.

OAuth (and by extension OIDC) use a number of defined  to manage the interactions between the , the  and the . In this post, you’ll focus on the . This flow is meant to be kicked off from your browser and goes like this:

  1. Yelp wants access to your contacts. It presents a button to link your Google Contacts.
  2. When you click the button, you’re redirected to Google where you log in with your username and password (if you’re not already logged in).
  3. Google shows you a screen telling you that Yelp would like read-only access to your contacts.
  4. Once you give your consent, Google redirects back to Yelp, via your browser, with a temporary code (called an authorization code).
  5. Using this code, Yelp contacts Google to trade it for an Access Token.
  6. Google validates the code and if all checks out, issues an Access Token with limited capabilities (read-only access to your contacts) to Yelp.
  7. Yelp then presents the Access Token to the Google Contacts API.
  8. Google Contacts API validates the token and, if the request matches the capabilities identified by the token, returns your contact list to Yelp.

OAuth 2.0 and Spring Boot

The Spring Framework is in its 17th year. The Spring Framework and the many projects it encompasses (like Spring Security) is vast.

It’s fair to say that the engine at the heart of Spring and its many projects is configuration. Spring Boot brought the concept of “convention over configuration” to the world of Spring so that you could get a production-ready application up and running very quickly. It does this through an opinionated auto-configuration system (which you can override if need be).

Spring Security formalizes the approach to authentication and authorization in the Spring Framework.

OAuth and OIDC are a natural fit for the Spring Security constructs and, in the latest version of Spring Boot (version 2.1.3 as of this writing) and Spring Security (version 5.1.4 as of this writing), these standards are now first-class citizens.

If you’ve been using Spring Boot 1.5.x for OAuth and OIDC, you’ll need to do a little migration work to come into the new world of Spring Boot 2.1.x, but it’s worth it.

In the example code that you walk through in the migration path, you integrate with Okta’s OAuth and OIDC services. However, you could follow this guide for any OAuth and OIDC compliant provider.

Configure OpenID Connect

Okta makes it a snap to configure OIDC and OAuth 2.0 for your applications. All you have to do is provide some basic information, and Okta does all the heavy lifting. It’s OaaS! (OAuth as a Service).

Get Okta set up with OIDC and OAuth 2.0 for the Spring Boot examples found in the code. You only need to do this configuration once for use in each of the three code examples.

First, head on over and create yourself a free developer Okta organization. Follow the instructions to activate your organization.

Create an OIDC Application in Okta

Click  from your Okta Admin UI menu.

Click  and click the  option.

Click . Enter a  for the app. Change the value for  to: . Add another Login Redirect Uri: . Leave all the other default values.

NOTE: You add two different login redirect uris to support the different versions of Spring Boot. In the 2.1.x version, you’d use: 

Click . Scroll down and capture the  and the  values.

That’s it! Four steps. Not too bad.

Play the Spring Boot OpenID Connect and OAuth 2.0 Game

The code example is broken up into three maven modules: , , and . These are wholly enclosed examples that do not have parent relationships between them. They do each have the right version  for that example. This makes the  files more verbose than necessary, but it makes it so that you can run each version of the  and each version of the  completely standalone. You could even use different JVM versions for each.

Each version of the example code has four primary files

  1. - identifies dependencies
  2. - required configuration for OIDC & OAuth
  3. - the Client Application
  4. - the Resource Server

In each case, I set a goal of minimizing dependencies, configuration, and annotations to get the job done. Also, application code, controller code, and configuration code are artificially included in single files. This was to keep the example clear and concise. In a real-world application, you would separate these concerns into their own classes.

When you launch the , it will be listening on http://localhost:8080. When you launch the , it will be listening on http://localhost:8081.

By default, Spring Security protects all paths (whether you’re using OIDC and OAuth, or not). When you first navigate to the  at http://localhost:8080/, you’re redirected to Okta to authenticate. You’re then redirected back and you’ll see your full name in your browser.

Next, if you navigate to http://localhost:8080/api, the  will make an API call to the  using the  that was set when you authenticated above. This is all done behind the scenes. In your browser, you’ll see a response indicating that you were able to access a protected resource. And, for good measure, you could try navigating directly to http://localhost:8081/api. You should see that request fail as there is no access token.

Take a look at the differences amongst each version of the code.

Delving the Spring Boot Resource Server Code

In each of the examples, the Resource Server code is nearly identical:

Looking at this code alone - without the context of dependencies and configuration - you might be inclined to think that it’s just a regular old REST controller. But, it hooks into the OAuth framework thanks to those dependencies and configuration.

The one big difference in the code is that for the Spring Boot 1.5.x version, you need to include the  annotation on the class. In the Spring Boot 2.1.x versions, you do not need that annotation.

The rest of the differences are in dependencies and configuration and will be covered below.

Using Spring Boot 1.5.x, Spring Security 4.2.x, and OAuth 2.0

This version of Spring Boot and Spring Security went a long way to make working with OAuth 2.0 civilized. You see below that there’s not too much to it. It gets even better in the new release!

Resource Server Dependencies and Configuration

Take a look at the  file for the Resource Server:

As you can see, Spring Security 4.2.x has OAuth2 support as a secondary dependency.

Take a look at the  configuration file:

All that’s required is a , a  and a .

Okta uses JWTs for access tokens. This means that you could validate the JWT locally be (a) obtaining the public key that matches the private key used to sign it and (b) parsing the values out of the payload of the JWT (like, when it expires).

However, with Spring Boot 1.5, that requires additional configuration and additional code. So, to keep everything as simple as possible, this version of the Resource Server uses an Introspect request instead. The impact of this choice, though, is that the Resource Server makes an API call to Okta every time it gets a request in order for Okta to validate the access token.

You’ll see in the other examples that JWT handling is built-in and easier to configure and manage. Also, it’s worth noting that previous versions of the Okta Spring Boot Starter included support for validating and parsing JWT access tokens, so if you must use Spring Boot 1.5.x, take a look at the matching version of the Okta Spring Boot Starter.

Client Application Dependencies, Configuration, and Code

The Client Application has the same three dependencies as the Resource Server: , , and 

Here’s the  file:

Here, you’re explicitly configuring each of the components required in the OAuth Authorization Code Flow. The  is where the Client Application will redirect to kick off the flow with the Authorization Server (Okta). Once Okta redirects with the temporary authorization code, the Client Application will use the  value to exchange the authorization code with the Authorization Server for an access token. The  and  are required for both of these interactions with the Authorization Server. The  is used to obtain information about the authenticated user and requires the access token.

The value for  is a custom property used by the Client Application to identify where to access the Resource Server. It’s complete configuration coordinates are: .

Take a look at the Client Application Code:

The  annotation is necessary to hook into the  library in this class.

The root mapping method -  - takes an  object as its parameter. The  displays the full name. The Authorization Code Flow will be kicked off automatically by Spring Security when you access this path.

In order to have the Client Application make an API call to the Resource Server, you make use of a . This is a mechanism to make RESTful API calls in general, and in this case, you use an  instance to be able to pass along the access token that was automatically (and internally) set as part of the Authorization Code Flow. Take a look at that in more detail.

The guts of the  method are nice and compact: 

You pass the  object into the call to the private  method and then from there, it’s just a standard  method call with the URL to your Resource Server’s API endpoint (http://localhost:8081/api).

The heavy lifting is done in the  method. You cast the  method call (which returns an ) to . This is the first “ding” in this code - the need to cast a method call result.

Once you have the  object, you can use its  method to get the raw access token (in the case of Okta, this will be a JWT). This allows us to complete the creation of the OAuth2RestTemplate, and the access token will now automatically be sent in an HTTP Authorize header when the request of the Resource Server is made.

Using Spring Boot 2.1.x, Spring Security 5.1.x, and OAuth 2.0

With this version of Spring Boot and Spring Security, OAuth 2.0 and OpenID Connect are brought into the fold as first-class citizens. This changes the dependencies, configuration, and code - all for the better.

Resource Server Dependencies and Configuration

Here’s the  file:

Once again you have three dependencies, but this time you get rid of the direct Spring Security oauth2 reference and instead use a formal Spring Boot Starter: . This gives us all of the sensible defaults and auto-configuration of other starters.

Next up is the  configuration file:

Well, this is a breath of terse fresh air! All your Resource Server needs is the  (JWT Key Set) endpoint. This endpoint returns a set of public keys that the Resource Server uses to validate the cryptographic signature of the access token.

This isn’t just a benefit from the perspective of a smaller configuration file. With the exact same code (minus the  annotation), you get the benefit of being able to validate the access token locally, alleviating the need for additional Introspect calls to the Authorization Server. Our Resource Server will snag the public key(s) once and then validate incoming access tokens locally - very efficient.

Client Application Dependencies, Configuration, and Code

Here’s the  file for the Client Application:

This time around, in addition to the  and  Spring Boot Starters, you have the  starter. This gives us all the sensible defaults and auto-configuration for the Client Application. This new approach also reduces the amount of code you have to bring into your project. You have a separate starter for your Resource Server and a separate starter for your Client Application.

The last dependency, , is what you’re going to use to make the API calls to the Resource Server instead of using . More on that below.

Next up, 

In this case, you just need a ,  and an . The OAuth integration will automatically retrieve the authorization and token endpoints of the Authorization Server using a well-known endpoint. You can try it yourself by browsing to:

You’ll get back a JSON document that has all the configuration information for your Okta Authorization Server, including the link to the JWT key set URI.

You also have a custom configuration for the resource server at the coordinates: .

Notice that  is embedded in this configuration. Like: . It’s not that Spring Security has any particular knowledge of Okta. Rather, it’s that you can now use  as a named provider in your code. Take a look at that next.

Here’s the Client Application:

You no longer need the  annotation. OAuth2 and OIDC are now first-class citizens in the Spring Boot and Spring Security ecosystems.

Take a look at the root mapping. That will kick of the Authorization Code Flow. This time, you can inject an  object which is populated with all the information from the ID Token that was obtained as part of this flow. You use  to return the full name of the authenticated user.

Through constructor dependency injection, you have access to a  object. The new guidance for Spring, in general, is to use  instead of  and the latest versions of Spring Boot and Spring Security follow this.  is in scope, thanks to the  dependency. The  method makes use of the application.yml` file (http://localhost:8081/api). This looks like an ordinary HTTP GET method request to an endpoint. However, the Access Token obtained during the Authorization Code Flow is sent along as part of this request, which is a requirement of the Resource Server.

To understand the mechanism behind this, you can examine the embedded  class which exposes the  as a .

Since  is ordinarily used in the context of reactive applications, you need a little glue to make it work in the context of the traditional Servlet approach, which is how this example is organized.

You create a  object for this purpose. And, since you could have any number of Client Applications configured, you set the default to the named configuration:  (shown previously in the  file).

You use ’s builder pattern methods to apply the  object that you setup and return the  object. It is this object that is injected into the Client Application and ensures that when you make the api call, the Access Token is included in the Authorization header.

Spring Boot 2.1.x and the Okta Spring Boot Starter

Our final iteration is to incorporate the Okta Spring Boot Starter. So far, both the generic Spring Boot 1.5.x and Spring Boot 2.1.x examples could have been configured for any OAuth 2.0 / OIDC provider. Okta has created its own Spring Boot Starter that is listed on https://start.spring.io and can easily be incorporated into your application.

As you’ve done for each of the previous examples, take a look at the dependencies, configuration, and code for this example.

Resource Server Dependencies and Configuration

Here’s the  file for the resource server:

You’re down to 2 dependencies while keeping the code for your Resource Server exactly the same.

Take a look at the :

You now have an easy to read relatively flat configuration. You just need the , ,  and, for added security an  value that matches the base URL of the Resource Server. In addition, validating the cryptographic signature of the JWT Access Token, it will ensure that the audience value encoded in the payload matches the configured  value from the  file.

Client Application Dependencies, Configuration, and Code

Here are the dependencies for the Client Application from the  file:

You have the same 2 dependencies as you did for the Resource Server as well as  so that the Client Application can use the  object to make API requests.

The  file is exactly the same as the Resource server. You’ve now achieved complete parity for the configuration of the Resource Server and the Client Application. You also have the benefit of being able to reuse the  value in the Client Application. Here’s where you’re bringing it into scope thanks to Spring Boot’s environment variable support:

The rest of the Client Application code is the same as the Spring Boot 2.1.x example (without the Okta starter support).

Here’s the code that uses the  object to make the API request of the Resource Server:

Sours: https://dzone.com/articles/implement-oauth-20-easily-with-spring-boot-and-spr

Spring Boot + OAuth 2 Client Credentials Grant - Hello World Example

Define the Spring Boot Main Application. package com.javainuse; import java.security.Principal; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @EnableResourceServer @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } //This method will be used to check if the user has a valid token to access the resource @RequestMapping("/validateUser") public Principal user(Principal user) { return user; } } Configure the Authorization Server. The @EnableAuthorizationServer annotation is used to configure the OAuth 2.0 Authorization Server mechanism and defines the behaviour of various endpoints when interacting with the authorization server. package com.javainuse.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; @Configuration @EnableAuthorizationServer public class AuthorizationServer extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory().withClient("javainuse-client").secret("javainuse-secret") .authorizedGrantTypes("client_credentials").scopes("resource-server-read", "resource-server-write"); } }

Resource Server

Next create the Resource Server which has the reource to be accessed by the client. Maven Project will be as follows-

Spring Boot OAuth2 Client Credentials Grant Maven

In the Maven we need the Spring oauth dependency. Maven will be as follows- <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javainuse</groupId> <artifactId>boot-oauth2-resource-server</artifactId> <version>0.0.1.SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.0.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Define the Spring Boot Main Application. Configure the Resource Serverusing @EnableResourceServer annotation. It means the service expects an access token in order to process the request. Access token should be obtained from Authorization Server by OAuth 2.0 Client before calling the Resource Server. package com.javainuse; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.web.bind.annotation.RestController; @EnableResourceServer @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } Define the Controller, to expose API which can be accessed only using valid token. package com.javainuse.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @RequestMapping("/test") public String test() { return "Hello World"; } } Next define the url of the authorization server to be called by the resource server for verifying the token in the application.yml as follows. security: oauth2: resource: userInfoUri: http://localhost:8080/validateUser server: port: 9090 Finally start the Authorization Server and the Resource Server.
  • First get the Access Token by making a POST request to localhost:8080/oauth/token
    • Specify the client_id and client_secret in the header using base64 encoding.
      Spring Boot OAuth2 Client Credentials Grant - Token
    • Next specify the grant type as Client Credentials in body and send the request.
      Spring Boot OAuth2 Client Credentials Grant - Token Example
      We get the token as response
  • Get the Resource using the access token received above and making a GET call to localhost:9090/test.
    The token is specified as Authorization Bearer.
    Spring Boot OAuth2 Client Credentials Grant Tutorial

Download Source Code

Download it -
Spring Boot + OAuth2 Authorization Server for Client Credentials Grant
Spring Boot + OAuth2 Resource Server for Client Credentials Grant

See Also

Spring Boot Hello World Application- Create simple controller and jsp view using MavenSpring Boot Tutorial-Spring Data JPASpring Boot + Simple Security ConfigurationPagination using Spring Boot Simple ExampleSpring Boot + ActiveMQ Hello world ExampleSpring Boot + Swagger Example Hello World ExampleSpring Boot + Swagger- Understanding the various Swagger AnnotationsSpring Boot Main MenuSpring Boot Interview Questions
Sours: https://www.javainuse.com
  1. Dachshund mix puppies for adoption
  2. San francisco restaurant reopening guidelines
  3. Fallout 4 child companion mod

spring-security-oauth2-client-example

Modules

minimal-sample

This module contains the minimal configuration required for a Spring Boot project using Spring Security with OAuth2 client.

custom-userservice-sample

Same as minimal-sample, but it contains a custom OAuth2 UserService.

Note

For Google, it's actually possible to just use the two following properties:

spring.security.oauth2.client.registration.google.client-id= spring.security.oauth2.client.registration.google.client-secret=

But for the sake of the example, I'll be inserting all properties.

create credentials

  • Select Web Application
  • Add as Authorised JavaScript origins
  • Add as Authorised redirect URIs

oauth-client-id-parameters

  • Click on Create
  • Copy your client ID and your client secret as the value for and respectively in the file.
  • Done
Sours: https://github.com/TwinProduction/spring-security-oauth2-client-example
How to Add OAuth 2 0 in Spring Boot (Github) Step by Step in 5 minutes

Spring Boot Client App Tutorial

The purpose of the sample project is to show you how to write an OAuth2 client application for FusionCreator, with a Java framework - Spring Boot.

You will implement both the standard OAuth2 Authorization Code grant flow and the private key authentication based on asymmetric cryptography.

Get it from GitHub

For your convenience, this sample client application is available on GitHub, in the following repository: https://github.com/FusionFabric/ffdc-sample-springboot.

Clone it and follow the instructions from ffdc-authorization-code/README.md.

The provided GitHub repository contains also a sample client application - ffdc-client-credentials - that demonstrates the implementation of the OAuth2 Client Credentials grant flow which is not covered in the current tutorial.

Bootstrap App

In this section, you will use a web service called Spring Initializr to prepare a Spring Boot project.

To bootstrap your application

  1. Go to https://start.spring.io/ to use Spring Initializr.
  2. Enter the Project Metadata, as follows:
    • Group: the group ID, such as
    • Artifact: the artifact ID, which is your application name, such as:
  3. Search for and add the following dependencies:
    • Thymleaf
    • Spring Web
    • Spring Boot DevTools

Bootstrap your client app with Spring Intializr

  1. Click Generate. A ZIP archive, with the name of your artifact, is ready for you to download.
  2. Unpack the downloaded archive, and open the project directory.
  3. Open pom.xml and add the following dependencies, apart from those already added by Spring Initializr:
  1. Open a terminal, or a command prompt and run the Maven install command as follows:

    • if you have Maven installed on your computer:

    The required dependencies are downloaded and added to your project.

  2. Import the project in your favorite IDE.

You are now ready to code your application.

API Data Model

You start by implementing a data model that you will use to store and manipulate the data retrieved from the registered APIs.

To implement the data model

  1. Create a package named model.
  2. In model, create a class named TradeCaptureStaticData with the following members:
  1. Create a second class, named TradeCaptureStaticDataList with the following members:

Your data model contains a data class - TradeCaptureStaticData - to store a trade reference source and a list of reference sources - TradeCaptureStaticDataList - implemented as an array.

API Client

In this section you will create a class to retrieve the data from FusionFabric.cloud registered APIs. This API client class stores the data in dedicated data structures, such as a list of reference sources applicable to legal entities.

To code the FusionFabric.cloud API client

  1. Create a package named api.
  2. In api, create a new class named FfdcApi.
  3. In FfdcApi, add the following property, to fetch the base URL form the configuration file:
  1. Add another member responsible for firing the HTTP connection:
  1. Add a method to retrieve some reference sources from the API’s endpoint, and store it to a dedicated list - :
  1. Accept the import of the following packages:

Notes

  • This method returns the list of reference sources that you will receive from the call.
  • The query parameters are hard-coded so this method will work for reference sources as legal entities.

Security Configuration

In this section you will implement the configuration for Spring Security. You will do that by writing a configuration class - - that extends to meet the custom requirements of FusionFabric.cloud APIs.

To create the security configuration class

  1. Create a package, named config.
  2. In config, create a class, named FfdcConfig.
  3. Add the following members, that are provided by the application configuration file - application.yml:
  1. Set the OAuth2 grant type:
  1. Implement the REST template for the default authorization code grant authentication - authentication with client secrets:
  1. Configure the token services:
  1. Configure the filter to acquire the access token from the FusionCreator Authorization server, based on the REST template defined in the previous step:
  1. Set the authentication entry point:
  1. Set the token store to the . The value is configured in application.yml and provided by the Discovery service:
  1. Implement the method, required by the parent class, to tailor the security implementation to your scenario:
  1. Accept all package imports suggested by your IDE:

Controller Class - App’s Endpoints

In this section you will create the classes responsible for mapping your client app endpoints to your app UI model.

You define two controller classes - a and an

To create the controller classes

  1. Create a package named endpoint.
  2. In endpoint, create a class named ProductController and add the following class definition:
  1. Implement the , home - , and endpoints:
  1. Import the required packages:
  1. In endpoint, create a class named ErrorController and add the following class definition:
  1. Import the required packages:

HTML Templates

Now that your model and controllers are ready, you need the view. It is based on HTML templates that you will implement in this section. The templating system is provided by Thymeleaf.

To enable the view templates

  1. In src.main/resources/templates, create the following subdirectories and empty text files:
  • templates/
    • layout/
      • footer.html
      • head.html
      • header.html
    • error.html
    • index.html
    • layout.html
    • logout.html
    • results.html
  1. Add the following content to error.html:
  1. Add the following content to index.html:
  1. Add the following content to layout.html:
  1. Add the following content to logout.html:
  1. Add the following content to results.html:
  1. Add the following content to layout/footer.html:
  1. Add the following content to layout/head.html:
  1. Add the following content to layout/header.html:
  1. In src/main/resources/static create a directory named css, with an empty CSS file - style.css:
  1. Add the following code to style.css:

App Configuration

You store the application configuration parameters in a YAML file.

To create the configuration file

  1. In /src/main/resources create an empty file, named application.yml.
  2. Add the following content:
  1. Replace and with the actual client ID and secret key of the application that you registered on FusionCreator.

The , , URLs are provided by the Discovery service.

Your application is configured to run on the port 8081.

Run your App

Your are now ready to run your client app.

To run your app

  1. If you have Maven installed on your machine, start your app with:

Otherwise, with:

  1. Point your browser to localhost:8081.

  2. Click Get Data. You are redirected to the authentication page of FusionFabric.cloud Authorization Server.

  3. Use one of the following pair of credentials, and then click Log In.

The authentication page of FusionFabric.cloud Authorization Server.

If successful, you are redirected to your the results page of your application, and list of the reference sources retrieved from the FusionFabric.cloud Static Data for Trade Capture API is displayed.

The results page of your Spring Boot sample application.

  1. (Optional) Click Remove Access Token to clear the access token from your browser’ session.

Private Key Authentication

Private key authentication is an enhanced authentication method, based on asymmetric cryptography, where you use a pair of private and public RSA keys to sign a JSON Web Token (JWT) - with the private key, that you sent over the network to request the access token. The JWT is decoded with the public key that you submit to the Authorization Server in advance.

To enable private key authentication in your client application

  1. Enable private key authentication in your application, as described in Private Key Authentication and store the private RSA key in a file named private.key.

  2. Convert private.key to pkcs8 format. You can do that with OpenSSL, or other tool of choice. With OpenSSL, the command is:

Store pkcs8_private.pem in src/main/resources.

  1. Update src/main/resources/application.yml and add the following parameter:

Replace with the ID - kid, of the JWK file that you uploaded to your application on FusionCreator.

  1. In api, create a class named JwtClientAuthenticationHandler to handle the JWT generation and authentication:
  1. In api, create a helper class, named PrivateKeyReader to read the private key that you use to sign the JWT:
Sours: https://developer.fusionfabric.cloud/docs/examples/sample-client-springboot.html

Oauth2 example boot spring client

The client credentials grant is used when two servers need to communicate with each other outside the context of a user. This is a very common scenario—and yet, it’s often overlooked by tutorials and documentation online. In contrast, the authorization code grant type is more common, for when an application needs to authenticate a user and retrieve an authorization token, typically a JWT, that represents the user’s identity within the application and defines the resources the user can access, and the actions the user can perform.

The OAuth 2.0 docs describe the client credentials grant in this way:

The Client Credentials grant type is used by clients to obtain an access token outside of the context of a user. This is typically used by clients to access resources about themselves rather than to access a user’s resources.

Table of Contents

In this tutorial, you will learn about how to allow services to securely interoperate even when there is not an authenticated user, using the client credentials grant.

Fortunately, this grant type is more straightforward than the other user-focused grant types. It is often used for processes such as CRON jobs, scheduled tasks, and other types of heavy background data processing.

You will create a simple resource server that will be secured using Okta as an OAuth 2.0 and OpenID Connect (OIDC) provider. After that, you will create a Spring Boot-based command-line client that uses Spring’s to make authenticated requests to the secure server. You will see how to authenticate the client with Okta using the client credentials grant and how to exchange the client credentials for a JSON Web Token (JWT), which will be used in the requests to the secure server.

is deprecated, and while still widely used, should probably not be used for new code. Instead, the WebFlux-based class, should be used. In the next part of the tutorial, you will implement the same OAuth 2.0 client credentials grant using Spring .

What Is the Client Credentials Grant Flow?

The goal of the OAuth 2.0 client credentials grant is to allow two automated services to interact securely. It does this primarily by replacing the old scheme, HTTP Basic, with a token-based authentication scheme that greatly reduces the number of requests that expose sensitive access credentials.

The primary problem with HTTP Basic is that it sends the username and password with every request. This means that each and every request between each and every service is a major potential security risk. Did the headers get leaked in a log file? Did somebody forget to force HTTPS? One mistake and credentials are compromised. Further, because usernames and passwords often don’t have expiration dates, and because many people will (sadly) reuse these credentials across services, such a leak can expose a hole the size of a barn in a system’s security barrier.

HTTP Basic Sequence

OAuth 2.0, in contrast, mitigates this risk by having the client (the service initiating the request) request an access token from an authorization server. This access token is then used in the request to the other service for authentication and authorization. The primary benefit here is that the service credentials are only exposed when a new token must be requested or refreshed.

Further, this request is performed in a far more controlled manner, since it happens between the client and the authorization server.With HTTP Basic, in essence, every server has to act as an authorization server, with the increased security risk this poses. (Ideally a single authorization server can be hardened far more effectively than an entire network of services.)

The same is true when the service that receives the request validates the token. It makes a request to the authorization server, sending only the token, not exposing the username and password of the client.

Client Credentials Sequence

Another major benefit is that the tokens should expire and can be scoped. Passwords only expire when they are changed. Tokens have an expiration built into them. Further, the scope of the token and the authenticated identity of the token holder can be used to restrict the actions that the token holder is allowed to perform.

Prerequisites:

  • Java 11: This project uses Java 11. OpenJDK 11 will work just as well. Instructions are found on the OpenJDK website. OpenJDK can also be installed using Homebrew. Alternatively, SDKMAN is another excellent option for installing and managing Java versions.
  • HTTPie: This is a powerful command-line HTTP request utility that you’ll use to test the WebFlux server. Install it according to the docs on their site.
  • Okta CLI: The Okta CLI is a simple way to use Okta as an OAuth 2.0 and OpenID Connect provider. You can sign up for a free Okta developer account, log in to an existing account, and create OIDC applications. You’ll use it in this tutorial to configure Okta as your OAuth 2.0 and OIDC provider.

Intro to Spring Security 5 Core Classes

Spring Security 5 changed how a lot of the OAuth flow is handled. The client credentials grant was no exception—the old method used Spring’s and . While you can still use , is gone and does not work with Spring Security 5. The preferred method in Spring Security 5 is to use the , which is part of the package.

I’m going to take a moment to introduce some of the main OAuth Spring Security classes. If you already feel comfortable with OAuth 2.0 and Spring Security 5, or just want to see the code, feel free to skip ahead to the next section.

In the examples below, you’ll see that to configure client credentials need to configure Spring by overriding some of these classes through Bean definitions. If you want to get a more detailed look at these classes, take a look at the Spring docs on the subject.

ClientRegistration: represents a client registered with OAuth 2.0 or OpenID Connect (OIDC). It holds all of the basic information about the client, such as client id, client secret, grant type, and the various URIs. Client registrations are typically loaded automatically from an file. Spring auto-configuration looks for properties with the schema and creates a instance within a As you will see, in the command line runner version of this, we have to re-create some of this logic manually because it is not being auto-configured for us outside of the scope of a web service environment.

ClientRegistrationRepository: this is a container class that holds .

OAuth2AuthorizedClient: Represents an authorized client. This is a composed class that contains a client registration but adds authentication information. Take a look at the code excerpt below. You’ll see that the adds three properties composed on top of the client registration: a principal name, an access token, and a refresh token.

OAuth2AuthorizedClientRepository: is a container class that holds and persists authorized clients between requests. The default implementation, , simply stores the clients in memory.

OAuth2AuthorizedClientManager: is the manager class that contains the logic to handle the authorization flow. Most importantly, it authorizes and re-authorizes OAuth 2.0 clients using an . It also delegates persistence of the authorized clients and calls success or failure handlers when client authorization succeeds or fails.

OAuth2AuthorizedClientProvider: represents an OAuth 2.0 provider and handles the actual request logic for different grant types and OAuth 2.0 providers. They can be auto-configured based on property values (). In the case of this tutorial, you will be using Okta as your provider, so you’ll see properties with the prefix that are auto-configuring an associated .

Now for the code!

Build a Secure OAuth 2.0 Resource Server with Spring Security

In this section, you’re going to make a simple resource server for the clients to call. To bootstrap the project, you’re going to use the Spring Initializr. It’s a great way to create a preconfigured Spring Boot project. Here you’re going to access it via the REST API, but it also has a pretty slick web interface.

Make a root project directory for the three different applications:

  • the resource server,
  • the client, and
  • the client.

Open a BASH shell and navigate to the base project directory. Run the command below to retrieve the pre-configured starter project for the server using the Spring Initializr REST API.

This defines four dependencies:

  • Spring Boot OAuth 2.0 resource server
  • Spring Boot web starter
  • Spring security
  • The Okta Spring Boot starter

The Okta Spring Boot starter is a project that simplifies OAuth 2.0 and OpenID Connect (OIDC) configuration with Spring Boot and Okta. Take a look at the Okta Spring Boot Starter on GitHub for more information.

From within the project, open the class file and replace it with the following contents.

This class does a few important things. In the inner class, it configures Spring Boot as an OAuth 2.0 resource server using JWTs and requires that all requests are authenticated. It also enables using the annotation by including the annotation.

The second inner class, , defines a REST endpoint at the context root and secures this endpoint using the annotation. The security requires that the authorized JWT has the custom scope “mod_custom.”

Notice that to specify a required scope using the annotation, you use a Spring Expression Language snippet (SpEL): . Spring automatically prepends “SCOPE_” in front of the required scope name, such that the actual required scope is “mod_custom” not “SCOPE_mod_custom.”

The application code is in place. However, you still need to configure the Spring Boot application to use Okta as the OAuth 2.0 and OIDC provider. You also need to create an OIDC application on Okta.

Create an OIDC Application

Before you begin, you’ll need a free Okta developer account. Install the Okta CLI and run to sign up for a new account. If you already have an account, run . Then, run . Select the default app name, or change it as you see fit.

Copy the values from the generated file into . It should look like the following (with your own values for the issuer, client ID, and client secret) when you’re finished.

Add a line to the file. This changes the server port to 8081.

Test Your Secure Server

You now have a fully functioning server application. You can run it with the following command.

Once that finishes starting, you can run a request using HTTPie.

However, the server requires a valid JSON Web Token (JWT).

Add a Custom Scope to Your Authorization Server

Because we are using the custom scope in the annotation, you need to add this custom scope to your Okta authorization server. Run and open the resulting URL in your browser. Sign in to the Okta Admin Console. You may need to click the Admin button to get to your dashboard.

Go to Security > API. Select the Default authorization server by clicking on default in the table.

Select the Scopes tab. Click Add Scope.

Give the scope the following Name: .

Give the scope whatever Display Name and Description you would like, or leave it blank. Click Create to continue.

Create a RestTemplate Command-Line Application

Next, you will create a command-line application that makes an authorized request to the secure server using . Use the Spring Initializr to download a bootstrapped application with the following command, run from the root directory for the project as a whole.

Open this project in your IDE and a new class to hold the OAuth configuration.

In the context of a servlet, much of what this file does would be accomplished automatically by Spring auto-configuration. However, since this is a command-line utility and no servlet is going to be created, you have to recreate some of the OAuth configuration. This is what the file above accomplishes.

The method loads the properties for the client and provider from the file and creates an Okta client registration using those properties.

The other methods create an that contains this client registration and creates an , both of which are injected into a . This is the high-level controller class that orchestrates the OAuth 2.0 client credentials grant request. A lot is going on in this, and we won’t unpack it all here. I will point out that is a class specifically designed to be used outside of the context of a HttpServletRequest.

From the Spring Docs:

The DefaultOAuth2AuthorizedClientManager is designed to be used within the context of a HttpServletRequest. When operating outside of a HttpServletRequest context, use AuthorizedClientServiceOAuth2AuthorizedClientManager instead.

Next, update the file.

This file is the standard Spring Boot application file that starts the framework. It uses an inner class that extends to configure Spring Boot for OAuth 2.0 client. The bulk of the code is in the method, which is what is defined by the interface and is what is executed once Spring Boot is fully loaded.

The method does two main things:

  1. It uses the client ID and client secret to retrieve a JWT
  2. It uses that JWT to make an authorized HTTP request using

and are the classes used to configure the request for authentication with Okta’s servers and to make the actual request.

Before you can test the code, add some properties to the file. You need to fill in three values below:

  1. the client ID for your OIDC application
  2. the client secret for your OIDC application
  3. your own Okta URI in the

All of these values can be taken from the file for the secure server project above.

The last property, , tells Spring Boot not to launch any kind of web service. Since this is a command-line app, there’s no reason to launch the default Tomcat container.

With that all in place, you can now try it out. Make sure your server is running () and then run the client in a separate shell.

If all went well, the client will show you some output that looks like the following (I’ve omitted most of the token, but you’ll see it as a bit block of characters in your console).

One thing I want to point out is that this client is going to request a new token on every request. This is less than ideal because the token request sequence is the most vulnerable from a security perspective. A way around this would be to persist the token between requests. You could persist the token yourself and handle the refresh logic within the method, or you could implement an that persists the token instead of using the default in-memory implementation.

Create a WebClient-Based Application

In this section, you’re going to implement a command-line client using the newer, currently recommended WebClient API. WebClient is part of Spring’s WebFlux package. This is Spring’s reactive, non-blocking API, which you can read more about in their documentation. If you’re reading this and you don’t already have some idea of what non-blocking, asynchronous, or reactive coding is about, please tell me what rock you’ve been hiding under because it’s probably nice and quiet and peaceful.

It’s important to realize when using WebFlux within the Java servlet framework that you are mixing two different threading paradigms. Spring does a good job of handling this gracefully, but there are places (as you’ll see below) where you need to be aware of WebClient’s non-blocking nature and deliberately block it to wait for a response.

In this client, you will use two different methods to run tasks. First, you will use the interface, just as you did above. This will demonstrate using in a blocking context. Second, you will use to make requests using the annotation. This annotation allows for a variety of scheduling options, including CRON-style scheduling. It also allows the use of in all its non-blocking glory.

Here is the command to download the starter for the WebClient-based client from the Spring Initializr. The only difference between this bootstrapped project, and the previous one, is the addition of a new dependency. The dependency is necessary to add support for the class.

Run this command from a Bash shell from the project root directory.

Open the project in your favorite IDE and create a new class to hold the OAuth configuration.

Like the corresponding file in the previous client, this file loads the Okta client registration and packages it in an in-memory client registration repository (). This repository is specifically a reactive repository suitable for use with the class. This is used to build a reactive authorized client manager, which is packaged in an OAuth 2.0 filter that handles the client credentials grant exchange. Here the is packaged as a bean with the filter in place, and every request that uses this bean will have this filter. In the previous example, the client credentials exchange was performed explicitly in the command line runner method.

Update the class to match the following.

This class uses two different methods to trigger requests, both of which use the bean defined in the previous class. The method uses the annotation to trigger a request every five seconds. This annotation allows to be used in a non-blocking manner.

The method, by contrast, uses in a blocking manner. Notice the method in the chain of commands, and notice that it is returning a String value that is logged instead of using the more reactive methodology to log results: .

That’s it for this client. You can tell by the relative simplicity of this implementation over the implementation that Spring is moving in this direction. , while still widely used, is now deprecated.

Before you run it, copy the values from the file from the previous project to this project.

You can start the WebClient-based client using the following command.

You should see output like this:

Learn More About Spring Boot and Spring Security

In this tutorial, you saw two different ways to implement the OAuth 2.0 client credentials flow. You created a simple server application. You created a client using RestTemplate, a deprecated but still widely used Spring technology. Finally, you created a client using the newer, asynchronous , built on Spring’s WebFlux package.

You can find the source code for this example in our okta-spring-boot-client-credentials-example repository.

If you liked this post, there’s a good chance you might like some of our other ones.

If you have any questions about this post, please add a comment below. For more awesome content, follow @oktadev on Twitter, like us on Facebook, or subscribe to our YouTube channel.

Sours: https://developer.okta.com/blog/2021/05/05/client-credentials-spring-security
Spring Boot Security OAuth 2

I closed my eyes with pleasure, in an attempt to enjoy this kiss. But she broke off. - Anya. - at the same time with this exclamation of her, I opened my eyes, saw her wide open eyes, directed in the direction where Anya's hand was, and felt.

You will also be interested:

There was no shower noise, only strong slaps were clearly audible, and no one would confuse these slaps with anything. The spanking was so rhythmic and loud that it interrupted the squelching of my wife's pussy. It darkened in my eyes, the buzz hit me in the head with such a stream that I sat down on.

The floor, I saw almost nothing, when I opened the door I tried to see at least something.



916 917 918 919 920