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 4, 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 that end in |
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 SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user").password("password").roles("USER"); } }
Note | |
---|---|
The name of the configureGlobal method is not important. However, it is important to only configure AuthenticationManagerBuilder in a class annotated with either |
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 SecurityConfig
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(SecurityConfig.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 SecurityConfig
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[] { SecurityConfig.class }; } // ... other overrides ... }
Thus far our SecurityConfig 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.
However, Java Configuration has different defaults URLs and parameters. Keep this in mind when creating custom login pages. The result is that our URLs are more RESTful. Additionally, it is not quite so obvious we are using Spring Security which helps to prevent information leaks. For example:
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 Section 16.4.3, “Include the CSRF Token” To learn more read the Chapter 16, 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 resticted 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 cleanup. As such they should
not throw exceptions. Various implementations are provided:
Please see Section 15.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.
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:
@Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user").password("password").roles("USER").and() .withUser("admin").password("password").roles("USER", "ADMIN"); }
You can find the updates to suppport 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 { auth .jdbcAuthentication() .dataSource(dataSource) .withDefaultSchema() .withUser("user").password("password").roles("USER").and() .withUser("admin").password("password").roles("USER", "ADMIN"); }
You can find the updates to suppport 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 { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) { auth .inMemoryAuthentication() .withUser("user").password("password").roles("USER").and() .withUser("admin").password("password").roles("USER", "ADMIN"); } @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 an 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 overriden, 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 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; } }); }