
[[jc]]
= Java Configuration

General support for https://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/html/beans.html#beans-java[Java Configuration] was added to Spring Framework in Spring 3.1.
Since Spring Security 3.2 there has been Spring Security Java Configuration support which enables users to easily configure Spring Security without the use of any XML.

If you are familiar with the <<ns-config>> then you should find quite a few similarities between it and the Security Java Configuration support.

NOTE: Spring Security provides https://github.com/spring-projects/spring-security/tree/master/samples/javaconfig[lots of sample applications] which demonstrate the use of Spring Security Java Configuration.

== Hello Web Security Java Configuration

The first step is to create our Spring Security Java Configuration.
The configuration creates a Servlet Filter known as the `springSecurityFilterChain` which is responsible for all the security (protecting the application URLs, validating submitted username and passwords, redirecting to the log in form, etc) within your application.
You can find the most basic example of a Spring Security Java Configuration below:

[[jc-hello-wsca]]
[source,java]
----
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.*;
import org.springframework.security.config.annotation.authentication.builders.*;
import org.springframework.security.config.annotation.web.configuration.*;

@EnableWebSecurity
public class WebSecurityConfig {

	@Bean
	public UserDetailsService userDetailsService() {
		InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
		manager.createUser(User.withDefaultPasswordEncoder().username("user").password("password").roles("USER").build());
		return manager;
	}
}
----

There really isn't much to this configuration, but it does a lot.
You can find a summary of the features below:

* Require authentication to every URL in your application
* Generate a login form for you
* Allow the user with the *Username* _user_ and the *Password* _password_ to authenticate with form based authentication
* Allow the user to logout
* https://en.wikipedia.org/wiki/Cross-site_request_forgery[CSRF attack] prevention
* https://en.wikipedia.org/wiki/Session_fixation[Session Fixation] protection
* Security Header integration
** https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security[HTTP Strict Transport Security] for secure requests
** https://msdn.microsoft.com/en-us/library/ie/gg622941(v=vs.85).aspx[X-Content-Type-Options] integration
** Cache Control (can be overridden later by your application to allow caching of your static resources)
** https://msdn.microsoft.com/en-us/library/dd565647(v=vs.85).aspx[X-XSS-Protection] integration
** X-Frame-Options integration to help prevent https://en.wikipedia.org/wiki/Clickjacking[Clickjacking]
* Integrate with the following Servlet API methods
** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getRemoteUser()[HttpServletRequest#getRemoteUser()]
** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getUserPrincipal()[HttpServletRequest.html#getUserPrincipal()]
** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#isUserInRole(java.lang.String)[HttpServletRequest.html#isUserInRole(java.lang.String)]
** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#login(java.lang.String,%20java.lang.String)[HttpServletRequest.html#login(java.lang.String, java.lang.String)]
** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#logout()[HttpServletRequest.html#logout()]

=== AbstractSecurityWebApplicationInitializer

The next step is to register the `springSecurityFilterChain` with the war.
This can be done in Java Configuration with https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-container-config[Spring's WebApplicationInitializer support] in a Servlet 3.0+ environment.
Not suprisingly, Spring Security provides a base class `AbstractSecurityWebApplicationInitializer` that will ensure the `springSecurityFilterChain` gets registered for you.
The way in which we use `AbstractSecurityWebApplicationInitializer` differs depending on if we are already using Spring or if Spring Security is the only Spring component in our application.

* <<abstractsecuritywebapplicationinitializer-without-existing-spring>> - Use these instructions if you are not using Spring already
* <<abstractsecuritywebapplicationinitializer-with-spring-mvc>> - Use these instructions if you are already using Spring

=== AbstractSecurityWebApplicationInitializer without Existing Spring

If you are not using Spring or Spring MVC, you will need to pass in the `WebSecurityConfig` into the superclass to ensure the configuration is picked up.
You can find an example below:

[source,java]
----
import org.springframework.security.web.context.*;

public class SecurityWebApplicationInitializer
	extends AbstractSecurityWebApplicationInitializer {

	public SecurityWebApplicationInitializer() {
		super(WebSecurityConfig.class);
	}
}
----

The `SecurityWebApplicationInitializer` will do the following things:

* Automatically register the springSecurityFilterChain Filter for every URL in your application
* Add a ContextLoaderListener that loads the <<jc-hello-wsca,WebSecurityConfig>>.

=== AbstractSecurityWebApplicationInitializer with Spring MVC

If we were using Spring elsewhere in our application we probably already had a `WebApplicationInitializer` that is loading our Spring Configuration.
If we use the previous configuration we would get an error.
Instead, we should register Spring Security with the existing `ApplicationContext`.
For example, if we were using Spring MVC our `SecurityWebApplicationInitializer` would look something like the following:

[source,java]
----
import org.springframework.security.web.context.*;

public class SecurityWebApplicationInitializer
	extends AbstractSecurityWebApplicationInitializer {

}
----

This would simply only register the springSecurityFilterChain Filter for every URL in your application.
After that we would ensure that `WebSecurityConfig` was loaded in our existing ApplicationInitializer.
For example, if we were using Spring MVC it would be added in the `getRootConfigClasses()`

[[message-web-application-inititializer-java]]
[source,java]
----
public class MvcWebApplicationInitializer extends
		AbstractAnnotationConfigDispatcherServletInitializer {

	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class[] { WebSecurityConfig.class };
	}

	// ... other overrides ...
}
----

[[jc-httpsecurity]]
== HttpSecurity

Thus far our <<jc-hello-wsca,WebSecurityConfig>> only contains information about how to authenticate our users.
How does Spring Security know that we want to require all users to be authenticated?
How does Spring Security know we want to support form based authentication?
Actually, there is an configuration class that is being invoked behind the scenes called `WebSecurityConfigurerAdapter`.
It has a method called `configure` with the following default implementation:

[source,java]
----
protected void configure(HttpSecurity http) throws Exception {
	http
		.authorizeRequests()
			.anyRequest().authenticated()
			.and()
		.formLogin()
			.and()
		.httpBasic();
}
----

The default configuration above:

* Ensures that any request to our application requires the user to be authenticated
* Allows users to authenticate with form based login
* Allows users to authenticate with HTTP Basic authentication

You will notice that this configuration is quite similar the XML Namespace configuration:

[source,xml]
----
<http>
	<intercept-url pattern="/**" access="authenticated"/>
	<form-login />
	<http-basic />
</http>
----

The Java Configuration equivalent of closing an XML tag is expressed using the `and()` method which allows us to continue configuring the parent.
If you read the code it also makes sense.
I want to configure authorized requests __and__ configure form login __and__ configure HTTP Basic authentication.

[[jc-form]]
== Java Configuration and Form Login
You might be wondering where the login form came from when you were prompted to log in, since we made no mention of any HTML files or JSPs.
Since Spring Security's default configuration does not explicitly set a URL for the login page, Spring Security generates one automatically, based on the features that are enabled and using standard values for the URL which processes the submitted login, the default target URL the user will be sent to after logging in and so on.

While the automatically generated log in page is convenient to get up and running quickly, most applications will want to provide their own login page.
When we want to change the default configuration, we can customize the `WebSecurityConfigurerAdapter` that we mentioned earlier by extending it like so:

[source,java]
----
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	// ...
}
----

And then override the `configure` method as seen below:

[source,java]
----
protected void configure(HttpSecurity http) throws Exception {
	http
		.authorizeRequests()
			.anyRequest().authenticated()
			.and()
		.formLogin()
			.loginPage("/login") // <1>
			.permitAll();        // <2>
}
----

<1> The updated configuration specifies the location of the log in page.
<2> We must grant all users (i.e. unauthenticated users) access to our log in page.
The `formLogin().permitAll()` method allows granting access to all users for all URLs associated with form based log in.

An example log in page implemented with JSPs for our current configuration can be seen below:

NOTE: The login page below represents our current configuration.
We could easily update our configuration if some of the defaults do not meet our needs.

[source,html]
----
<c:url value="/login" var="loginUrl"/>
<form action="${loginUrl}" method="post">       <1>
	<c:if test="${param.error != null}">        <2>
		<p>
			Invalid username and password.
		</p>
	</c:if>
	<c:if test="${param.logout != null}">       <3>
		<p>
			You have been logged out.
		</p>
	</c:if>
	<p>
		<label for="username">Username</label>
		<input type="text" id="username" name="username"/>	<4>
	</p>
	<p>
		<label for="password">Password</label>
		<input type="password" id="password" name="password"/>	<5>
	</p>
	<input type="hidden"                        <6>
		name="${_csrf.parameterName}"
		value="${_csrf.token}"/>
	<button type="submit" class="btn">Log in</button>
</form>
----

<1> A POST to the `/login` URL will attempt to authenticate the user
<2> If the query parameter `error` exists, authentication was attempted and failed
<3> If the query parameter `logout` exists, the user was successfully logged out
<4> The username must be present as the HTTP parameter named __username__
<5> The password must be present as the HTTP parameter named __password__
<6> We must <<csrf-include-csrf-token>> To learn more read the <<csrf>> section of the reference

[[jc-authorize-requests]]
== Authorize Requests
Our examples have only required users to be authenticated and have done so for every URL in our application.
We can specify custom requirements for our URLs by adding multiple children to our `http.authorizeRequests()` method.
For example:


[source,java]
----
protected void configure(HttpSecurity http) throws Exception {
	http
		.authorizeRequests()                                                                <1>
			.antMatchers("/resources/**", "/signup", "/about").permitAll()                  <2>
			.antMatchers("/admin/**").hasRole("ADMIN")                                      <3>
			.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")            <4>
			.anyRequest().authenticated()                                                   <5>
			.and()
		// ...
		.formLogin();
}
----

<1> There are multiple children to the `http.authorizeRequests()` method each matcher is considered in the order they were declared.
<2> We specified multiple URL patterns that any user can access.
Specifically, any user can access a request if the URL starts with "/resources/", equals "/signup", or equals "/about".
<3> Any URL that starts with "/admin/" will be restricted to users who have the role "ROLE_ADMIN".
You will notice that since we are invoking the `hasRole` method we do not need to specify the "ROLE_" prefix.
<4> Any URL that starts with "/db/" requires the user to have both "ROLE_ADMIN" and "ROLE_DBA".
You will notice that since we are using the `hasRole` expression we do not need to specify the "ROLE_" prefix.
<5> Any URL that has not already been matched on only requires that the user be authenticated

[[jc-logout]]
== Handling Logouts

When using the `{security-api-url}org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurerAdapter.html[WebSecurityConfigurerAdapter]`, logout capabilities are automatically applied.
The default is that accessing the URL `/logout` will log the user out by:

- Invalidating the HTTP Session
- Cleaning up any RememberMe authentication that was configured
- Clearing the `SecurityContextHolder`
- Redirect to `/login?logout`

Similar to configuring login capabilities, however, you also have various options to further customize your logout requirements:

[source,java]
----
protected void configure(HttpSecurity http) throws Exception {
	http
		.logout()                                                                <1>
			.logoutUrl("/my/logout")                                                 <2>
			.logoutSuccessUrl("/my/index")                                           <3>
			.logoutSuccessHandler(logoutSuccessHandler)                              <4>
			.invalidateHttpSession(true)                                             <5>
			.addLogoutHandler(logoutHandler)                                         <6>
			.deleteCookies(cookieNamesToClear)                                       <7>
			.and()
		...
}
----

<1> Provides logout support.
This is automatically applied when using `WebSecurityConfigurerAdapter`.
<2> The URL that triggers log out to occur (default is `/logout`).
If CSRF protection is enabled (default), then the request must also be a POST.
For more information, please consult the {security-api-url}org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.html#logoutUrl-java.lang.String-[JavaDoc].
<3> The URL to redirect to after logout has occurred.
The default is `/login?logout`.
For more information, please consult the {security-api-url}org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.html#logoutSuccessUrl-java.lang.String-[JavaDoc].
<4> Let's you specify a custom `LogoutSuccessHandler`.
If this is specified, `logoutSuccessUrl()` is ignored.
For more information, please consult the {security-api-url}org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.html#logoutSuccessHandler-org.springframework.security.web.authentication.logout.LogoutSuccessHandler-[JavaDoc].
<5> Specify whether to invalidate the `HttpSession` at the time of logout.
This is *true* by default.
Configures the `SecurityContextLogoutHandler` under the covers.
For more information, please consult the {security-api-url}org/springframework/security/config/annotation/web/configurers/LogoutConfigurer.html#invalidateHttpSession-boolean-[JavaDoc].
<6> Adds a `LogoutHandler`.
`SecurityContextLogoutHandler` is added as the last `LogoutHandler` by default.
<7> Allows specifying the names of cookies to be removed on logout success.
This is a shortcut for adding a `CookieClearingLogoutHandler` explicitly.

[NOTE]
===
Logouts can of course also be configured using the XML Namespace notation.
Please see the documentation for the <<nsa-logout, logout element>> in the Spring Security XML Namespace section for further details.
===

Generally, in order to customize logout functionality, you can add
`{security-api-url}org/springframework/security/web/authentication/logout/LogoutHandler.html[LogoutHandler]`
and/or
`{security-api-url}org/springframework/security/web/authentication/logout/LogoutSuccessHandler.html[LogoutSuccessHandler]`
implementations.
For many common scenarios, these handlers are applied under the
covers when using the fluent API.

[[jc-logout-handler]]
=== LogoutHandler

Generally, `{security-api-url}org/springframework/security/web/authentication/logout/LogoutHandler.html[LogoutHandler]`
implementations indicate classes that are able to participate in logout handling.
They are expected to be invoked to perform necessary clean-up.
As such they should
not throw exceptions.
Various implementations are provided:

- {security-api-url}org/springframework/security/web/authentication/rememberme/PersistentTokenBasedRememberMeServices.html[PersistentTokenBasedRememberMeServices]
- {security-api-url}org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServices.html[TokenBasedRememberMeServices]
- {security-api-url}org/springframework/security/web/authentication/logout/CookieClearingLogoutHandler.html[CookieClearingLogoutHandler]
- {security-api-url}org/springframework/security/web/csrf/CsrfLogoutHandler.html[CsrfLogoutHandler]
- {security-api-url}org/springframework/security/web/authentication/logout/SecurityContextLogoutHandler.html[SecurityContextLogoutHandler]

Please see <<remember-me-impls>> for details.

Instead of providing `LogoutHandler` implementations directly, the fluent API also provides shortcuts that provide the respective `LogoutHandler` implementations under the covers.
E.g. `deleteCookies()` allows specifying the names of one or more cookies to be removed on logout success.
This is a shortcut compared to adding a `CookieClearingLogoutHandler`.

[[jc-logout-success-handler]]
=== LogoutSuccessHandler

The `LogoutSuccessHandler` is called after a successful logout by the `LogoutFilter`, to handle e.g.
redirection or forwarding to the appropriate destination.
Note that the interface is almost the same as the `LogoutHandler` but may raise an exception.

The following implementations are provided:

- {security-api-url}org/springframework/security/web/authentication/logout/SimpleUrlLogoutSuccessHandler.html[SimpleUrlLogoutSuccessHandler]
- HttpStatusReturningLogoutSuccessHandler

As mentioned above, you don't need to specify the `SimpleUrlLogoutSuccessHandler` directly.
Instead, the fluent API provides a shortcut by setting the `logoutSuccessUrl()`.
This will setup the `SimpleUrlLogoutSuccessHandler` under the covers.
The provided URL will be redirected to after a logout has occurred.
The default is `/login?logout`.

The `HttpStatusReturningLogoutSuccessHandler` can be interesting in REST API type scenarios.
Instead of redirecting to a URL upon the successful logout, this `LogoutSuccessHandler` allows you to provide a plain HTTP status code to be returned.
If not configured a status code 200 will be returned by default.

[[jc-logout-references]]
=== Further Logout-Related References

- <<ns-logout, Logout Handling>>
- <<test-logout, Testing Logout>>
- <<servletapi-logout, HttpServletRequest.logout()>>
- <<remember-me-impls>>
- <<csrf-logout, Logging Out>> in section CSRF Caveats
- Section <<cas-singlelogout, Single Logout>> (CAS protocol)
- Documentation for the <<nsa-logout, logout element>> in the Spring Security XML Namespace section


include::oauth2-client.adoc[]

include::oauth2-login.adoc[]


[[oauth2resourceserver]]
== OAuth 2.0 Resource Server

Spring Security supports protecting endpoints using https://tools.ietf.org/html/rfc7519[JWT]-encoded OAuth 2.0 https://tools.ietf.org/html/rfc6750.html[Bearer Tokens].

This is handy in circumstances where an application has federated its authority management out to an https://tools.ietf.org/html/rfc6749[authorization server] (for example, Okta or Ping Identity).
This authorization server can be consulted by Resource Servers to validate authority when serving requests.

[NOTE]
====
A complete working example can be found in {gh-samples-url}/boot/oauth2resourceserver[*OAuth 2.0 Resource Server Servlet sample*].
====

=== Dependencies

Most Resource Server support is collected into `spring-security-oauth2-resource-server`.
However, the support for decoding and verifying JWTs is in `spring-security-oauth2-jose`, meaning that both are necessary in order to have a working resource server that supports JWT-encoded Bearer Tokens.

[[oauth2resourceserver-minimalconfiguration]]
=== Minimal Configuration

When using https://spring.io/projects/spring-boot[Spring Boot], configuring an application as a resource server consists of two basic steps.
First, include the needed dependencies and second, indicate the location of the authorization server.

==== Specifying the Authorization Server

To specify which authorization server to use, simply do:

```yaml
security:
  oauth2:
    resourceserver:
      jwt:
        issuer-uri: https://idp.example.com
```

Where `https://idp.example.com` is the value contained in the `iss` claim for JWT tokens that the authorization server will issue.
Resource Server will use this property to further self-configure, discover the authorization server's public keys, and subsequently validate incoming JWTs.

[NOTE]
To use the `issuer-uri` property, it must also be true that `https://idp.example.com/.well-known/openid-configuration` is a supported endpoint for the authorization server.
This endpoint is referred to as a https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig[Provider Configuration] endpoint.

And that's it!

==== Startup Expectations

When this property and these dependencies are used, Resource Server will automatically configure itself to validate JWT-encoded Bearer Tokens.

It achieves this through a deterministic startup process:

1. Hit the Provider Configuration endpoint, `https://idp.example.com/.well-known/openid-configuration`, processing the response for the `jwks_url` property
2. Configure the validation strategy to query `jwks_url` for valid public keys
3. Configure the validation strategy to validate each JWTs `iss` claim against `https://idp.example.com`.

A consequence of this process is that the authorization server must be up and receiving requests in order for Resource Server to successfully start up.

[NOTE]
If the authorization server is down when Resource Server queries it (given appropriate timeouts), then startup will fail.

==== Runtime Expectations

Once the application is started up, Resource Server will attempt to process any request containing an `Authorization: Bearer` header:

```http
GET / HTTP/1.1
Authorization: Bearer some-token-value # Resource Server will process this
```

So long as this scheme is indicated, Resource Server will attempt to process the request according to the Bearer Token specification.

Given a well-formed JWT token, Resource Server will

1. Validate its signature against a public key obtained from the `jwks_url` endpoint during startup and matched against the JWTs header
2. Validate the JWTs `exp` and `nbf` timestamps and the JWTs `iss` claim, and
3. Map each scope to an authority with the prefix `SCOPE_`.

[NOTE]
As the authorization server makes available new keys, Spring Security will automatically rotate the keys used to validate the JWT tokens.

The resulting `Authentication#getPrincipal`, by default, is a Spring Security `Jwt` object, and `Authentication#getName` maps to the JWT's `sub` property, if one is present.

From here, consider jumping to:

<<oauth2resourceserver-jwkseturi,How to Configure without Tying Resource Server startup to an authorization server's availability>>

<<oauth2resourceserver-sansboot,How to Configure without Spring Boot>>

[[oauth2resourceserver-jwkseturi]]
=== Specifying the Authorization Server JWK Set Uri Directly

If the authorization server doesn't support the Provider Configuration endpoint, or if Resource Server must be able to start up independently from the authorization server, then `issuer-uri` can be exchanged for `jwk-set-uri`:

```yaml
security:
  oauth2:
    resourceserver:
      jwt:
        jwk-set-uri: https://idp.example.com/.well-known/jwks.json
```

[NOTE]
The JWK Set uri is not standardized, but can typically be found in the authorization server's documentation

Consequently, Resource Server will not ping the authorization server at startup.
However, it will also no longer validate the `iss` claim in the JWT (since Resource Server no longer knows what the issuer value should be).

[NOTE]
This property can also be supplied directly on the <<oauth2resourceserver-jwkseturi-dsl,DSL>>.

[[oauth2resourceserver-sansboot]]
=== Overriding or Replacing Boot Auto Configuration

There are two `@Bean` s that Spring Boot generates on Resource Server's behalf.

The first is a `WebSecurityConfigurerAdapter` that configures the app as a resource server:

```java
protected void configure(HttpSecurity http) {
    http
        .authorizeRequests()
            .anyRequest().authenticated()
            .and()
        .oauth2ResourceServer()
            .jwt();
}
```

If the application doesn't expose a `WebSecurityConfigurerAdapter` bean, then Spring Boot will expose the above default one.

Replacing this is as simple as exposing the bean within the application:

```java
@EnableWebSecurity
public class MyCustomSecurityConfiguration extends WebSecurityConfigurerAdapter {
    protected void configure(HttpSecurity http) {
        http
            .authorizeRequests()
                .mvcMatchers("/messages/**").hasAuthority("SCOPE_message:read")
                .anyRequest().authenticated()
                .and()
            .oauth2ResourceServer()
                .jwt()
                    .jwtAuthenticationConverter(myConverter());
    }
}
```

The above requires the scope of `message:read` for any URL that starts with `/messages/`.

Methods on the `oauth2ResourceServer` DSL will also override or replace auto configuration.

For example, the second `@Bean` Spring Boot creates is a `JwtDecoder`, which decodes `String` tokens into validated instances of `Jwt`:

```java
@Bean
public JwtDecoder jwtDecoder() {
    return JwtDecoders.fromOidcIssuerLocation(issuerUri);
}
```

If the application doesn't expose a `JwtDecoder` bean, then Spring Boot will expose the above default one.

And its configuration can be overridden using `jwkSetUri()` or replaced using `decoder()`.

[[oauth2resourceserver-jwkseturi-dsl]]
==== Using `jwkSetUri()`

An authorization server's JWK Set Uri can be configured <<oauth2resourceserver-jwkseturi,as a configuration property>> or it can be supplied in the DSL:

```java
@EnableWebSecurity
public class DirectlyConfiguredJwkSetUri extends WebSecurityConfigurerAdapter {
    protected void configure(HttpSecurity http) {
        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .oauth2ResourceServer()
                .jwt()
                    .jwkSetUri("https://idp.example.com/.well-known/jwks.json");
    }
}
```

Using `jwkSetUri()` takes precedence over any configuration property.

[[oauth2resourceserver-decoder-dsl]]
==== Using `decoder()`

More powerful than `jwkSetUri()` is `decoder()`, which will completely replace any Boot auto configuration of `JwtDecoder`:

```java
@EnableWebSecurity
public class DirectlyConfiguredJwkSetUri extends WebSecurityConfigurerAdapter {
    protected void configure(HttpSecurity http) {
        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .oauth2ResourceServer()
                .jwt()
                    .decoder(myCustomDecoder());
    }
}
```

This is handy when deeper configuration, like <<oauth2resourceserver-validation,validation>>, <<oauth2resourceserver-claimsetmapping,mapping>>, or <<oauth2resourceserver-timeouts,request timeouts>>, is necessary.

[[oauth2resourceserver-decoder-bean]]
==== Exposing a `JwtDecoder` `@Bean`

Or, exposing a `JwtDecoder` `@Bean` has the same effect as `decoder()`:

```java
@Bean
public JwtDecoder jwtDecoder() {
    return new NimbusJwtDecoderJwkSupport(jwkSetUri);
}
```

[[oauth2resourceserver-authorization]]
=== Configuring Authorization

A JWT that is issued from an OAuth 2.0 Authorization Server will typically either have a `scope` or `scp` attribute, indicating the scopes (or authorities) it's been granted, for example:

`{ ..., "scope" : "messages contacts"}`

When this is the case, Resource Server will attempt to coerce these scopes into a list of granted authorities, prefixing each scope with the string "SCOPE_".

This means that to protect an endpoint or method with a scope derived from a JWT, the corresponding expressions should include this prefix:

```java
@EnableWebSecurity
public class DirectlyConfiguredJwkSetUri extends WebSecurityConfigurerAdapter {
    protected void configure(HttpSecurity http) {
        http
            .authorizeRequests()
                .mvcMatchers("/contacts/**").hasAuthority("SCOPE_contacts")
                .mvcMatchers("/messages/**").hasAuthority("SCOPE_messages")
                .anyRequest().authenticated()
                .and()
            .oauth2ResourceServer()
                .jwt();
    }
}
```

Or similarly with method security:

```java
@PreAuthorize("hasAuthority('SCOPE_messages')")
public List<Message> getMessages(...) {}
```

[[oauth2resourceserver-authorization-extraction]]
==== Extracting Authorities Manually

However, there are a number of circumstances where this default is insufficient.
For example, some authorization servers don't use the `scope` attribute, but instead have their own custom attribute.
Or, at other times, the resource server may need to adapt the attribute or a composition of attributes into internalized authorities.

To this end, the DSL exposes `jwtAuthenticationConverter()`:

```java
@EnableWebSecurity
public class DirectlyConfiguredJwkSetUri extends WebSecurityConfigurerAdapter {
    protected void configure(HttpSecurity http) {
        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .oauth2ResourceServer()
                .jwt()
                    .jwtAuthenticationConverter(grantedAuthoritiesExtractor());
    }
}

Converter<Jwt, AbstractAuthenticationToken> grantedAuthoritiesExtractor() {
    return new GrantedAuthoritiesExtractor();
}
```

which is responsible for converting a `Jwt` into an `Authentication`.

We can override this quite simply to alter the way granted authorities are derived:

```java
static class GrantedAuthoritiesExtractor extends JwtAuthenticationConverter {
    protected Collection<GrantedAuthorities> extractAuthorities(Jwt jwt) {
        Collection<String> authorities = (Collection<String>)
                jwt.getClaims().get("mycustomclaim");

        return authorities.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
    }
}
```

For more flexibility, the DSL supports entirely replacing the converter with any class that implements `Converter<Jwt, AbstractAuthenticationToken>`:

```java
static class CustomAuthenticationConverter implements Converter<Jwt, AbstractAuthenticationToken> {
    public AbstractAuthenticationToken convert(Jwt jwt) {
        return new CustomAuthenticationToken(jwt);
    }
}
```

[[oauth2resourceserver-validation]]
=== Configuring Validation

Using <<oauth2resourceserver-minimalconfiguration,minimal Spring Boot configuration>>, indicating the authorization server's issuer uri, Resource Server will default to verifying the `iss` claim as well as the `exp` and `nbf` timestamp claims.

In circumstances where validation needs to be customized, Resource Server ships with two standard validators and also accepts custom `OAuth2TokenValidator` instances.

[[oauth2resourceserver-validation-clockskew]]
==== Customizing Timestamp Validation

JWT's typically have a window of validity, with the start of the window indicated in the `nbf` claim and the end indicated in the `exp` claim.

However, every server can experience clock drift, which can cause tokens to appear expired to one server, but not to another.
This can cause some implementation heartburn as the number of collaborating servers increases in a distributed system.

Resource Server uses `JwtTimestampValidator` to verify a token's validity window, and it can be configured with a `clockSkew` to alleviate the above problem:

```java
@Bean
JwtDecoder jwtDecoder() {
     NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder)
             JwtDecoders.fromOidcIssuerLocation(issuerUri);

     OAuth2TokenValidator<Jwt> withClockSkew = new DelegatingOAuth2TokenValidator<>(
            new JwtTimestampValidator(Duration.ofSeconds(60)),
            new IssuerValidator(issuerUri));

     jwtDecoder.setJwtValidator(withClockSkew);

     return jwtDecoder;
}
```

[NOTE]
By default, Resource Server configures a clock skew of 30 seconds.

[[oauth2resourceserver-validation-custom]]
==== Configuring a Custom Validator

Adding a check for the `aud` claim is simple with the `OAuth2TokenValidator` API:

```java
public class AudienceValidator implements OAuth2TokenValidator<Jwt> {
    OAuth2Error error = new OAuth2Error("invalid_token", "The required audience is missing", null);

    public OAuth2TokenValidatorResult validate(Jwt jwt) {
        if (jwt.getAudience().contains("messaging")) {
            return OAuth2TokenValidatorResult.success();
        } else {
            return OAuth2TokenValidatorResult.failure(error);
        }
    }
}
```

Then, to add into a resource server, it's a matter of specifying the `JwtDecoder` instance:

```java
@Bean
JwtDecoder jwtDecoder() {
    NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder)
        JwtDecoders.fromOidcIssuerLocation(issuerUri);

    OAuth2TokenValidator<Jwt> audienceValidator = new AudienceValidator();
    OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuerUri);
    OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator);

    jwtDecoder.setJwtValidator(withAudience);

    return jwtDecoder;
}
```

[[oauth2resourceserver-claimsetmapping]]
=== Configuring Claim Set Mapping

Spring Security uses the https://bitbucket.org/connect2id/nimbus-jose-jwt/wiki/Home[Nimbus] library for parsing JWTs and validating their signatures.
Consequently, Spring Security is subject to Nimbus's interpretation of each field value and how to coerce each into a Java type.

For example, because Nimbus remains Java 7 compatible, it doesn't use `Instant` to represent timestamp fields.

And it's entirely possible to use a different library or for JWT processing, which may make its own coercion decisions that need adjustment.

Or, quite simply, a resource server may want to add or remove claims from a JWT for domain-specific reasons.

For these purposes, Resource Server supports mapping the JWT claim set with `MappedJwtClaimSetConverter`.

[[oauth2resourceserver-claimsetmapping-singleclaim]]
==== Customizing the Conversion of a Single Claim

By default, `MappedJwtClaimSetConverter` will attempt to coerce claims into the following types:

|============
| Claim | Java Type
| `aud` | `Collection<String>`
| `exp` | `Instant`
| `iat` | `Instant`
| `iss` | `String`
| `jti` | `String`
| `nbf` | `Instant`
| `sub` | `String`
|============

An individual claim's conversion strategy can be configured using `MappedJwtClaimSetConverter.withDefaults`:

```java
@Bean
JwtDecoder jwtDecoder() {
    NimbusJwtDecoderJwkSupport jwtDecoder = new NimbusJwtDecoderJwkSupport(jwkSetUri);

    MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter
            .withDefaults(Collections.singletonMap("sub", this::lookupUserIdBySub));
    jwtDecoder.setJwtClaimSetConverter(converter);

    return jwtDecoder;
}
```
This will keep all the defaults, except it will override the default claim converter for `sub`.

[[oauth2resourceserver-claimsetmapping-add]]
==== Adding a Claim

`MappedJwtClaimSetConverter` can also be used to add a custom claim, for example, to adapt to an existing system:

```java
MappedJwtClaimSetConverter.withDefaults(Collections.singletonMap("custom", custom -> "value"));
```

[[oauth2resourceserver-claimsetmapping-remove]]
==== Removing a Claim

And removing a claim is also simple, using the same API:

```java
MappedJwtClaimSetConverter.withDefaults(Collections.singletonMap("legacyclaim", legacy -> null));
```

[[oauth2resourceserver-claimsetmapping-rename]]
==== Renaming a Claim

In more sophisticated scenarios, like consulting multiple claims at once or renaming a claim, Resource Server accepts any class that implements `Converter<Map<String, Object>, Map<String,Object>>`:

```java
public class UsernameSubClaimAdapter implements Converter<Map<String, Object>, Map<String, Object>> {
    private final MappedJwtClaimSetConverter delegate =
            MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap());

    public Map<String, Object> convert(Map<String, Object> claims) {
        Map<String, Object> convertedClaims = this.delegate.convert(claims);

        String username = (String) convertedClaims.get("user_name");
        convertedClaims.put("sub", username);

        return convertedClaims;
    }
}
```

And then, the instance can be supplied like normal:

```java
@Bean
JwtDecoder jwtDecoder() {
    NimbusJwtDecoderJwkSupport jwtDecoder = new NimbusJwtDecoderJwkSupport(jwkSetUri);
    jwtDecoder.setJwtClaimSetConverter(new UsernameSubClaimAdapter());
    return jwtDecoder;
}
```

[[oauth2resourceserver-timeouts]]
=== Configuring Timeouts

By default, Resource Server uses connection and socket timeouts of 30 seconds each for coordinating with the authorization server.

This may be too short in some scenarios.
Further, it doesn't take into account more sophisticated patterns like back-off and discovery.

To adjust the way in which Resource Server connects to the authorization server, `NimbusJwtDecoderJwkSupport` accepts an instance of `RestOperations`:

```java
@Bean
public JwtDecoder jwtDecoder(RestTemplateBuilder builder) {
    RestOperations rest = builder
            .setConnectionTimeout(60000)
            .setReadTimeout(60000)
            .build();

    NimbusJwtDecoderJwkSupport jwtDecoder = new NimbusJwtDecoderJwkSupport(jwkSetUri);
    jwtDecoder.setRestOperations(rest);
    return jwtDecoder;
}
```

[[jc-authentication]]
== Authentication

Thus far we have only taken a look at the most basic authentication configuration.
Let's take a look at a few slightly more advanced options for configuring authentication.

[[jc-authentication-inmemory]]
=== In-Memory Authentication

We have already seen an example of configuring in-memory authentication for a single user.
Below is an example to configure multiple users:

[source,java]
----
@Bean
public UserDetailsService userDetailsService() throws Exception {
	// ensure the passwords are encoded properly
	UserBuilder users = User.withDefaultPasswordEncoder();
	InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
	manager.createUser(users.username("user").password("password").roles("USER").build());
	manager.createUser(users.username("admin").password("password").roles("USER","ADMIN").build());
	return manager;
}
----

[[jc-authentication-jdbc]]
=== JDBC Authentication

You can find the updates to support JDBC based authentication.
The example below assumes that you have already defined a `DataSource` within your application.
The https://github.com/spring-projects/spring-security/tree/master/samples/javaconfig/jdbc[jdbc-javaconfig] sample provides a complete example of using JDBC based authentication.

[source,java]
----
@Autowired
private DataSource dataSource;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
	// ensure the passwords are encoded properly
	UserBuilder users = User.withDefaultPasswordEncoder();
	auth
		.jdbcAuthentication()
			.dataSource(dataSource)
			.withDefaultSchema()
			.withUser(users.username("user").password("password").roles("USER"))
			.withUser(users.username("admin").password("password").roles("USER","ADMIN"));
}
----

=== LDAP Authentication

You can find the updates to support LDAP based authentication.
The https://github.com/spring-projects/spring-security/tree/master/samples/javaconfig/ldap[ldap-javaconfig] sample provides a complete example of using LDAP based authentication.

[source,java]
----
@Autowired
private DataSource dataSource;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
	auth
		.ldapAuthentication()
			.userDnPatterns("uid={0},ou=people")
			.groupSearchBase("ou=groups");
}
----

The example above uses the following LDIF and an embedded Apache DS LDAP instance.

.users.ldif
----
dn: ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: groups

dn: ou=people,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: people

dn: uid=admin,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Rod Johnson
sn: Johnson
uid: admin
userPassword: password

dn: uid=user,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Dianne Emu
sn: Emu
uid: user
userPassword: password

dn: cn=user,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: groupOfNames
cn: user
uniqueMember: uid=admin,ou=people,dc=springframework,dc=org
uniqueMember: uid=user,ou=people,dc=springframework,dc=org

dn: cn=admin,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: groupOfNames
cn: admin
uniqueMember: uid=admin,ou=people,dc=springframework,dc=org
----

[[jc-authentication-authenticationprovider]]
=== AuthenticationProvider

You can define custom authentication by exposing a custom `AuthenticationProvider` as a bean.
For example, the following will customize authentication assuming that `SpringAuthenticationProvider` implements `AuthenticationProvider`:

NOTE: This is only used if the `AuthenticationManagerBuilder` has not been populated

[source,java]
----
@Bean
public SpringAuthenticationProvider springAuthenticationProvider() {
	return new SpringAuthenticationProvider();
}
----

[[jc-authentication-userdetailsservice]]
=== UserDetailsService

You can define custom authentication by exposing a custom `UserDetailsService` as a bean.
For example, the following will customize authentication assuming that `SpringDataUserDetailsService` implements `UserDetailsService`:

NOTE: This is only used if the `AuthenticationManagerBuilder` has not been populated and no `AuthenticationProviderBean` is defined.

[source,java]
----
@Bean
public SpringDataUserDetailsService springDataUserDetailsService() {
	return new SpringDataUserDetailsService();
}
----

You can also customize how passwords are encoded by exposing a `PasswordEncoder` as a bean.
For example, if you use bcrypt you can add a bean definition as shown below:

[source,java]
----
@Bean
public BCryptPasswordEncoder passwordEncoder() {
	return new BCryptPasswordEncoder();
}
----

== Multiple HttpSecurity

We can configure multiple HttpSecurity instances just as we can have multiple `<http>` blocks.
The key is to extend the `WebSecurityConfigurerAdapter` multiple times.
For example, the following is an example of having a different configuration for URL's that start with `/api/`.

[source,java]
----
@EnableWebSecurity
public class MultiHttpSecurityConfig {
	@Bean                                                             <1>
	public UserDetailsService userDetailsService() throws Exception {
		// ensure the passwords are encoded properly
		UserBuilder users = User.withDefaultPasswordEncoder();
		InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
		manager.createUser(users.username("user").password("password").roles("USER").build());
		manager.createUser(users.username("admin").password("password").roles("USER","ADMIN").build());
		return manager;
	}

	@Configuration
	@Order(1)                                                        <2>
	public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
		protected void configure(HttpSecurity http) throws Exception {
			http
				.antMatcher("/api/**")                               <3>
				.authorizeRequests()
					.anyRequest().hasRole("ADMIN")
					.and()
				.httpBasic();
		}
	}

	@Configuration                                                   <4>
	public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

		@Override
		protected void configure(HttpSecurity http) throws Exception {
			http
				.authorizeRequests()
					.anyRequest().authenticated()
					.and()
				.formLogin();
		}
	}
}
----

<1> Configure Authentication as normal
<2> Create an instance of `WebSecurityConfigurerAdapter` that contains `@Order` to specify which `WebSecurityConfigurerAdapter` should be considered first.
<3> The `http.antMatcher` states that this `HttpSecurity` will only be applicable to URLs that start with `/api/`
<4> Create another instance of `WebSecurityConfigurerAdapter`.
If the URL does not start with `/api/` this configuration will be used.
This configuration is considered after `ApiWebSecurityConfigurationAdapter` since it has an `@Order` value after `1` (no `@Order` defaults to last).


[[jc-method]]
== Method Security

From version 2.0 onwards Spring Security has improved support substantially for adding security to your service layer methods.
It provides support for JSR-250 annotation security as well as the framework's original `@Secured` annotation.
From 3.0 you can also make use of new <<el-access,expression-based annotations>>.
You can apply security to a single bean, using the `intercept-methods` element to decorate the bean declaration, or you can secure multiple beans across the entire service layer using the AspectJ style pointcuts.

=== EnableGlobalMethodSecurity

We can enable annotation-based security using the `@EnableGlobalMethodSecurity` annotation on any `@Configuration` instance.
For example, the following would enable Spring Security's `@Secured` annotation.

[source,java]
----
@EnableGlobalMethodSecurity(securedEnabled = true)
public class MethodSecurityConfig {
// ...
}
----

Adding an annotation to a method (on a class or interface) would then limit the access to that method accordingly.
Spring Security's native annotation support defines a set of attributes for the method.
These will be passed to the AccessDecisionManager for it to make the actual decision:

[source,java]
----
public interface BankService {

@Secured("IS_AUTHENTICATED_ANONYMOUSLY")
public Account readAccount(Long id);

@Secured("IS_AUTHENTICATED_ANONYMOUSLY")
public Account[] findAccounts();

@Secured("ROLE_TELLER")
public Account post(Account account, double amount);
}
----

Support for JSR-250 annotations can be enabled using

[source,java]
----
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public class MethodSecurityConfig {
// ...
}
----

These are standards-based and allow simple role-based constraints to be applied but do not have the power Spring Security's native annotations.
To use the new expression-based syntax, you would use

[source,java]
----
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig {
// ...
}
----

and the equivalent Java code would be

[source,java]
----
public interface BankService {

@PreAuthorize("isAnonymous()")
public Account readAccount(Long id);

@PreAuthorize("isAnonymous()")
public Account[] findAccounts();

@PreAuthorize("hasAuthority('ROLE_TELLER')")
public Account post(Account account, double amount);
}
----

=== GlobalMethodSecurityConfiguration

Sometimes you may need to perform operations that are more complicated than are possible with the `@EnableGlobalMethodSecurity` annotation allow.
For these instances, you can extend the `GlobalMethodSecurityConfiguration` ensuring that the `@EnableGlobalMethodSecurity` annotation is present on your subclass.
For example, if you wanted to provide a custom `MethodSecurityExpressionHandler`, you could use the following configuration:

[source,java]
----
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
	@Override
	protected MethodSecurityExpressionHandler createExpressionHandler() {
		// ... create and return custom MethodSecurityExpressionHandler ...
		return expressionHandler;
	}
}
----

For additional information about methods that can be overridden, refer to the `GlobalMethodSecurityConfiguration` Javadoc.

== Post Processing Configured Objects

Spring Security's Java Configuration does not expose every property of every object that it configures.
This simplifies the configuration for a majority of users.
Afterall, if every property was exposed, users could use standard bean configuration.

While there are good reasons to not directly expose every property, users may still need more advanced configuration options.
To address this Spring Security introduces the concept of an `ObjectPostProcessor` which can be used to modify or replace many of the Object instances created by the Java Configuration.
For example, if you wanted to configure the `filterSecurityPublishAuthorizationSuccess` property on `FilterSecurityInterceptor` you could use the following:

[source,java]
----
@Override
protected void configure(HttpSecurity http) throws Exception {
	http
		.authorizeRequests()
			.anyRequest().authenticated()
			.withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
				public <O extends FilterSecurityInterceptor> O postProcess(
						O fsi) {
					fsi.setPublishAuthorizationSuccess(true);
					return fsi;
				}
			});
}
----

[[jc-custom-dsls]]
== Custom DSLs

You can provide your own custom DSLs in Spring Security.
For example, you might have something that looks like this:

[source,java]
----
public class MyCustomDsl extends AbstractHttpConfigurer<MyCustomDsl, HttpSecurity> {
	private boolean flag;

	@Override
	public void init(H http) throws Exception {
		// any method that adds another configurer
		// must be done in the init method
		http.csrf().disable();
	}

	@Override
	public void configure(H http) throws Exception {
		ApplicationContext context = http.getSharedObject(ApplicationContext.class);

		// here we lookup from the ApplicationContext. You can also just create a new instance.
		MyFilter myFilter = context.getBean(MyFilter.class);
		myFilter.setFlag(flag);
		http.addFilterBefore(myFilter, UsernamePasswordAuthenticationFilter.class);
	}

	public MyCustomDsl flag(boolean value) {
		this.flag = value;
		return this;
	}

	public static MyCustomDsl customDsl() {
		return new MyCustomDsl();
	}
}
----

NOTE: This is actually how methods like `HttpSecurity.authorizeRequests()` are implemented.

The custom DSL can then be used like this:

[source,java]
----
@EnableWebSecurity
public class Config extends WebSecurityConfigurerAdapter {
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.apply(customDsl())
				.flag(true)
				.and()
			...;
	}
}
----

The code is invoked in the following order:

* Code in `Config`s configure method is invoked
* Code in `MyCustomDsl`s init method is invoked
* Code in `MyCustomDsl`s configure method is invoked

If you want, you can have `WebSecurityConfiguerAdapter` add `MyCustomDsl` by default by using `SpringFactories`.
For example, you would create a resource on the classpath named `META-INF/spring.factories` with the following contents:

.META-INF/spring.factories
----
org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer = sample.MyCustomDsl
----

Users wishing to disable the default can do so explicitly.

[source,java]
----
@EnableWebSecurity
public class Config extends WebSecurityConfigurerAdapter {
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.apply(customDsl()).disable()
			...;
	}
}
----
