General support for 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 Chapter 7, Security Namespace Configuration then you should find quite a few similarities between it and the Security Java Configuration support.
Note | |
---|---|
Spring Security provides lots of sample applications which demonstrate the use of Spring 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:
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 implements WebMvcConfigurer { @Bean public UserDetailsService userDetailsService() throws Exception { 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:
Security Header integration
Integrate with the following Servlet API methods
The next step is to register the springSecurityFilterChain
with the war.
This can be done in Java Configuration with 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.
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:
import org.springframework.security.web.context.*; public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { public SecurityWebApplicationInitializer() { super(WebSecurityConfig.class); } }
The SecurityWebApplicationInitializer
will do the following things:
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:
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()
public class MvcWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[] { WebSecurityConfig.class }; } // ... other overrides ... }
Thus far our 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? The reason for this is that the WebSecurityConfigurerAdapter
provides a default configuration in the configure(HttpSecurity http)
method that looks like:
protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .and() .httpBasic(); }
The default configuration above:
You will notice that this configuration is quite similar the XML Namespace configuration:
<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.
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 log in page. To do so we can update our configuration as seen below:
protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll(); }
The updated configuration specifies the location of the log in page. | |
We must grant all users (i.e. unauthenticated users) access to our log in page.
The |
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. |
<c:url value="/login" var="loginUrl"/> <form action="${loginUrl}" method="post"> <c:if test="${param.error != null}"> <p> Invalid username and password. </p> </c:if> <c:if test="${param.logout != null}"> <p> You have been logged out. </p> </c:if> <p> <label for="username">Username</label> <input type="text" id="username" name="username"/> </p> <p> <label for="password">Password</label> <input type="password" id="password" name="password"/> </p> <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/> <button type="submit" class="btn">Log in</button> </form>
A POST to the | |
If the query parameter | |
If the query parameter | |
The username must be present as the HTTP parameter named username | |
The password must be present as the HTTP parameter named password | |
We must the section called “Include the CSRF Token” To learn more read the Section 10.6, “Cross Site Request Forgery (CSRF)” section of the reference |
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:
protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/resources/**", "/signup", "/about").permitAll() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')") .anyRequest().authenticated() .and() // ... .formLogin(); }
There are multiple children to the | |
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". | |
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 | |
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 | |
Any URL that has not already been matched on only requires that the user be authenticated |
When using the WebSecurityConfigurerAdapter
, logout capabilities are automatically applied.
The default is that accessing the URL /logout
will log the user out by:
SecurityContextHolder
/login?logout
Similar to configuring login capabilities, however, you also have various options to further customize your logout requirements:
protected void configure(HttpSecurity http) throws Exception { http .logout() .logoutUrl("/my/logout") .logoutSuccessUrl("/my/index") .logoutSuccessHandler(logoutSuccessHandler) .invalidateHttpSession(true) .addLogoutHandler(logoutHandler) .deleteCookies(cookieNamesToClear) .and() ... }
Provides logout support.
This is automatically applied when using | |
The URL that triggers log out to occur (default is | |
The URL to redirect to after logout has occurred.
The default is | |
Let’s you specify a custom | |
Specify whether to invalidate the | |
Adds a | |
Allows specifying the names of cookies to be removed on logout success.
This is a shortcut for adding a |
Note | |
---|---|
=== Logouts can of course also be configured using the XML Namespace notation. Please see the documentation for the logout element in the Spring Security XML Namespace section for further details. === |
Generally, in order to customize logout functionality, you can add
LogoutHandler
and/or
LogoutSuccessHandler
implementations.
For many common scenarios, these handlers are applied under the
covers when using the fluent API.
Generally, 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:
Please see Section 10.5.4, “Remember-Me Interfaces and Implementations” 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
.
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:
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.
The OAuth 2.0 Client features provide support for the Client role as defined in the OAuth 2.0 Authorization Framework.
The following main features are available:
WebClient
extension for Servlet Environments (for making protected resource requests)
HttpSecurity.oauth2Client()
provides a number of configuration options for customizing OAuth 2.0 Client.
The following code shows the complete configuration options available for the oauth2Client()
DSL:
@EnableWebSecurity public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .oauth2Client() .clientRegistrationRepository(this.clientRegistrationRepository()) .authorizedClientRepository(this.authorizedClientRepository()) .authorizedClientService(this.authorizedClientService()) .authorizationCodeGrant() .authorizationRequestRepository(this.authorizationRequestRepository()) .authorizationRequestResolver(this.authorizationRequestResolver()) .accessTokenResponseClient(this.accessTokenResponseClient()); } }
The following sections go into more detail on each of the configuration options available:
ClientRegistration
is a representation of a client registered with an OAuth 2.0 or OpenID Connect 1.0 Provider.
A client registration holds information, such as client id, client secret, authorization grant type, redirect URI, scope(s), authorization URI, token URI, and other details.
ClientRegistration
and its properties are defined as follows:
public final class ClientRegistration { private String registrationId; private String clientId; private String clientSecret; private ClientAuthenticationMethod clientAuthenticationMethod; private AuthorizationGrantType authorizationGrantType; private String redirectUriTemplate; private Set<String> scopes; private ProviderDetails providerDetails; private String clientName; public class ProviderDetails { private String authorizationUri; private String tokenUri; private UserInfoEndpoint userInfoEndpoint; private String jwkSetUri; private Map<String, Object> configurationMetadata; public class UserInfoEndpoint { private String uri; private AuthenticationMethod authenticationMethod; private String userNameAttributeName; } } }
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
The ClientRegistrationRepository
serves as a repository for OAuth 2.0 / OpenID Connect 1.0 ClientRegistration
(s).
Note | |
---|---|
Client registration information is ultimately stored and owned by the associated Authorization Server. This repository provides the ability to retrieve a sub-set of the primary client registration information, which is stored with the Authorization Server. |
Spring Boot 2.x auto-configuration binds each of the properties under spring.security.oauth2.client.registration.[registrationId]
to an instance of ClientRegistration
and then composes each of the ClientRegistration
instance(s) within a ClientRegistrationRepository
.
Note | |
---|---|
The default implementation of |
The auto-configuration also registers the ClientRegistrationRepository
as a @Bean
in the ApplicationContext
so that it is available for dependency-injection, if needed by the application.
The following listing shows an example:
@Controller public class OAuth2ClientController { @Autowired private ClientRegistrationRepository clientRegistrationRepository; @RequestMapping("/") public String index() { ClientRegistration googleRegistration = this.clientRegistrationRepository.findByRegistrationId("google"); ... return "index"; } }
OAuth2AuthorizedClient
is a representation of an Authorized Client.
A client is considered to be authorized when the end-user (Resource Owner) has granted authorization to the client to access its protected resources.
OAuth2AuthorizedClient
serves the purpose of associating an OAuth2AccessToken
(and optional OAuth2RefreshToken
) to a ClientRegistration
(client) and resource owner, who is the Principal
end-user that granted the authorization.
OAuth2AuthorizedClientRepository
is responsible for persisting OAuth2AuthorizedClient
(s) between web requests.
Whereas, the primary role of OAuth2AuthorizedClientService
is to manage OAuth2AuthorizedClient
(s) at the application-level.
From a developer perspective, the OAuth2AuthorizedClientRepository
or OAuth2AuthorizedClientService
provides the capability to lookup an OAuth2AccessToken
associated with a client so that it may be used to initiate a protected resource request.
Note | |
---|---|
Spring Boot 2.x auto-configuration registers an |
The developer may also register an OAuth2AuthorizedClientRepository
or OAuth2AuthorizedClientService
@Bean
in the ApplicationContext
(overriding Spring Boot 2.x auto-configuration) in order to have the ability to lookup an OAuth2AccessToken
associated with a specific ClientRegistration
(client).
The following listing shows an example:
@Controller public class OAuth2LoginController { @Autowired private OAuth2AuthorizedClientService authorizedClientService; @RequestMapping("/userinfo") public String userinfo(OAuth2AuthenticationToken authentication) { // authentication.getAuthorizedClientRegistrationId() returns the // registrationId of the Client that was authorized during the oauth2Login() flow OAuth2AuthorizedClient authorizedClient = this.authorizedClientService.loadAuthorizedClient( authentication.getAuthorizedClientRegistrationId(), authentication.getName()); OAuth2AccessToken accessToken = authorizedClient.getAccessToken(); ... return "userinfo"; } }
The @RegisteredOAuth2AuthorizedClient
annotation provides the capability of resolving a method parameter to an argument value of type OAuth2AuthorizedClient
.
This is a convenient alternative compared to looking up the OAuth2AuthorizedClient
via the OAuth2AuthorizedClientService
.
@Controller public class OAuth2LoginController { @RequestMapping("/userinfo") public String userinfo(@RegisteredOAuth2AuthorizedClient("google") OAuth2AuthorizedClient authorizedClient) { OAuth2AccessToken accessToken = authorizedClient.getAccessToken(); ... return "userinfo"; } }
The @RegisteredOAuth2AuthorizedClient
annotation is handled by OAuth2AuthorizedClientArgumentResolver
and provides the following capabilities:
An OAuth2AccessToken
will automatically be requested if the client has not yet been authorized.
authorization_code
, this involves triggering the authorization request redirect to initiate the flow
client_credentials
, the access token is directly obtained from the Token Endpoint using DefaultClientCredentialsTokenResponseClient
AuthorizationRequestRepository
is responsible for the persistence of the OAuth2AuthorizationRequest
from the time the Authorization Request is initiated to the time the Authorization Response is received (the callback).
Tip | |
---|---|
The |
The default implementation of AuthorizationRequestRepository
is HttpSessionOAuth2AuthorizationRequestRepository
, which stores the OAuth2AuthorizationRequest
in the HttpSession
.
If you would like to provide a custom implementation of AuthorizationRequestRepository
that stores the attributes of OAuth2AuthorizationRequest
in a Cookie
, you may configure it as shown in the following example:
@EnableWebSecurity public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .oauth2Client() .authorizationCodeGrant() .authorizationRequestRepository(this.cookieAuthorizationRequestRepository()) ... } private AuthorizationRequestRepository<OAuth2AuthorizationRequest> cookieAuthorizationRequestRepository() { return new HttpCookieOAuth2AuthorizationRequestRepository(); } }
The primary role of the OAuth2AuthorizationRequestResolver
is to resolve an OAuth2AuthorizationRequest
from the provided web request.
The default implementation DefaultOAuth2AuthorizationRequestResolver
matches on the (default) path /oauth2/authorization/{registrationId}
extracting the registrationId
and using it to build the OAuth2AuthorizationRequest
for the associated ClientRegistration
.
One of the primary use cases an OAuth2AuthorizationRequestResolver
can realize is the ability to customize the Authorization Request with additional parameters above the standard parameters defined in the OAuth 2.0 Authorization Framework.
For example, OpenID Connect defines additional OAuth 2.0 request parameters for the Authorization Code Flow extending from the standard parameters defined in the OAuth 2.0 Authorization Framework.
One of those extended parameters is the prompt
parameter.
Note | |
---|---|
OPTIONAL. Space delimited, case sensitive list of ASCII string values that specifies whether the Authorization Server prompts the End-User for reauthentication and consent. The defined values are: none, login, consent, select_account |
The following example shows how to implement an OAuth2AuthorizationRequestResolver
that customizes the Authorization Request for oauth2Login()
, by including the request parameter prompt=consent
.
@EnableWebSecurity public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private ClientRegistrationRepository clientRegistrationRepository; @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .oauth2Login() .authorizationEndpoint() .authorizationRequestResolver( new CustomAuthorizationRequestResolver( this.clientRegistrationRepository)); } } public class CustomAuthorizationRequestResolver implements OAuth2AuthorizationRequestResolver { private final OAuth2AuthorizationRequestResolver defaultAuthorizationRequestResolver; public CustomAuthorizationRequestResolver( ClientRegistrationRepository clientRegistrationRepository) { this.defaultAuthorizationRequestResolver = new DefaultOAuth2AuthorizationRequestResolver( clientRegistrationRepository, "/oauth2/authorization"); } @Override public OAuth2AuthorizationRequest resolve(HttpServletRequest request) { OAuth2AuthorizationRequest authorizationRequest = this.defaultAuthorizationRequestResolver.resolve(request); return authorizationRequest != null ? customAuthorizationRequest(authorizationRequest) : null; } @Override public OAuth2AuthorizationRequest resolve( HttpServletRequest request, String clientRegistrationId) { OAuth2AuthorizationRequest authorizationRequest = this.defaultAuthorizationRequestResolver.resolve( request, clientRegistrationId); return authorizationRequest != null ? customAuthorizationRequest(authorizationRequest) : null; } private OAuth2AuthorizationRequest customAuthorizationRequest( OAuth2AuthorizationRequest authorizationRequest) { Map<String, Object> additionalParameters = new LinkedHashMap<>(authorizationRequest.getAdditionalParameters()); additionalParameters.put("prompt", "consent"); return OAuth2AuthorizationRequest.from(authorizationRequest) .additionalParameters(additionalParameters) .build(); } }
Configure the custom | |
Attempt to resolve the | |
If an | |
Add custom parameters to the existing | |
Create a copy of the default | |
Override the default |
Tip | |
---|---|
|
The preceding example shows the common use case of adding a custom parameter on top of the standard parameters.
However, if you need to remove or change a standard parameter or your requirements are more advanced, than you can take full control in building the Authorization Request URI by simply overriding the OAuth2AuthorizationRequest.authorizationRequestUri
property.
The following example shows a variation of the customAuthorizationRequest()
method from the preceding example, and instead overrides the OAuth2AuthorizationRequest.authorizationRequestUri
property.
private OAuth2AuthorizationRequest customAuthorizationRequest( OAuth2AuthorizationRequest authorizationRequest) { String customAuthorizationRequestUri = UriComponentsBuilder .fromUriString(authorizationRequest.getAuthorizationRequestUri()) .queryParam("prompt", "consent") .build(true) .toUriString(); return OAuth2AuthorizationRequest.from(authorizationRequest) .authorizationRequestUri(customAuthorizationRequestUri) .build(); }
The primary role of the OAuth2AccessTokenResponseClient
is to exchange an authorization grant credential for an access token credential at the Authorization Server’s Token Endpoint.
The default implementation of OAuth2AccessTokenResponseClient
for the authorization_code
grant is DefaultAuthorizationCodeTokenResponseClient
, which uses a RestOperations
for exchanging an authorization code for an access token at the Token Endpoint.
The DefaultAuthorizationCodeTokenResponseClient
is quite flexible as it allows you to customize the pre-processing of the Token Request and/or post-handling of the Token Response.
If you need to customize the pre-processing of the Token Request, you can provide DefaultAuthorizationCodeTokenResponseClient.setRequestEntityConverter()
with a custom Converter<OAuth2AuthorizationCodeGrantRequest, RequestEntity<?>>
.
The default implementation OAuth2AuthorizationCodeGrantRequestEntityConverter
builds a RequestEntity
representation of a standard OAuth 2.0 Access Token Request.
However, providing a custom Converter
, would allow you to extend the standard Token Request and add a custom parameter for example.
Important | |
---|---|
The custom |
On the other end, if you need to customize the post-handling of the Token Response, you will need to provide DefaultAuthorizationCodeTokenResponseClient.setRestOperations()
with a custom configured RestOperations
.
The default RestOperations
is configured as follows:
RestTemplate restTemplate = new RestTemplate(Arrays.asList( new FormHttpMessageConverter(), new OAuth2AccessTokenResponseHttpMessageConverter())); restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
Tip | |
---|---|
Spring MVC |
OAuth2AccessTokenResponseHttpMessageConverter
is a HttpMessageConverter
for an OAuth 2.0 Access Token Response.
You can provide OAuth2AccessTokenResponseHttpMessageConverter.setTokenResponseConverter()
with a custom Converter<Map<String, String>, OAuth2AccessTokenResponse>
that is used for converting the OAuth 2.0 Access Token Response parameters to an OAuth2AccessTokenResponse
.
OAuth2ErrorResponseErrorHandler
is a ResponseErrorHandler
that can handle an OAuth 2.0 Error (400 Bad Request).
It uses an OAuth2ErrorHttpMessageConverter
for converting the OAuth 2.0 Error parameters to an OAuth2Error
.
Whether you customize DefaultAuthorizationCodeTokenResponseClient
or provide your own implementation of OAuth2AccessTokenResponseClient
, you’ll need to configure it as shown in the following example:
@EnableWebSecurity public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .oauth2Client() .authorizationCodeGrant() .accessTokenResponseClient(this.customAccessTokenResponseClient()) ... } private OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> customAccessTokenResponseClient() { ... } }
The OAuth 2.0 Login feature provides an application with the capability to have users log in to the application by using their existing account at an OAuth 2.0 Provider (e.g. GitHub) or OpenID Connect 1.0 Provider (such as Google). OAuth 2.0 Login implements the use cases: "Login with Google" or "Login with GitHub".
Note | |
---|---|
OAuth 2.0 Login is implemented by using the Authorization Code Grant, as specified in the OAuth 2.0 Authorization Framework and OpenID Connect Core 1.0. |
Spring Boot 2.x brings full auto-configuration capabilities for OAuth 2.0 Login.
This section shows how to configure the OAuth 2.0 Login sample using Google as the Authentication Provider and covers the following topics:
To use Google’s OAuth 2.0 authentication system for login, you must set up a project in the Google API Console to obtain OAuth 2.0 credentials.
Note | |
---|---|
Google’s OAuth 2.0 implementation for authentication conforms to the OpenID Connect 1.0 specification and is OpenID Certified. |
Follow the instructions on the OpenID Connect page, starting in the section, "Setting up OAuth 2.0".
After completing the "Obtain OAuth 2.0 credentials" instructions, you should have a new OAuth Client with credentials consisting of a Client ID and a Client Secret.
The redirect URI is the path in the application that the end-user’s user-agent is redirected back to after they have authenticated with Google and have granted access to the OAuth Client (created in the previous step) on the Consent page.
In the "Set a redirect URI" sub-section, ensure that the Authorized redirect URIs field is set to http://localhost:8080/login/oauth2/code/google
.
Tip | |
---|---|
The default redirect URI template is |
Now that you have a new OAuth Client with Google, you need to configure the application to use the OAuth Client for the authentication flow. To do so:
Go to application.yml
and set the following configuration:
spring: security: oauth2: client: registration: google: client-id: google-client-id client-secret: google-client-secret
Example 6.1. OAuth Client properties
| |
Following the base property prefix is the ID for the ClientRegistration, such as google. |
client-id
and client-secret
property with the OAuth 2.0 credentials you created earlier.
Launch the Spring Boot 2.x sample and go to http://localhost:8080
.
You are then redirected to the default auto-generated login page, which displays a link for Google.
Click on the Google link, and you are then redirected to Google for authentication.
After authenticating with your Google account credentials, the next page presented to you is the Consent screen. The Consent screen asks you to either allow or deny access to the OAuth Client you created earlier. Click Allow to authorize the OAuth Client to access your email address and basic profile information.
At this point, the OAuth Client retrieves your email address and basic profile information from the UserInfo Endpoint and establishes an authenticated session.
The following table outlines the mapping of the Spring Boot 2.x OAuth Client properties to the ClientRegistration properties.
Spring Boot 2.x | ClientRegistration |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
CommonOAuth2Provider
pre-defines a set of default client properties for a number of well known providers: Google, GitHub, Facebook, and Okta.
For example, the authorization-uri
, token-uri
, and user-info-uri
do not change often for a Provider.
Therefore, it makes sense to provide default values in order to reduce the required configuration.
As demonstrated previously, when we configured a Google client, only the client-id
and client-secret
properties are required.
The following listing shows an example:
spring: security: oauth2: client: registration: google: client-id: google-client-id client-secret: google-client-secret
Tip | |
---|---|
The auto-defaulting of client properties works seamlessly here because the |
For cases where you may want to specify a different registrationId
, such as google-login
, you can still leverage auto-defaulting of client properties by configuring the provider
property.
The following listing shows an example:
spring: security: oauth2: client: registration: google-login: provider: google client-id: google-client-id client-secret: google-client-secret
There are some OAuth 2.0 Providers that support multi-tenancy, which results in different protocol endpoints for each tenant (or sub-domain).
For example, an OAuth Client registered with Okta is assigned to a specific sub-domain and have their own protocol endpoints.
For these cases, Spring Boot 2.x provides the following base property for configuring custom provider properties: spring.security.oauth2.client.provider.[providerId]
.
The following listing shows an example:
spring: security: oauth2: client: registration: okta: client-id: okta-client-id client-secret: okta-client-secret provider: okta: authorization-uri: https://your-subdomain.oktapreview.com/oauth2/v1/authorize token-uri: https://your-subdomain.oktapreview.com/oauth2/v1/token user-info-uri: https://your-subdomain.oktapreview.com/oauth2/v1/userinfo user-name-attribute: sub jwk-set-uri: https://your-subdomain.oktapreview.com/oauth2/v1/keys
The Spring Boot 2.x auto-configuration class for OAuth Client support is OAuth2ClientAutoConfiguration
.
It performs the following tasks:
ClientRegistrationRepository
@Bean
composed of ClientRegistration
(s) from the configured OAuth Client properties.
WebSecurityConfigurerAdapter
@Configuration
and enables OAuth 2.0 Login through httpSecurity.oauth2Login()
.
If you need to override the auto-configuration based on your specific requirements, you may do so in the following ways:
The following example shows how to register a ClientRegistrationRepository
@Bean
:
@Configuration public class OAuth2LoginConfig { @Bean public ClientRegistrationRepository clientRegistrationRepository() { return new InMemoryClientRegistrationRepository(this.googleClientRegistration()); } private ClientRegistration googleClientRegistration() { return ClientRegistration.withRegistrationId("google") .clientId("google-client-id") .clientSecret("google-client-secret") .clientAuthenticationMethod(ClientAuthenticationMethod.BASIC) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .redirectUriTemplate("{baseUrl}/login/oauth2/code/{registrationId}") .scope("openid", "profile", "email", "address", "phone") .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth") .tokenUri("https://www.googleapis.com/oauth2/v4/token") .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo") .userNameAttributeName(IdTokenClaimNames.SUB) .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs") .clientName("Google") .build(); } }
The following example shows how to provide a WebSecurityConfigurerAdapter
with @EnableWebSecurity
and enable OAuth 2.0 login through httpSecurity.oauth2Login()
:
@EnableWebSecurity public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .oauth2Login(); } }
The following example shows how to completely override the auto-configuration by registering a ClientRegistrationRepository
@Bean
and providing a WebSecurityConfigurerAdapter
.
@Configuration public class OAuth2LoginConfig { @EnableWebSecurity public static class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .oauth2Login(); } } @Bean public ClientRegistrationRepository clientRegistrationRepository() { return new InMemoryClientRegistrationRepository(this.googleClientRegistration()); } private ClientRegistration googleClientRegistration() { return ClientRegistration.withRegistrationId("google") .clientId("google-client-id") .clientSecret("google-client-secret") .clientAuthenticationMethod(ClientAuthenticationMethod.BASIC) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .redirectUriTemplate("{baseUrl}/login/oauth2/code/{registrationId}") .scope("openid", "profile", "email", "address", "phone") .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth") .tokenUri("https://www.googleapis.com/oauth2/v4/token") .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo") .userNameAttributeName(IdTokenClaimNames.SUB) .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs") .clientName("Google") .build(); } }
If you are not able to use Spring Boot 2.x and would like to configure one of the pre-defined providers in CommonOAuth2Provider
(for example, Google), apply the following configuration:
@Configuration public class OAuth2LoginConfig { @EnableWebSecurity public static class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .oauth2Login(); } } @Bean public ClientRegistrationRepository clientRegistrationRepository() { return new InMemoryClientRegistrationRepository(this.googleClientRegistration()); } @Bean public OAuth2AuthorizedClientService authorizedClientService( ClientRegistrationRepository clientRegistrationRepository) { return new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository); } @Bean public OAuth2AuthorizedClientRepository authorizedClientRepository( OAuth2AuthorizedClientService authorizedClientService) { return new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(authorizedClientService); } private ClientRegistration googleClientRegistration() { return CommonOAuth2Provider.GOOGLE.getBuilder("google") .clientId("google-client-id") .clientSecret("google-client-secret") .build(); } }
The following additional resources describe advanced configuration options:
Spring Security supports protecting endpoints using JWT-encoded OAuth 2.0 Bearer Tokens.
This is handy in circumstances where an application has federated its authority management out to an authorization server (for example, Okta or Ping Identity). This authorization server can be consulted by Resource Servers to validate authority when serving requests.
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.
When using 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.
To specify which authorization server to use, simply do:
security: oauth2: resourceserver: jwt: issuer-uri: https://the.issuer.location
Where https://the.issuer.location
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 and subsequently validate incoming JWTs.
Note | |
---|---|
To use the |
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:
https://the.issuer.location/.well-known/openid-configuration
, processing the response for the jwks_url
property
jwks_url
for valid public keys
iss
claim against https://the.issuer.location
.
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. |
Once the application is started up, Resource Server will attempt to process any request containing an Authorizatization: Bearer
header:
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 validate the JWTs exp
and nbf
timestamps and the JWTs iss
claim.
It will also validate the signature against a public key obtained from the jwks_url
endpoint and matched against the JWTs header.
The resulting Authentication#getPrincipal
, by default, is a Spring Security Jwt
object, and Authentication#getName
map’s to the JWT’s sub
property, if one is present.
From here, consider jumping to:
How to Configure without Tying Resource Server startup to an authorization server’s availability
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
:
security: oauth2: resourceserver: jwt: jwk-set-uri: https://the.issuer.location/.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 DSL. |
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:
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:
@EnableWebSecurity public class MyCustomSecurityConfiguration extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) { http .authorizeRequests() .mvcMatchers("/admin/**").hasAuthority("SCOPE_admin") .anyRequest().authenticated() .and() .oauth2ResourceServer() .jwt() .jwtAuthenticationConverter(myConverter()); } }
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
:
@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()
.
An authorization server’s JWK Set Uri can be configured as a configuration property or it can be supplied in the DSL:
@EnableWebSecurity public class DirectlyConfiguredJwkSetUri extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) { http .authorizeRequests() .anyRequest().authenticated() .and() .oauth2ResourceServer() .jwt() .jwkSetUri("https://the.issuer.location/.well-known/jwks.json"); } }
Using jwkSetUri()
takes precedence over any configuration property.
More powerful than jwkSetUri()
is decoder()
, which will completely replace any Boot auto configuration of JwtDecoder
:
@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 validation, mapping, or request timeouts, is necessary.
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 prefix "SCOPE_".
This means that to protect an endpoint or method with a scope derived from a JWT, the corresponding expressions should include this prefix:
@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:
@PreAuthorize("hasAuthority('SCOPE_messages')") public List<Message> getMessages(...) {}
However, there are a number of circumstances where this default is insufficient.
For example, some authorization server’s 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()
:
@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:
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>
:
static class CustomAuthenticationConverter implements Converter<Jwt, AbstractAuthenticationToken> { public AbstractAuthenticationToken convert(Jwt jwt) { return new CustomAuthenticationToken(jwt); } }
Using 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.
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:
@Bean JwtDecoder jwtDecoder() { NimbusJwtDecoderJwkSupport jwtDecoder = (NimbusJwtDecoderJwkSupport) JwtDecoders.withOidcIssuerLocation(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. |
Adding a check for the aud
claim is simple with the OAuth2TokenValidator
API:
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:
@Bean JwtDecoder jwtDecoder() { NimbusJwtDecoderJwkSupport jwtDecoder = (NimbusJwtDecoderJwkSupport) JwtDecoders.withOidcIssuerLocation(issuerUri); OAuth2TokenValidator<Jwt> audienceValidator = new AudienceValidator(); OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuerUri); OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator); jwtDecoder.setJwtValidator(withAudience); return jwtDecoder; }
Spring Security uses the 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
.
By default, MappedJwtClaimSetConverter
will attempt to coerce claims into the following types:
Claim | Java Type |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
An individual claim’s conversion strategy can be configured using MappedJwtClaimSetConverter.withDefaults
:
@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
.
MappedJwtClaimSetConverter
can also be used to add a custom claim, for example, to adapt to an existing system:
MappedJwtClaimSetConverter.withDefaults(Collections.singletonMap("custom", custom -> "value"));
And removing a claim is also simple, using the same API:
MappedJwtClaimSetConverter.withDefaults(Collections.singletonMap("legacyclaim", legacy -> null));
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>>
:
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:
@Bean JwtDecoder jwtDecoder() { NimbusJwtDecoderJwkSupport jwtDecoder = new NimbusJwtDecoderJwkSupport(jwkSetUri); jwtDecoder.setJwtClaimSetConverter(new UsernameSubClaimAdapter()); return jwtDecoder; }
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
:
@Bean public JwtDecoder jwtDecoder(RestTemplateBuilder builder) { RestOperations rest = builder .setConnectionTimeout(60000) .setReadTimeout(60000) .build(); NimbusJwtDecoderJwkSupport jwtDecoder = new NimbusJwtDecoderJwkSupport(jwkSetUri); jwtDecoder.setRestOperations(rest); return jwtDecoder; }
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.
We have already seen an example of configuring in-memory authentication for a single user. Below is an example to configure multiple users:
@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; }
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 jdbc-javaconfig sample provides a complete example of using JDBC based authentication.
@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")); }
You can find the updates to support LDAP based authentication. The ldap-javaconfig sample provides a complete example of using LDAP based authentication.
@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
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 |
@Bean public SpringAuthenticationProvider springAuthenticationProvider() { return new SpringAuthenticationProvider(); }
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 |
@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:
@Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); }
We can configure multiple HttpSecurity instances just as we can have multiple <http>
blocks.
The key is to extend the WebSecurityConfigurationAdapter
multiple times.
For example, the following is an example of having a different configuration for URL’s that start with /api/
.
@EnableWebSecurity public class MultiHttpSecurityConfig { @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; } @Configuration @Order(1) public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) throws Exception { http .antMatcher("/api/**") .authorizeRequests() .anyRequest().hasRole("ADMIN") .and() .httpBasic(); } } @Configuration public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin(); } } }
Configure Authentication as normal | |
Create an instance of | |
The | |
Create another instance of |
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 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.
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.
@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:
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
@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
@EnableGlobalMethodSecurity(prePostEnabled = true) public class MethodSecurityConfig { // ... }
and the equivalent Java code would be
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); }
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:
@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.
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:
@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; } }); }
You can provide your own custom DSLs in Spring Security. For example, you might have something that looks like this:
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 |
The custom DSL can then be used like this:
@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:
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.
@EnableWebSecurity public class Config extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .apply(customDsl()).disable() ...; } }