servlet-oauth2-resource-server-bearer-tokens.md 9.0 KB
Newer Older
茶陵後's avatar
茶陵後 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
# OAuth 2.0 Bearer Tokens

## Bearer Token Resolution

By default, Resource Server looks for a bearer token in the `Authorization` header.
This, however, can be customized in a handful of ways.

### Reading the Bearer Token from a Custom Header

For example, you may have a need to read the bearer token from a custom header.
To achieve this, you can expose a `DefaultBearerTokenResolver` as a bean, or wire an instance into the DSL, as you can see in the following example:

Example 1. Custom Bearer Token Header

Java

```
@Bean
BearerTokenResolver bearerTokenResolver() {
    DefaultBearerTokenResolver bearerTokenResolver = new DefaultBearerTokenResolver();
    bearerTokenResolver.setBearerTokenHeaderName(HttpHeaders.PROXY_AUTHORIZATION);
    return bearerTokenResolver;
}
```

Kotlin

```
@Bean
fun bearerTokenResolver(): BearerTokenResolver {
    val bearerTokenResolver = DefaultBearerTokenResolver()
    bearerTokenResolver.setBearerTokenHeaderName(HttpHeaders.PROXY_AUTHORIZATION)
    return bearerTokenResolver
}
```

Xml

```
<http>
    <oauth2-resource-server bearer-token-resolver-ref="bearerTokenResolver"/>
</http>

<bean id="bearerTokenResolver"
        class="org.springframework.security.oauth2.server.resource.web.DefaultBearerTokenResolver">
    <property name="bearerTokenHeaderName" value="Proxy-Authorization"/>
</bean>
```

Or, in circumstances where a provider is using both a custom header and value, you can use `HeaderBearerTokenResolver` instead.

### Reading the Bearer Token from a Form Parameter

Or, you may wish to read the token from a form parameter, which you can do by configuring the `DefaultBearerTokenResolver`, as you can see below:

Example 2. Form Parameter Bearer Token

Java

```
DefaultBearerTokenResolver resolver = new DefaultBearerTokenResolver();
resolver.setAllowFormEncodedBodyParameter(true);
http
    .oauth2ResourceServer(oauth2 -> oauth2
        .bearerTokenResolver(resolver)
    );
```

Kotlin

```
val resolver = DefaultBearerTokenResolver()
resolver.setAllowFormEncodedBodyParameter(true)
http {
    oauth2ResourceServer {
        bearerTokenResolver = resolver
    }
}
```

Xml

```
<http>
    <oauth2-resource-server bearer-token-resolver-ref="bearerTokenResolver"/>
</http>

<bean id="bearerTokenResolver"
        class="org.springframework.security.oauth2.server.resource.web.HeaderBearerTokenResolver">
    <property name="allowFormEncodedBodyParameter" value="true"/>
</bean>
```

## Bearer Token Propagation

Now that you’re resource server has validated the token, it might be handy to pass it to downstream services.
This is quite simple with `[ServletBearerExchangeFilterFunction](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServletBearerExchangeFilterFunction.html)`, which you can see in the following example:

Java

```
@Bean
public WebClient rest() {
    return WebClient.builder()
            .filter(new ServletBearerExchangeFilterFunction())
            .build();
}
```

Kotlin

```
@Bean
fun rest(): WebClient {
    return WebClient.builder()
            .filter(ServletBearerExchangeFilterFunction())
            .build()
}
```

When the above `WebClient` is used to perform requests, Spring Security will look up the current `Authentication` and extract any `[AbstractOAuth2Token](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/oauth2/core/AbstractOAuth2Token.html)` credential.
Then, it will propagate that token in the `Authorization` header.

For example:

Java

```
this.rest.get()
        .uri("https://other-service.example.com/endpoint")
        .retrieve()
        .bodyToMono(String.class)
        .block()
```

Kotlin

```
this.rest.get()
        .uri("https://other-service.example.com/endpoint")
        .retrieve()
        .bodyToMono<String>()
        .block()
```

Will invoke the `[https://other-service.example.com/endpoint](https://other-service.example.com/endpoint)`, adding the bearer token `Authorization` header for you.

In places where you need to override this behavior, it’s a simple matter of supplying the header yourself, like so:

Java

```
this.rest.get()
        .uri("https://other-service.example.com/endpoint")
        .headers(headers -> headers.setBearerAuth(overridingToken))
        .retrieve()
        .bodyToMono(String.class)
        .block()
```

Kotlin

```
this.rest.get()
        .uri("https://other-service.example.com/endpoint")
        .headers{  headers -> headers.setBearerAuth(overridingToken)}
        .retrieve()
        .bodyToMono<String>()
        .block()
```

In this case, the filter will fall back and simply forward the request onto the rest of the web filter chain.

|   |Unlike the [OAuth 2.0 Client filter function](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunction.html), this filter function makes no attempt to renew the token, should it be expired.<br/>To obtain this level of support, please use the OAuth 2.0 Client filter.|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### `RestTemplate` support

There is no `RestTemplate` equivalent for `ServletBearerExchangeFilterFunction` at the moment, but you can propagate the request’s bearer token quite simply with your own interceptor:

Java

```
@Bean
RestTemplate rest() {
	RestTemplate rest = new RestTemplate();
	rest.getInterceptors().add((request, body, execution) -> {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication == null) {
			return execution.execute(request, body);
		}

		if (!(authentication.getCredentials() instanceof AbstractOAuth2Token)) {
			return execution.execute(request, body);
		}

		AbstractOAuth2Token token = (AbstractOAuth2Token) authentication.getCredentials();
	    request.getHeaders().setBearerAuth(token.getTokenValue());
	    return execution.execute(request, body);
	});
	return rest;
}
```

Kotlin

```
@Bean
fun rest(): RestTemplate {
    val rest = RestTemplate()
    rest.interceptors.add(ClientHttpRequestInterceptor { request, body, execution ->
        val authentication: Authentication? = SecurityContextHolder.getContext().authentication
        if (authentication != null) {
            execution.execute(request, body)
        }

        if (authentication!!.credentials !is AbstractOAuth2Token) {
            execution.execute(request, body)
        }

        val token: AbstractOAuth2Token = authentication.credentials as AbstractOAuth2Token
        request.headers.setBearerAuth(token.tokenValue)
        execution.execute(request, body)
    })
    return rest
}
```

|   |Unlike the [OAuth 2.0 Authorized Client Manager](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/oauth2/client/OAuth2AuthorizedClientManager.html), this filter interceptor makes no attempt to renew the token, should it be expired.<br/>To obtain this level of support, please create an interceptor using the [OAuth 2.0 Authorized Client Manager](../client/index.html#oauth2client).|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

## Bearer Token Failure

A bearer token may be invalid for a number of reasons. For example, the token may no longer be active.

In these circumstances, Resource Server throws an `InvalidBearerTokenException`.
Like other exceptions, this results in an OAuth 2.0 Bearer Token error response:

```
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer error_code="invalid_token", error_description="Unsupported algorithm of none", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1"
```

Additionally, it is published as an `AuthenticationFailureBadCredentialsEvent`, which you can [listen for in your application](../../authentication/events.html#servlet-events) like so:

Java

```
@Component
public class FailureEvents {
	@EventListener
    public void onFailure(AuthenticationFailureBadCredentialsEvent badCredentials) {
		if (badCredentials.getAuthentication() instanceof BearerTokenAuthenticationToken) {
		    // ... handle
        }
    }
}
```

Kotlin

```
@Component
class FailureEvents {
    @EventListener
    fun onFailure(badCredentials: AuthenticationFailureBadCredentialsEvent) {
        if (badCredentials.authentication is BearerTokenAuthenticationToken) {
            // ... handle
        }
    }
}
```

[Multitenancy](multitenancy.html)[SAML2](../../saml2/index.html)