This guide shows how to configure Spring Authorization Server to support a Single Page Application (SPA) with Proof Key for Code Exchange (PKCE). The purpose of this guide is to demonstrate how to support a public client and require PKCE for client authentication.
Spring Authorization Server will not issue refresh tokens for a public client. We recommend the backend for frontend (BFF) pattern as an alternative to exposing a public client. See gh-297 for more information. |
Enable CORS
A SPA consists of static resources that can be deployed in a variety of ways. It can be deployed separately from the backend such as with a CDN or separate web server, or it can be deployed along side the backend using Spring Boot.
When a SPA is hosted under a different domain, Cross Origin Resource Sharing (CORS) can be used to allow the application to communicate with the backend.
For example, if you have an Angular dev server running locally on port 4200
, you can define a CorsConfigurationSource
@Bean
and configure Spring Security to allow pre-flight requests using the cors()
DSL as in the following example:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
@Order(1)
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http)
throws Exception {
return http.cors(Customizer.withDefaults()).build();
}
@Bean
@Order(2)
public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http)
throws Exception {
return http.cors(Customizer.withDefaults()).build();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.addAllowedHeader("*");
config.addAllowedMethod("*");
config.addAllowedOrigin("http://127.0.0.1:4200");
config.setAllowCredentials(true);
source.registerCorsConfiguration("/**", config);
return source;
}
}
Click on the "Expand folded text" icon in the code sample above to display the full example. |
Configure a Public Client
A SPA cannot securely store credentials and therefore must be treated as a public client. Public clients should be required to use Proof Key for Code Exchange (PKCE).
Continuing the earlier example, you can configure Spring Authorization Server to support a public client using the Client Authentication Method none
and require PKCE as in the following example:
spring:
security:
oauth2:
authorizationserver:
client:
public-client:
registration:
client-id: "public-client"
client-authentication-methods:
- "none"
authorization-grant-types:
- "authorization_code"
redirect-uris:
- "http://127.0.0.1:4200"
scopes:
- "openid"
- "profile"
require-authorization-consent: true
require-proof-key: true
@Bean
public RegisteredClientRepository registeredClientRepository() {
RegisteredClient publicClient = RegisteredClient.withId(UUID.randomUUID().toString())
.clientId("public-client")
.clientAuthenticationMethod(ClientAuthenticationMethod.NONE)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri("http://127.0.0.1:4200")
.scope(OidcScopes.OPENID)
.scope(OidcScopes.PROFILE)
.clientSettings(ClientSettings.builder()
.requireAuthorizationConsent(true)
.requireProofKey(true)
.build()
)
.build();
return new InMemoryRegisteredClientRepository(publicClient);
}
The requireProofKey setting is helpful in situations where you forget to include the code_challenge and code_challenge_method query parameters because you will receive an error indicating PKCE is required during the Authorization Request instead of a general client authentication error during the Token Request.
|
Authenticate with the Client
Once the server is configured to support a public client, a common question is: How do I authenticate the client and get an access token? The short answer is: The same way you would with any other client.
A SPA is a browser-based application and therefore uses the same redirection-based flow as any other client. This question is usually related to an expectation that authentication can be performed via a REST API, which is not the case with OAuth2. |
A more detailed answer requires an understanding of the flow(s) involved in OAuth2 and OpenID Connect, in this case the Authorization Code flow. The steps of the Authorization Code flow are as follows:
-
The client initiates an OAuth2 request via a redirect to the Authorization Endpoint. For a public client, this step includes generating the
code_verifier
and calculating thecode_challenge
, which is then sent as a query parameter. -
If the user is not authenticated, the authorization server will redirect to the login page. After authentication, the user is redirected back to the Authorization Endpoint again.
-
If the user has not consented to the requested scope(s) and consent is required, the consent page is displayed.
-
Once the user has consented, the authorization server generates an
authorization_code
and redirects back to the client via theredirect_uri
. -
The client obtains the
authorization_code
via a query parameter and performs a request to the Token Endpoint. For a public client, this step includes sending thecode_verifier
parameter instead of credentials for authentication.
As you can see, the flow is fairly involved and this overview only scratches the surface.
It is recommended that you use a robust client-side library supported by your single-page app framework to handle the Authorization Code flow. |