1. Introduction
OAuth is an open standard that describes a process of authorization. It can be used to authorize user access to an API. For example, a REST API can restrict access only for registered users with a proper role.
An OAuth authorization server is responsible for authenticating the users and issuing access tokens containing the user data and proper access policies.
In this tutorial, we'll implement a simple OAuth server using the Spring Security OAuth Authorization Server experimental module.
In the process, we'll create a client-server application that will fetch a list of Baeldung articles from a REST API. Both the client services and server services will require an OAuth authentication.
2. Authorization Server Implementation
Let's start by looking at the OAuth authorization server configuration. It'll serve as an authentication source for both the article resource and client servers.
2.1. Dependencies
First, we'll need to add a few dependencies to our pom.xml file:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.4.3</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> <version>2.4.3</version> </dependency> <dependency> <groupId>org.springframework.security.experimental</groupId> <artifactId>spring-security-oauth2-authorization-server</artifactId> <version>0.1.0</version> </dependency>
2.2. Configuration
Now, let's configure the port that our auth server will run on by setting the server.port property in the application.yml file:
server:
port: 9000
After that, we can move to the Spring beans configuration. First, we'll need a @Configuration class and import the OAuthAuthorizationServerConfiguration. Inside the configuration class, we'll create a few OAuth-specific beans. The first one will be the repository of client services. In our example, we'll have a single client, created using the RegisteredClient builder class:
@Configuration
@Import(OAuth2AuthorizationServerConfiguration.class)
public class AuthorizationServerConfig {
@Bean
public RegisteredClientRepository registeredClientRepository() {
RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
.clientId("article-client")
.clientSecret("secret")
.clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
.redirectUri("http://localhost:8080/login/oauth2/code/articles-client-oidc")
.scope("articles.read")
.build();
return new InMemoryRegisteredClientRepository(registeredClient);
}
}
The properties we're configuring are:
- Client ID – Spring will use it to identify which client is trying to access the resource
- Client secret code – a secret known to the client and server that provides trust between the two
- Authentication method – in our case, we'll use basic authentication which is just a username and password
- Authorization grant type – we want to allow the client to generate both an authorization code and a refresh token
- Redirect URI – the client will use it in a redirect-based flow
- Scope – this parameter defines authorizations that the client may have. In our case, we'll have just one – articles.read
Each authorization server needs its signing key for tokens to keep a proper boundary between security domains. Let's generate a 2048-byte RSA key:
@Bean
public JWKSource<SecurityContext> jwkSource() {
RSAKey rsaKey = generateRsa();
JWKSet jwkSet = new JWKSet(rsaKey);
return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet);
}
private static RSAKey generateRsa() {
KeyPair keyPair = generateRsaKey();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
return new RSAKey.Builder(publicKey)
.privateKey(privateKey)
.keyID(UUID.randomUUID().toString())
.build();
}
private static KeyPair generateRsaKey() {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
return keyPairGenerator.generateKeyPair();
}
Except for the signing key, each authorization server needs to have a unique issuer URL as well. We'll set it up as a http://127.0.0.1 on port 9000 by creating the ProviderSettings bean:
@Bean
public ProviderSettings providerSettings() {
return new ProviderSettings().issuer("http://127.0.0.1:9000");
}
Finally, we'll enable the Spring web security module with an @EnableWebSecurity annotated configuration class:
@EnableWebSecurity
public class DefaultSecurityConfig {
@Bean
SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
http.authorizeRequests(authorizeRequests ->
authorizeRequests.anyRequest().authenticated()
)
.formLogin(withDefaults());
return http.build();
}
// ...
}
Here, we're calling authorizeRequests.anyRequest().authenticated() to require authentication for all requests, and we're providing a form-based authentication by invoking the formLogin(defaults()) method.
Additionally, we'll define a set of example users that we'll use for testing. For the sake of this example, let's create a repository with just a single admin user:
@Bean
UserDetailsService users() {
UserDetails user = User.withDefaultPasswordEncoder()
.username("admin")
.password("password")
.build();
return new InMemoryUserDetailsManager(user);
}
3. Resource Server
Now, we'll create a resource server that will return a list of articles from a GET endpoint. The endpoints should allow only requests that are authenticated against our OAuth server.
3.1. Dependencies
First, let's include the required dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
<version>2.4.3</version>
</dependency>
3.2. Configuration
Before we start with the implementation code, we should configure some properties in the application.yml file. The first one is the server port:
server:
port: 8090
Next, it's time for the security configuration. We need to set up the proper URL for our authentication server with the host and the port we've configured in the ProviderSettings bean earlier:
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: http://127.0.0.1:9000
Now, we can set up our web security configuration. Again, we want to explicitly say that every request to article resources should be authorized and have a proper article.read authority:
@EnableWebSecurity
public class ResourceServerConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.mvcMatcher("/articles/**")
.authorizeRequests()
.mvcMatchers("/articles/**").access("hasAuthority('SCOPE_article.read')")
.and()
.oauth2ResourceServer()
.jwt();
return http.build();
}
}
As shown here, we're also invoking the oauth2ResourceServer() method, which will configure the OAuth server connection based on the application.yml configuration.
3.3. Articles Controller
Finally, we'll create a REST controller that will return a list of articles under the GET /articles endpoint:
@RestController
public class ArticlesController {
@GetMapping("/articles")
public String[] getArticles() {
return new String[] { "Article 1", "Article 2", "Article 3" };
}
}
4. API Client
For the last part, we'll create a REST API client that will fetch the list of articles from the resource server.
4.1. Dependencies
To start, let's include the needed dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webflux</artifactId>
<version>5.3.4</version>
</dependency>
<dependency>
<groupId>io.projectreactor.netty</groupId>
<artifactId>reactor-netty</artifactId>
<version>1.0.4</version>
</dependency>
4.2. Configuration
As we did earlier, we'll define some configuration properties for authentication purposes:
server:
port: 8080
spring:
security:
oauth2:
client:
registration:
articles-client-oidc:
provider: spring
client-id: articles-client
client-secret: secret
authorization-grant-type: authorization_code
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
scope: openid
client-name: articles-client-oidc
articles-client-authorization-code:
provider: spring
client-id: articles-client
client-secret: secret
authorization-grant-type: authorization_code
redirect-uri: "{baseUrl}/authorized"
scope: articles.read
client-name: articles-client-authorization-code
provider:
spring:
issuer-uri: http://127.0.0.1:9000
Now, let's create a WebClient instance to perform HTTP requests to our resource server. We'll use the standard implementation with just one addition of the OAuth authorization filter:
@Bean
WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) {
ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client =
new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
return WebClient.builder()
.apply(oauth2Client.oauth2Configuration())
.build();
}
The WebClient requires an OAuth2AuthorizedClientManager as a dependency. Let's create a default implementation:
@Bean
OAuth2AuthorizedClientManager authorizedClientManager(
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {
OAuth2AuthorizedClientProvider authorizedClientProvider =
OAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode()
.refreshToken()
.build();
DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository);
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
return authorizedClientManager;
}
Lastly, we'll configure web security:
@EnableWebSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests(authorizeRequests ->
authorizeRequests.anyRequest().authenticated()
)
.oauth2Login(oauth2Login ->
oauth2Login.loginPage("/oauth2/authorization/articles-client-oidc"))
.oauth2Client(withDefaults());
return http.build();
}
}
Here, as well as in other servers, we'll need every request to be authenticated. Additionally, we need to configure the login page URL (defined in .yml config) and the OAuth client.
4.3. Articles Client Controller
Finally, we can create the data access controller. We'll use the previously configured WebClient to send an HTTP request to our resource server:
@RestController
public class ArticlesController {
private WebClient webClient;
@GetMapping(value = "/articles")
public String[] getArticles(
@RegisteredOAuth2AuthorizedClient("articles-client-authorization-code") OAuth2AuthorizedClient authorizedClient
) {
return this.webClient
.get()
.uri("http://localhost:8090/articles")
.attributes(oauth2AuthorizedClient(authorizedClient))
.retrieve()
.bodyToMono(String[].class)
.block();
}
}
In the above example, we're taking the OAuth authorization token from the request in a form of OAuth2AuthorizedClient class. It's automatically bound by Spring using the @RegisterdOAuth2AuthorizedClient annotation with proper identification. In our case, it's pulled from the article-client-authorizaiton-code that we configured previously in the .yml file.
This authorization token is further passed to the HTTP request.
4.4. Accessing the Articles List
Now, when we go into the browser and try to access the http://localhost:8080/articles page, we'll be automatically redirected to the OAuth server login page under http://127.0.0.1:900/login URL:
After providing the proper username and password, the authorization server will redirect us back to the requested URL – the list of articles.
Further requests to the articles endpoint won't require logging in, as the access token will be stored in a cookie.
5. Conclusion
In this article, we've learned how to set up, configure, and use the Spring Security OAuth Authorization Server.
As always, all the source code is available over on GitHub.draf
The post Spring Security OAuth Authorization Server first appeared on Baeldung.