World Tech

The new OAuth2 Authorization Server

In this blog post we will explain the new authorization server, also called OAuth2 server, that replaces the old authorization server. You should keep in mind that this is a simplified explanation about OAuth2 server, it will not describe why OAuth2 is important, how it works, how to use it, etc. Instead it will be a high-level explanation that will help you to understand how OAuth2 server works.

This article covers the new OAuth2 Authorization Server, a major update to the OAuth2 Server. The new OAuth2 Server is called OAuth2Server1.0, and added support for the new OAuth2 Version 2.0. The OAuth2 Server is a very important piece of the OAuth2 puzzle. It is responsible for the OAuth2 Authorization Server Client, which is generally the client that implements Oauth2. The OAuth2 Server is responsible for the delegation of authorization and access to OAuth2 resources, such as OAuth2 web applications, OAuth2 APIs, OAuth2 Web API, and OAuth2 User.

In this tutorial I will show you how to use the new OAuth2 authentication server (v0.0.3), created by the Spring team.

Here are the new features introduced in the new version:

  1. Ensure unique use of authorization code
  2. Introduction of OAuth2 tokens
  3. Add a grant for tag updates
  4. Implement the token lock endpoint

OAuth2 is an authorization method for accessing secure resources over the HTTP protocol.

Access badgevs. Upgrade Token

Let’s take a quick look at what an access token is and what an update token is.

The access token is a string representing the authorization granted to the client. An access token is a specific amount and duration of access provided by the source owner and provided by the source server and the authorization server.

The renewal token is issued (together with the access token) by the authentication server to the client and is used to obtain a new access token when the current access token becomes invalid or expires. The renewal token is also used to obtain additional access tokens with the same or a more limited scope (access tokens may have a shorter validity period and fewer rights than those allowed by the source owner). The issuance of an update token is optional and left to the discretion of the authorization server.

  • It is the responsibility of the access card to access the data before it expires,
  • It is the responsibility of the renewal token to request a new access token when the existing access token has expired.

Let’s try it. I will create an OAuth2 authorization server with Spring Authorization Server (version 0.0.3) and a resource server to authorize with OAuth2 JWT, based on the example created by the Spring Security Team.

Creating a project for an authorization server

I will use Spring Initializer (https://start.spring.io/) to create a new project. When you add new dependencies with Spring Initializer, you can only add one Spring Web dependency.  I will add a list of required losses later.

After you create a project with Spring Initializer, import the project into Eclipse.

Dependencies in pom.xml file

Here is the list of dependencies in my pom.xml file. Note the dependency on the new OAuth2 authorization server. The new authorization server is still in the experimental phase, and the latest version at the time of writing this blog post is only 0.0.3.

org.springframework.boot
spring-boot-starter-web

org.springframework.security.experimental
spring-security-oauth2-authorization-server
0.0.3

org.springframework.boot
spring-boot-starter-test
test

Add authorization server configuration

The following ProjectConfig class is used to define the implementation of the in-memory or JDBC client data service. I used an in-memory implementation. It has the following key features:

  • clientId – The (mandatory) identifier of the OAuth2 client,
  • secrecy – (required for trusted clients) the client’s confidentiality, if any,
    scope – the scope to which the client is limited. If the range is undefined or empty (default), the client is not restricted to this range,
    authorizedGrantTypes – The types of assignments that the client is authorized to use. The default value is empty,
    authority is the authority assigned to the client (normal Spring Security authority),
    redirect URIs redirect the user agent to the client’s redirect endpoint. It must be an absolute URL.

To create an authorization server with Spring Authorization Server, I will create a config for Spring Security that also creates a WebSecurityConfigurerAdapter config. This is how Spring Security typically uses the default configuration to set up the various Spring Security endpoints needed. Authorization server with OAuth2 protocol.

Create the registeredClientRepository bean that comes with the Spring authorization server to use as the client information for system authorization. You can see that the Client Id is set to messaging client and Client Secret is set to secret, which means that the example will only work for one client and the data will be stored in system memory.

Create a KeySource bean to manage system keys. In this version there is only one implementation of StaticKeyGeneratingKeyManager (this will be replaced in the future by CryptoKey, which should be more secure).

Finally, the UserDetailsService, like Spring Security, is typically used by Spring Security to store user details and also keep them in memory.

import java.time.Duration ;

import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Import;import org.springframework.security.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.core.userdetails.User;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.crypto.keys.KeyManager;import org.springframework.security.crypto.keys.StaticKeyGeneratingKeyManager;import org.springframework.security.crypto.password.NoOpPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.security.oauth2.core.AuthorizationGrantType;import org.springframework.security.oauth2.core.ClientAuthenticationMethod;import org.springframework.security.oauth2.server.authorization.client.InMemoryRegisteredClientRepository;import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;import org.springframework.security.provisioning.InMemoryUserDetailsManager ;

@Configuration
@EnableWebSecurity
@Import(OAuth2AuthorizationServerConfiguration.class)
public class ProjectConfig extends WebSecurityConfigurerAdapter {.

@Bean
public UserDetailsService userDetailsService() {
var uds = new InMemoryUserDetailsManager() ;

var u1 = User.withUsername(test).password(12345).authorities(read).build() ;

uds.createUser(u1) ;

return uds;
}

@Bean
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}

@Bean
public RegisteredClientRepository registeredClientRepository() {
var rc = RegisteredClient.withId(client).clientId(client1).clientSecret(secret1)
.clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
.redirectUri(http://localhost:8080/authorized).tokenSettings(t -> {
t.enableRefreshTokens(true);
t.reuseRefreshTokens(true);
t.accessTokenTimeToLive(Duration.ofHours(5));
}).scope(read).build() ;

return new InMemoryRegisteredClientRepository(rc);
}

@Bean
public KeyManager keyManager() {
return new StaticKeyGeneratingKeyManager();
}
}

The basic configuration of our OAuth2 authorization server is now ready. We should be able to build and run it on the default 8080 port.

Start the authorization server

You should be able to run the new OAuth2 authorization server like any other Spring Boot application. You can run it from within the Eclipse development environment or with the Maven commands below.

Starting an authorization server with Maven commands

mvn clean package
mvn spring-boot:run

Running a server with the Eclipse IDE

Note that the authentication server operates on port 8080 by default. That’s because I didn’t configure another port for it in the application.properties file.

The log displays the filters used with endpoints for the OAuth2 protocol, as follows:

  • POST /oauth2/token – as a token endpoint,
  • POST /oauth2/authorize – as an authorization endpoint,
  • GET /oauth2/authorize – This is also the authorization endpoint,
  • POST /oauth2/revoke – as a token revocation endpoint,
  • GET /oauth2/jwks – This is the endpoint of the JWT key.

The authorization endpoint can use the HTTP POST or GET method.

Receipt of access and renewal tokens

To see how the server works and to have it give us a JWT access token and a refresh token, I’m going to use the Postman HTTP client.

I’m going to use the Permission Code type to get the access token, and I need to perform two basic steps.

  1. Authenticate yourself and get an OAuth2 code,
  2. Swap the OAuth code for an access token and an update token.

Obtaining an OAuth2 code

To authenticate the user and retrieve the OAuth2 code value, open the following URL in a browser window.

http://localhost:8080/oauth2/authorize?response_type=code&client_id=client1&scope=read

Where:

  • http://localhost:8080 – Domain and port number where the OAuth2 authentication server is running,
  • /oauth2/authorize – Authorization endpoint,
  • response_type=code – mandatory parameter to get the authorization code,
  • &client_id=client1 is the ID of the OAuth2 client that we configured on the authorization server when we registered the OAuth2 client. To verify this, take a look at the Java ProjectConfig class above.
  • &scope=read – Scope.

Once you open the above URL in your browser window, you should be redirected to the user authentication page. Enter the username and password configured in the userDetailsService() method of the Java ProjectConfig class above.

When the user authenticates, the authentication server generates an authorization code, adds it to the redirect URI, and redirects the browser to the redirect URI with the code request parameter added to the URL.

When the redirection occurs, check the URL in your browser’s address bar. The redirect URI looks like this.

http://localhost:8080/authorized?code=5LTawRGAB2ZbjO9x6zE-KkN6xEYSFHV3qn73HyDinxbRDwrwx0juVuT-XSXhrO9yXYMMtTUDi8K_2K3GbOjgs4zCUV44nfauhMQOYcxucDqTcUxVZPmST2bEzgNRdu9R

Where

  • code – URL query string parameter containing the value of the OAuth2 code to use in the next step. We’ll exchange this code for an access card.

OAuth2 code exchange for access token

To exchange the value of the above OAuth2 code for an access token, we need to use the Postman HTTP client to send an HTTP post request to the /oauth2/token endpoint. The details of the HTTP request are shown below.

Basic authorization device

The /oauth2/token endpoint request must contain the Basic Auth credentials.

In the Postman HTTP client, open the Authorization tab and configure basic OAuth as shown in the following figure.

  1. Set the authentication type to Basic Auth,
  2. Enter a user name and password. These values are the ClientID and Secret of the OAuth2 Client that we configured in the registeredClientRepository() method of the Java ProjectConfig class above.

Setting monitoring parameters

To exchange the OAuth2 token for an access token, we need to send an HTTP post request to the /oauth2/token endpoint.

  • http://localhost:8080/oauth2/token

There are two query parameters that need to be added to this query:

  • grant_type=Authorization_code
  • &code=5LTawRGAB2ZbjO9x6zE-KkN6xEYSFHV3qn73HyDinxbRDwrwx0juVuT-XSXhrO9yXYMMtTUDi8K_2K3GbOjgs4zCUV44nfauhMQOYcxucDqTcUxVPmST2bEzgNRdu9R

Below is a screenshot of my HTTP Postman client showing the details of the request. If the request was successful, you should receive a JSON response with an access token and an update token, as shown in the following figure.

Using theupdate marker

Access marks are short lived and expired. If the access token has expired, you can use Refresh Token to get a new value for the access token. To do this, you need to send an HTTP post request to the same /oauth2/token endpoint, specifying the following request parameters.

  • grant_type=refresh_token
  • &refresh_token=MdhBcUQh9b-nTBJAKTieW_7_rFGPHWPI0qiw9upY48sJklm_j-r8KhUc0LT0QuEkyBLUM5oRo376zudAjhzSwTulG0qsIKs0hpiRgHRiI4YhXCkFRheCNMb5zhjqmAp

Note that the option for requesting a new admission ticket is now different. When refresh tokens are used, the Grant Type request parameter must be set to refresh_token to get a new value for the access token.

Below is a screenshot of the Postman HTTP client showing the details of the new access token request.

I hope you found this guide useful.

To learn more about OAuth2 and how to use it in Spring Boot applications, watch the video course below.

OAuth2 in Spring Boot applications

Have fun learning!

Related Tags:

spring oauth2 authorization serveroauth2 examplespring authorization server vs keycloakoauth2 tutorialspring-authorization-server mavenspring-security-oauth2-authorization-server maven,People also search for,Privacy settings,How Search works,OAuth,OpenID,Lightweight Directory Access Pr…,Hypertext Transfer Protocol,JSON,Uniform Resource Identifier,See more,spring oauth2 authorization server,spring-security-oauth2-authorization-server maven,oauth2 example,spring authorization server vs keycloak,spring boot authorization server deprecated,oauth2 tutorial,spring boot oauth2 authorization code example,spring-authorization-server maven

You may also like...

Leave a Reply

Your email address will not be published.