For the latest stable version, please use Spring Security 6.4.1!spring-doc.cn

OAuth 2.0 Resource Server

Spring Security supports protecting endpoints using two forms of OAuth 2.0 Bearer Tokens:spring-doc.cn

This is handy in circumstances where an application has delegated its authority management to an authorization server (for example, Okta or Ping Identity). This authorization server can be consulted by resource servers to authorize requests.spring-doc.cn

This section provides details on how Spring Security provides support for OAuth 2.0 Bearer Tokens.spring-doc.cn

Working samples for both JWTs and Opaque Tokens are available in the Spring Security Samples repository.spring-doc.cn

Let’s take a look at how Bearer Token Authentication works within Spring Security. First, we see that, like Basic Authentication, the WWW-Authenticate header is sent back to an unauthenticated client.spring-doc.cn

bearerauthenticationentrypoint
Figure 1. Sending WWW-Authenticate Header

The figure above builds off our SecurityFilterChain diagram.spring-doc.cn

number 1 First, a user makes an unauthenticated request to the resource /private for which it is not authorized.spring-doc.cn

number 2 Spring Security’s FilterSecurityInterceptor indicates that the unauthenticated request is Denied by throwing an AccessDeniedException.spring-doc.cn

number 3 Since the user is not authenticated, ExceptionTranslationFilter initiates Start Authentication. The configured AuthenticationEntryPoint is an instance of BearerTokenAuthenticationEntryPoint which sends a WWW-Authenticate header. The RequestCache is typically a NullRequestCache that does not save the request since the client is capable of replaying the requests it originally requested.spring-doc.cn

When a client receives the WWW-Authenticate: Bearer header, it knows it should retry with a bearer token. Below is the flow for the bearer token being processed.spring-doc.cn

bearertokenauthenticationfilter
Figure 2. Authenticating Bearer Token

The figure builds off our SecurityFilterChain diagram.spring-doc.cn

number 1 When the user submits their bearer token, the BearerTokenAuthenticationFilter creates a BearerTokenAuthenticationToken which is a type of Authentication by extracting the token from the HttpServletRequest.spring-doc.cn

number 2 Next, the HttpServletRequest is passed to the AuthenticationManagerResolver, which selects the AuthenticationManager. The BearerTokenAuthenticationToken is passed into the AuthenticationManager to be authenticated. The details of what AuthenticationManager looks like depends on whether you’re configured for JWT or opaque token.spring-doc.cn

number 3 If authentication fails, then Failurespring-doc.cn

number 4 If authentication is successful, then Success.spring-doc.cn