Remove Duplicated Docs
This commit is contained in:
parent
4d8d95163f
commit
562c1d939e
|
@ -177,7 +177,7 @@ The default value is true.
|
|||
[[nsa-access-denied-handler]]
|
||||
==== <access-denied-handler>
|
||||
This element allows you to set the `errorPage` property for the default `AccessDeniedHandler` used by the `ExceptionTranslationFilter`, using the <<nsa-access-denied-handler-error-page,error-page>> attribute, or to supply your own implementation using the<<nsa-access-denied-handler-ref,ref>> attribute.
|
||||
This is discussed in more detail in the section on the <<access-denied-handler,ExceptionTranslationFilter>>.
|
||||
This is discussed in more detail in the section on the <<servlet-exceptiontranslationfilter,ExceptionTranslationFilter>>.
|
||||
|
||||
|
||||
[[nsa-access-denied-handler-parents]]
|
||||
|
@ -2058,7 +2058,7 @@ It is the same as the alias element, but provides a more consistent experience w
|
|||
|
||||
[[nsa-authentication-provider]]
|
||||
==== <authentication-provider>
|
||||
Unless used with a `ref` attribute, this element is shorthand for configuring a <<core-services-dao-provider,DaoAuthenticationProvider>>.
|
||||
Unless used with a `ref` attribute, this element is shorthand for configuring a `DaoAuthenticationProvider`.
|
||||
`DaoAuthenticationProvider` loads user information from a `UserDetailsService` and compares the username/password combination with the values supplied at login.
|
||||
The `UserDetailsService` instance can be defined either by using an available namespace element (`jdbc-user-service` or by using the `user-service-ref` attribute to point to a bean defined elsewhere in the application context).
|
||||
|
||||
|
|
|
@ -1,146 +0,0 @@
|
|||
[[core-web-filters]]
|
||||
== Core Security Filters
|
||||
There are some key filters which will always be used in a web application which uses Spring Security, so we'll look at these and their supporting classes and interfaces first.
|
||||
We won't cover every feature, so be sure to look at the Javadoc for them if you want to get the complete picture.
|
||||
|
||||
|
||||
[[access-denied-handler]]
|
||||
=== AccessDeniedHandler
|
||||
What happens if a user is already authenticated and they try to access a protected resource? In normal usage, this shouldn't happen because the application workflow should be restricted to operations to which a user has access.
|
||||
For example, an HTML link to an administration page might be hidden from users who do not have an admin role.
|
||||
You can't rely on hiding links for security though, as there's always a possibility that a user will just enter the URL directly in an attempt to bypass the restrictions.
|
||||
Or they might modify a RESTful URL to change some of the argument values.
|
||||
Your application must be protected against these scenarios or it will definitely be insecure.
|
||||
You will typically use simple web layer security to apply constraints to basic URLs and use more specific method-based security on your service layer interfaces to really nail down what is permissible.
|
||||
|
||||
If an `AccessDeniedException` is thrown and a user has already been authenticated, then this means that an operation has been attempted for which they don't have enough permissions.
|
||||
In this case, `ExceptionTranslationFilter` will invoke a second strategy, the `AccessDeniedHandler`.
|
||||
By default, an `AccessDeniedHandlerImpl` is used, which just sends a 403 (Forbidden) response to the client.
|
||||
Alternatively you can configure an instance explicitly (as in the above example) and set an error page URL which it will forwards the request to footnote:[
|
||||
We use a forward so that the SecurityContextHolder still contains details of the principal, which may be useful for displaying to the user.
|
||||
In old releases of Spring Security we relied upon the servlet container to handle a 403 error message, which lacked this useful contextual information.
|
||||
].
|
||||
This can be a simple "access denied" page, such as a JSP, or it could be a more complex handler such as an MVC controller.
|
||||
And of course, you can implement the interface yourself and use your own implementation.
|
||||
|
||||
It's also possible to supply a custom `AccessDeniedHandler` when you're using the namespace to configure your application.
|
||||
See <<nsa-access-denied-handler,the namespace appendix>> for more details.
|
||||
|
||||
|
||||
[[request-caching]]
|
||||
=== SavedRequest s and the RequestCache Interface
|
||||
Another responsibility of `ExceptionTranslationFilter` responsibilities is to save the current request before invoking the `AuthenticationEntryPoint`.
|
||||
This allows the request to be restored after the user has authenticated (see previous overview of <<tech-intro-web-authentication,web authentication>>).
|
||||
A typical example would be where the user logs in with a form, and is then redirected to the original URL by the default `SavedRequestAwareAuthenticationSuccessHandler` (see <<form-login-flow-handling,below>>).
|
||||
|
||||
The `RequestCache` encapsulates the functionality required for storing and retrieving `HttpServletRequest` instances.
|
||||
By default the `HttpSessionRequestCache` is used, which stores the request in the `HttpSession`.
|
||||
The `RequestCacheFilter` has the job of actually restoring the saved request from the cache when the user is redirected to the original URL.
|
||||
|
||||
Under normal circumstances, you shouldn't need to modify any of this functionality, but the saved-request handling is a "best-effort" approach and there may be situations which the default configuration isn't able to handle.
|
||||
The use of these interfaces makes it fully pluggable from Spring Security 3.0 onwards.
|
||||
|
||||
|
||||
[[security-context-persistence-filter]]
|
||||
=== SecurityContextPersistenceFilter
|
||||
We covered the purpose of this all-important filter in the <<tech-intro-sec-context-persistence,Technical Overview>> chapter so you might want to re-read that section at this point.
|
||||
Let's first take a look at how you would configure it for use with a `FilterChainProxy`.
|
||||
A basic configuration only requires the bean itself
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<bean id="securityContextPersistenceFilter"
|
||||
class="org.springframework.security.web.context.SecurityContextPersistenceFilter"/>
|
||||
----
|
||||
|
||||
As we saw previously, this filter has two main tasks.
|
||||
It is responsible for storage of the `SecurityContext` contents between HTTP requests and for clearing the `SecurityContextHolder` when a request is completed.
|
||||
Clearing the `ThreadLocal` in which the context is stored is essential, as it might otherwise be possible for a thread to be replaced into the servlet container's thread pool, with the security context for a particular user still attached.
|
||||
This thread might then be used at a later stage, performing operations with the wrong credentials.
|
||||
|
||||
|
||||
[[security-context-repository]]
|
||||
==== SecurityContextRepository
|
||||
From Spring Security 3.0, the job of loading and storing the security context is now delegated to a separate strategy interface:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
public interface SecurityContextRepository {
|
||||
|
||||
SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder);
|
||||
|
||||
void saveContext(SecurityContext context, HttpServletRequest request,
|
||||
HttpServletResponse response);
|
||||
}
|
||||
----
|
||||
|
||||
The `HttpRequestResponseHolder` is simply a container for the incoming request and response objects, allowing the implementation to replace these with wrapper classes.
|
||||
The returned contents will be passed to the filter chain.
|
||||
|
||||
The default implementation is `HttpSessionSecurityContextRepository`, which stores the security context as an `HttpSession` attribute footnote:[In Spring Security 2.0 and earlier, this filter was called `HttpSessionContextIntegrationFilter` and performed all the work of storing the context was performed by the filter itself.
|
||||
If you were familiar with this class, then most of the configuration options which were available can now be found on `HttpSessionSecurityContextRepository`.].
|
||||
The most important configuration parameter for this implementation is the `allowSessionCreation` property, which defaults to `true`, thus allowing the class to create a session if it needs one to store the security context for an authenticated user (it won't create one unless authentication has taken place and the contents of the security context have changed).
|
||||
If you don't want a session to be created, then you can set this property to `false`:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<bean id="securityContextPersistenceFilter"
|
||||
class="org.springframework.security.web.context.SecurityContextPersistenceFilter">
|
||||
<property name='securityContextRepository'>
|
||||
<bean class='org.springframework.security.web.context.HttpSessionSecurityContextRepository'>
|
||||
<property name='allowSessionCreation' value='false' />
|
||||
</bean>
|
||||
</property>
|
||||
</bean>
|
||||
----
|
||||
|
||||
Alternatively you could provide an instance of `NullSecurityContextRepository`, a https://en.wikipedia.org/wiki/Null_Object_pattern[null object] implementation, which will prevent the security context from being stored, even if a session has already been created during the request.
|
||||
|
||||
|
||||
[[form-login-filter]]
|
||||
=== UsernamePasswordAuthenticationFilter
|
||||
We've now seen the three main filters which are always present in a Spring Security web configuration.
|
||||
These are also the three which are automatically created by the namespace `<http>` element and cannot be substituted with alternatives.
|
||||
The only thing that's missing now is an actual authentication mechanism, something that will allow a user to authenticate.
|
||||
This filter is the most commonly used authentication filter and the one that is most often customized footnote:[For historical reasons, prior to Spring Security 3.0, this filter was called `AuthenticationProcessingFilter` and the entry point was called `AuthenticationProcessingFilterEntryPoint`.
|
||||
Since the framework now supports many different forms of authentication, they have both been given more specific names in 3.0.].
|
||||
It also provides the implementation used by the `<form-login>` element from the namespace.
|
||||
There are three stages required to configure it.
|
||||
|
||||
* Configure a `LoginUrlAuthenticationEntryPoint` with the URL of the login page, just as we did above, and set it on the `ExceptionTranslationFilter`.
|
||||
* Implement the login page (using a JSP or MVC controller).
|
||||
* Configure an instance of `UsernamePasswordAuthenticationFilter` in the application context
|
||||
* Add the filter bean to your filter chain proxy (making sure you pay attention to the order).
|
||||
|
||||
The login form simply contains `username` and `password` input fields, and posts to the URL that is monitored by the filter (by default this is `/login`).
|
||||
The basic filter configuration looks something like this:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<bean id="authenticationFilter" class=
|
||||
"org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
|
||||
<property name="authenticationManager" ref="authenticationManager"/>
|
||||
</bean>
|
||||
----
|
||||
|
||||
[[form-login-flow-handling]]
|
||||
==== Application Flow on Authentication Success and Failure
|
||||
The filter calls the configured `AuthenticationManager` to process each authentication request.
|
||||
The destination following a successful authentication or an authentication failure is controlled by the `AuthenticationSuccessHandler` and `AuthenticationFailureHandler` strategy interfaces, respectively.
|
||||
The filter has properties which allow you to set these so you can customize the behaviour completely footnote:[In versions prior to 3.0, the application flow at this point had evolved to a stage was controlled by a mix of properties on this class and strategy plugins.
|
||||
The decision was made for 3.0 to refactor the code to make these two strategies entirely responsible.].
|
||||
Some standard implementations are supplied such as `SimpleUrlAuthenticationSuccessHandler`, `SavedRequestAwareAuthenticationSuccessHandler`, `SimpleUrlAuthenticationFailureHandler`, `ExceptionMappingAuthenticationFailureHandler` and `DelegatingAuthenticationFailureHandler`.
|
||||
Have a look at the Javadoc for these classes and also for `AbstractAuthenticationProcessingFilter` to get an overview of how they work and the supported features.
|
||||
|
||||
If authentication is successful, the resulting `Authentication` object will be placed into the `SecurityContextHolder`.
|
||||
The configured `AuthenticationSuccessHandler` will then be called to either redirect or forward the user to the appropriate destination.
|
||||
By default a `SavedRequestAwareAuthenticationSuccessHandler` is used, which means that the user will be redirected to the original destination they requested before they were asked to login.
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
The `ExceptionTranslationFilter` caches the original request a user makes.
|
||||
When the user authenticates, the request handler makes use of this cached request to obtain the original URL and redirect to it.
|
||||
The original request is then rebuilt and used as an alternative.
|
||||
====
|
||||
|
||||
If authentication fails, the configured `AuthenticationFailureHandler` will be invoked.
|
|
@ -1,116 +0,0 @@
|
|||
[[core-services]]
|
||||
== Core Services
|
||||
Now that we have a high-level overview of the Spring Security architecture and its core classes, let's take a closer look at one or two of the core interfaces and their implementations, in particular the `AuthenticationManager`, `UserDetailsService` and the `AccessDecisionManager`.
|
||||
These crop up regularly throughout the remainder of this document so it's important you know how they are configured and how they operate.
|
||||
|
||||
[[core-services-dao-provider]]
|
||||
=== DaoAuthenticationProvider
|
||||
The simplest `AuthenticationProvider` implemented by Spring Security is `DaoAuthenticationProvider`, which is also one of the earliest supported by the framework.
|
||||
It leverages a `UserDetailsService` (as a DAO) in order to lookup the username, password and `GrantedAuthority` s.
|
||||
It authenticates the user simply by comparing the password submitted in a `UsernamePasswordAuthenticationToken` against the one loaded by the `UserDetailsService`.
|
||||
Configuring the provider is quite simple:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
|
||||
<bean id="daoAuthenticationProvider"
|
||||
class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
|
||||
<property name="userDetailsService" ref="inMemoryDaoImpl"/>
|
||||
<property name="passwordEncoder" ref="passwordEncoder"/>
|
||||
</bean>
|
||||
----
|
||||
|
||||
The `PasswordEncoder` is optional.
|
||||
A `PasswordEncoder` provides encoding and matching of encoded passwords presented in the `UserDetails` object that is returned from the configured `UserDetailsService`.
|
||||
This is discussed in more detail in <<authentication-password-storage>>.
|
||||
|
||||
|
||||
=== UserDetailsService Implementations
|
||||
As mentioned in the earlier in this reference guide, most authentication providers take advantage of the `UserDetails` and `UserDetailsService` interfaces.
|
||||
Recall that the contract for `UserDetailsService` is a single method:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
|
||||
----
|
||||
|
||||
The returned `UserDetails` is an interface that provides getters that guarantee non-null provision of authentication information such as the username, password, granted authorities and whether the user account is enabled or disabled.
|
||||
Most authentication providers will use a `UserDetailsService`, even if the username and password are not actually used as part of the authentication decision.
|
||||
They may use the returned `UserDetails` object just for its `GrantedAuthority` information, because some other system (like LDAP or X.509 or CAS etc) has undertaken the responsibility of actually validating the credentials.
|
||||
|
||||
Given `UserDetailsService` is so simple to implement, it should be easy for users to retrieve authentication information using a persistence strategy of their choice.
|
||||
Having said that, Spring Security does include a couple of useful base implementations, which we'll look at below.
|
||||
|
||||
|
||||
[[core-services-in-memory-service]]
|
||||
==== In-Memory Authentication
|
||||
Is easy to use create a custom `UserDetailsService` implementation that extracts information from a persistence engine of choice, but many applications do not require such complexity.
|
||||
This is particularly true if you're building a prototype application or just starting integrating Spring Security, when you don't really want to spend time configuring databases or writing `UserDetailsService` implementations.
|
||||
For this sort of situation, a simple option is to use the `user-service` element from the security <<ns-minimal,namespace>>:
|
||||
|
||||
[source,xml,attrs="-attributes"]
|
||||
----
|
||||
<user-service id="userDetailsService">
|
||||
<!-- Password is prefixed with {noop} to indicate to DelegatingPasswordEncoder that
|
||||
NoOpPasswordEncoder should be used. This is not safe for production, but makes reading
|
||||
in samples easier. Normally passwords should be hashed using BCrypt -->
|
||||
<user name="jimi" password="{noop}jimispassword" authorities="ROLE_USER, ROLE_ADMIN" />
|
||||
<user name="bob" password="{noop}bobspassword" authorities="ROLE_USER" />
|
||||
</user-service>
|
||||
----
|
||||
|
||||
|
||||
This also supports the use of an external properties file:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<user-service id="userDetailsService" properties="users.properties"/>
|
||||
----
|
||||
|
||||
The properties file should contain entries in the form
|
||||
|
||||
[source,txt]
|
||||
----
|
||||
username=password,grantedAuthority[,grantedAuthority][,enabled|disabled]
|
||||
----
|
||||
|
||||
For example
|
||||
|
||||
[source,txt]
|
||||
----
|
||||
jimi=jimispassword,ROLE_USER,ROLE_ADMIN,enabled
|
||||
bob=bobspassword,ROLE_USER,enabled
|
||||
----
|
||||
|
||||
[[core-services-jdbc-user-service]]
|
||||
==== JdbcDaoImpl
|
||||
Spring Security also includes a `UserDetailsService` that can obtain authentication information from a JDBC data source.
|
||||
Internally Spring JDBC is used, so it avoids the complexity of a fully-featured object relational mapper (ORM) just to store user details.
|
||||
If your application does use an ORM tool, you might prefer to write a custom `UserDetailsService` to reuse the mapping files you've probably already created.
|
||||
Returning to `JdbcDaoImpl`, an example configuration is shown below:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
|
||||
<property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
|
||||
<property name="url" value="jdbc:hsqldb:hsql://localhost:9001"/>
|
||||
<property name="username" value="sa"/>
|
||||
<property name="password" value=""/>
|
||||
</bean>
|
||||
|
||||
<bean id="userDetailsService"
|
||||
class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl">
|
||||
<property name="dataSource" ref="dataSource"/>
|
||||
</bean>
|
||||
----
|
||||
|
||||
You can use different relational database management systems by modifying the `DriverManagerDataSource` shown above.
|
||||
You can also use a global data source obtained from JNDI, as with any other Spring configuration.
|
||||
|
||||
===== Authority Groups
|
||||
By default, `JdbcDaoImpl` loads the authorities for a single user with the assumption that the authorities are mapped directly to users (see the <<appendix-schema,database schema appendix>>).
|
||||
An alternative approach is to partition the authorities into groups and assign groups to the user.
|
||||
Some people prefer this approach as a means of administering user rights.
|
||||
See the `JdbcDaoImpl` Javadoc for more information on how to enable the use of group authorities.
|
||||
The group schema is also included in the appendix.
|
||||
|
|
@ -18,9 +18,3 @@ include::security-filter-chain.adoc[leveloffset=+1]
|
|||
include::security-filters.adoc[leveloffset=+1]
|
||||
|
||||
include::exception-translation-filter.adoc[leveloffset=+1]
|
||||
|
||||
include::technical-overview.adoc[]
|
||||
|
||||
include::core-filters.adoc[]
|
||||
|
||||
include::core-services.adoc[]
|
||||
|
|
|
@ -1,344 +0,0 @@
|
|||
[[technical-overview]]
|
||||
== Technical Overview
|
||||
|
||||
|
||||
[[core-components]]
|
||||
=== Core Components
|
||||
As of Spring Security 3.0, the contents of the `spring-security-core` jar were stripped down to the bare minimum.
|
||||
It no longer contains any code related to web-application security, LDAP or namespace configuration.
|
||||
We'll take a look here at some of the Java types that you'll find in the core module.
|
||||
They represent the building blocks of the framework, so if you ever need to go beyond a simple namespace configuration then it's important that you understand what they are, even if you don't actually need to interact with them directly.
|
||||
|
||||
|
||||
[[tech-userdetailsservice]]
|
||||
==== The UserDetailsService
|
||||
Another item to note from the above code fragment is that you can obtain a principal from the `Authentication` object.
|
||||
The principal is just an `Object`.
|
||||
Most of the time this can be cast into a `UserDetails` object.
|
||||
`UserDetails` is a core interface in Spring Security.
|
||||
It represents a principal, but in an extensible and application-specific way.
|
||||
Think of `UserDetails` as the adapter between your own user database and what Spring Security needs inside the `SecurityContextHolder`.
|
||||
Being a representation of something from your own user database, quite often you will cast the `UserDetails` to the original object that your application provided, so you can call business-specific methods (like `getEmail()`, `getEmployeeNumber()` and so on).
|
||||
|
||||
By now you're probably wondering, so when do I provide a `UserDetails` object? How do I do that? I thought you said this thing was declarative and I didn't need to write any Java code - what gives? The short answer is that there is a special interface called `UserDetailsService`.
|
||||
The only method on this interface accepts a `String`-based username argument and returns a `UserDetails`:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
|
||||
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
|
||||
----
|
||||
|
||||
This is the most common approach to loading information for a user within Spring Security and you will see it used throughout the framework whenever information on a user is required.
|
||||
|
||||
On successful authentication, `UserDetails` is used to build the `Authentication` object that is stored in the `SecurityContextHolder` (more on this <<tech-intro-authentication,below>>).
|
||||
The good news is that we provide a number of `UserDetailsService` implementations, including one that uses an in-memory map (`InMemoryDaoImpl`) and another that uses JDBC (`JdbcDaoImpl`).
|
||||
Most users tend to write their own, though, with their implementations often simply sitting on top of an existing Data Access Object (DAO) that represents their employees, customers, or other users of the application.
|
||||
Remember the advantage that whatever your `UserDetailsService` returns can always be obtained from the `SecurityContextHolder` using the above code fragment.
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
|
||||
There is often some confusion about `UserDetailsService`.
|
||||
It is purely a DAO for user data and performs no other function other than to supply that data to other components within the framework.
|
||||
In particular, it __does not__ authenticate the user, which is done by the `AuthenticationManager`.
|
||||
In many cases it makes more sense to implement `AuthenticationProvider` directly if you require a custom authentication process.
|
||||
|
||||
====
|
||||
|
||||
|
||||
==== Summary
|
||||
Just to recap, the major building blocks of Spring Security that we've seen so far are:
|
||||
|
||||
|
||||
* `SecurityContextHolder`, to provide access to the `SecurityContext`.
|
||||
|
||||
* `SecurityContext`, to hold the `Authentication` and possibly request-specific security information.
|
||||
|
||||
* `Authentication`, to represent the principal in a Spring Security-specific manner.
|
||||
|
||||
* `GrantedAuthority`, to reflect the application-wide permissions granted to a principal.
|
||||
|
||||
* `UserDetails`, to provide the necessary information to build an Authentication object from your application's DAOs or other source of security data.
|
||||
|
||||
* `UserDetailsService`, to create a `UserDetails` when passed in a `String`-based username (or certificate ID or the like).
|
||||
|
||||
|
||||
|
||||
Now that you've gained an understanding of these repeatedly-used components, let's take a closer look at the process of authentication.
|
||||
|
||||
|
||||
[[tech-intro-authentication]]
|
||||
=== Authentication
|
||||
Spring Security can participate in many different authentication environments.
|
||||
While we recommend people use Spring Security for authentication and not integrate with existing Container Managed Authentication, it is nevertheless supported - as is integrating with your own proprietary authentication system.
|
||||
|
||||
|
||||
==== What is authentication in Spring Security?
|
||||
Let's consider a standard authentication scenario that everyone is familiar with.
|
||||
|
||||
. A user is prompted to log in with a username and password.
|
||||
. The system (successfully) verifies that the password is correct for the username.
|
||||
. The context information for that user is obtained (their list of roles and so on).
|
||||
. A security context is established for the user
|
||||
. The user proceeds, potentially to perform some operation which is potentially protected by an access control mechanism which checks the required permissions for the operation against the current security context information.
|
||||
|
||||
|
||||
The first four items constitute the authentication process so we'll take a look at how these take place within Spring Security.
|
||||
|
||||
. The username and password are obtained and combined into an instance of `UsernamePasswordAuthenticationToken` (an instance of the `Authentication` interface, which we saw earlier).
|
||||
. The token is passed to an instance of `AuthenticationManager` for validation.
|
||||
. The `AuthenticationManager` returns a fully populated `Authentication` instance on successful authentication.
|
||||
. The security context is established by calling `SecurityContextHolder.getContext().setAuthentication(...)`, passing in the returned authentication object.
|
||||
|
||||
From that point on, the user is considered to be authenticated.
|
||||
Let's look at some code as an example.
|
||||
|
||||
[source,java]
|
||||
----
|
||||
import org.springframework.security.authentication.*;
|
||||
import org.springframework.security.core.*;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
public class AuthenticationExample {
|
||||
private static AuthenticationManager am = new SampleAuthenticationManager();
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
|
||||
|
||||
while(true) {
|
||||
System.out.println("Please enter your username:");
|
||||
String name = in.readLine();
|
||||
System.out.println("Please enter your password:");
|
||||
String password = in.readLine();
|
||||
try {
|
||||
Authentication request = new UsernamePasswordAuthenticationToken(name, password);
|
||||
Authentication result = am.authenticate(request);
|
||||
SecurityContextHolder.getContext().setAuthentication(result);
|
||||
break;
|
||||
} catch(AuthenticationException e) {
|
||||
System.out.println("Authentication failed: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
System.out.println("Successfully authenticated. Security context contains: " +
|
||||
SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
}
|
||||
|
||||
class SampleAuthenticationManager implements AuthenticationManager {
|
||||
static final List<GrantedAuthority> AUTHORITIES = new ArrayList<GrantedAuthority>();
|
||||
|
||||
static {
|
||||
AUTHORITIES.add(new SimpleGrantedAuthority("ROLE_USER"));
|
||||
}
|
||||
|
||||
public Authentication authenticate(Authentication auth) throws AuthenticationException {
|
||||
if (auth.getName().equals(auth.getCredentials())) {
|
||||
return new UsernamePasswordAuthenticationToken(auth.getName(),
|
||||
auth.getCredentials(), AUTHORITIES);
|
||||
}
|
||||
throw new BadCredentialsException("Bad Credentials");
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
Here we have written a little program that asks the user to enter a username and password and performs the above sequence.
|
||||
The `AuthenticationManager` which we've implemented here will authenticate any user whose username and password are the same.
|
||||
It assigns a single role to every user.
|
||||
The output from the above will be something like:
|
||||
|
||||
[source,txt]
|
||||
----
|
||||
|
||||
Please enter your username:
|
||||
bob
|
||||
Please enter your password:
|
||||
password
|
||||
Authentication failed: Bad Credentials
|
||||
Please enter your username:
|
||||
bob
|
||||
Please enter your password:
|
||||
bob
|
||||
Successfully authenticated. Security context contains: \
|
||||
org.springframework.security.authentication.UsernamePasswordAuthenticationToken@441d0230: \
|
||||
Principal: bob; Password: [PROTECTED]; \
|
||||
Authenticated: true; Details: null; \
|
||||
Granted Authorities: ROLE_USER
|
||||
|
||||
----
|
||||
|
||||
|
||||
|
||||
Note that you don't normally need to write any code like this.
|
||||
The process will normally occur internally, in a web authentication filter for example.
|
||||
We've just included the code here to show that the question of what actually constitutes authentication in Spring Security has quite a simple answer.
|
||||
A user is authenticated when the `SecurityContextHolder` contains a fully populated `Authentication` object.
|
||||
|
||||
|
||||
==== Setting the SecurityContextHolder Contents Directly
|
||||
In fact, Spring Security doesn't mind how you put the `Authentication` object inside the `SecurityContextHolder`.
|
||||
The only critical requirement is that the `SecurityContextHolder` contains an `Authentication` which represents a principal before the `AbstractSecurityInterceptor` (which we'll see more about later) needs to authorize a user operation.
|
||||
|
||||
You can (and many users do) write their own filters or MVC controllers to provide interoperability with authentication systems that are not based on Spring Security.
|
||||
For example, you might be using Container-Managed Authentication which makes the current user available from a ThreadLocal or JNDI location.
|
||||
Or you might work for a company that has a legacy proprietary authentication system, which is a corporate "standard" over which you have little control.
|
||||
In situations like this it's quite easy to get Spring Security to work, and still provide authorization capabilities.
|
||||
All you need to do is write a filter (or equivalent) that reads the third-party user information from a location, build a Spring Security-specific `Authentication` object, and put it into the `SecurityContextHolder`.
|
||||
In this case you also need to think about things which are normally taken care of automatically by the built-in authentication infrastructure.
|
||||
For example, you might need to pre-emptively create an HTTP session to <<tech-intro-sec-context-persistence,cache the context between requests>>, before you write the response to the client footnote:[It isn't possible to create a session once the response has been committed.].
|
||||
|
||||
If you're wondering how the `AuthenticationManager` is implemented in a real world example, we'll look at that in the <<servlet-authentication-authenticationmanager,`AuthenticationManager`>>.
|
||||
|
||||
|
||||
[[tech-intro-web-authentication]]
|
||||
=== Authentication in a Web Application
|
||||
Now let's explore the situation where you are using Spring Security in a web application (without `web.xml` security enabled).
|
||||
How is a user authenticated and the security context established?
|
||||
|
||||
Consider a typical web application's authentication process:
|
||||
|
||||
|
||||
. You visit the home page, and click on a link.
|
||||
. A request goes to the server, and the server decides that you've asked for a protected resource.
|
||||
. As you're not presently authenticated, the server sends back a response indicating that you must authenticate.
|
||||
The response will either be an HTTP response code, or a redirect to a particular web page.
|
||||
. Depending on the authentication mechanism, your browser will either redirect to the specific web page so that you can fill out the form, or the browser will somehow retrieve your identity (via a BASIC authentication dialogue box, a cookie, a X.509 certificate etc.).
|
||||
. The browser will send back a response to the server.
|
||||
This will either be an HTTP POST containing the contents of the form that you filled out, or an HTTP header containing your authentication details.
|
||||
. Next the server will decide whether or not the presented credentials are valid.
|
||||
If they're valid, the next step will happen.
|
||||
If they're invalid, usually your browser will be asked to try again (so you return to step two above).
|
||||
. The original request that you made to cause the authentication process will be retried.
|
||||
Hopefully you've authenticated with sufficient granted authorities to access the protected resource.
|
||||
If you have sufficient access, the request will be successful.
|
||||
Otherwise, you'll receive back an HTTP error code 403, which means "forbidden".
|
||||
|
||||
Spring Security has distinct classes responsible for most of the steps described above.
|
||||
The main participants (in the order that they are used) are the `ExceptionTranslationFilter`, an `AuthenticationEntryPoint` and an "authentication mechanism", which is responsible for calling the `AuthenticationManager` which we saw in the previous section.
|
||||
|
||||
[[tech-intro-auth-entry-point]]
|
||||
==== AuthenticationEntryPoint
|
||||
The `AuthenticationEntryPoint` is responsible for step three in the above list.
|
||||
As you can imagine, each web application will have a default authentication strategy (well, this can be configured like nearly everything else in Spring Security, but let's keep it simple for now).
|
||||
Each major authentication system will have its own `AuthenticationEntryPoint` implementation, which typically performs one of the actions described in step 3.
|
||||
|
||||
|
||||
==== Authentication Mechanism
|
||||
Once your browser submits your authentication credentials (either as an HTTP form post or HTTP header) there needs to be something on the server that "collects" these authentication details.
|
||||
By now we're at step six in the above list.
|
||||
In Spring Security we have a special name for the function of collecting authentication details from a user agent (usually a web browser), referring to it as the "authentication mechanism".
|
||||
Examples are form-base login and Basic authentication.
|
||||
Once the authentication details have been collected from the user agent, an `Authentication` "request" object is built and then presented to the `AuthenticationManager`.
|
||||
|
||||
After the authentication mechanism receives back the fully-populated `Authentication` object, it will deem the request valid, put the `Authentication` into the `SecurityContextHolder`, and cause the original request to be retried (step seven above).
|
||||
If, on the other hand, the `AuthenticationManager` rejected the request, the authentication mechanism will ask the user agent to retry (step two above).
|
||||
|
||||
|
||||
[[tech-intro-sec-context-persistence]]
|
||||
==== Storing the SecurityContext between requests
|
||||
Depending on the type of application, there may need to be a strategy in place to store the security context between user operations.
|
||||
In a typical web application, a user logs in once and is subsequently identified by their session Id.
|
||||
The server caches the principal information for the duration session.
|
||||
In Spring Security, the responsibility for storing the `SecurityContext` between requests falls to the `SecurityContextPersistenceFilter`, which by default stores the context as an `HttpSession` attribute between HTTP requests.
|
||||
It restores the context to the `SecurityContextHolder` for each request and, crucially, clears the `SecurityContextHolder` when the request completes.
|
||||
You shouldn't interact directly with the `HttpSession` for security purposes.
|
||||
There is simply no justification for doing so - always use the `SecurityContextHolder` instead.
|
||||
|
||||
Many other types of application (for example, a stateless RESTful web service) do not use HTTP sessions and will re-authenticate on every request.
|
||||
However, it is still important that the `SecurityContextPersistenceFilter` is included in the chain to make sure that the `SecurityContextHolder` is cleared after each request.
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
In an application which receives concurrent requests in a single session, the same `SecurityContext` instance will be shared between threads.
|
||||
Even though a `ThreadLocal` is being used, it is the same instance that is retrieved from the `HttpSession` for each thread.
|
||||
This has implications if you wish to temporarily change the context under which a thread is running.
|
||||
If you just use `SecurityContextHolder.getContext()`, and call `setAuthentication(anAuthentication)` on the returned context object, then the `Authentication` object will change in __all__ concurrent threads which share the same `SecurityContext` instance.
|
||||
You can customize the behaviour of `SecurityContextPersistenceFilter` to create a completely new `SecurityContext` for each request, preventing changes in one thread from affecting another.
|
||||
Alternatively you can create a new instance just at the point where you temporarily change the context.
|
||||
The method `SecurityContextHolder.createEmptyContext()` always returns a new context instance.
|
||||
====
|
||||
|
||||
[[tech-intro-access-control]]
|
||||
=== Access-Control (Authorization) in Spring Security
|
||||
The main interface responsible for making access-control decisions in Spring Security is the `AccessDecisionManager`.
|
||||
It has a `decide` method which takes an `Authentication` object representing the principal requesting access, a "secure object" (see below) and a list of security metadata attributes which apply for the object (such as a list of roles which are required for access to be granted).
|
||||
|
||||
|
||||
==== Security and AOP Advice
|
||||
If you're familiar with AOP, you'd be aware there are different types of advice available: before, after, throws and around.
|
||||
An around advice is very useful, because an advisor can elect whether or not to proceed with a method invocation, whether or not to modify the response, and whether or not to throw an exception.
|
||||
Spring Security provides an around advice for method invocations as well as web requests.
|
||||
We achieve an around advice for method invocations using Spring's standard AOP support and we achieve an around advice for web requests using a standard Filter.
|
||||
|
||||
For those not familiar with AOP, the key point to understand is that Spring Security can help you protect method invocations as well as web requests.
|
||||
Most people are interested in securing method invocations on their services layer.
|
||||
This is because the services layer is where most business logic resides in current-generation Java EE applications.
|
||||
If you just need to secure method invocations in the services layer, Spring's standard AOP will be adequate.
|
||||
If you need to secure domain objects directly, you will likely find that AspectJ is worth considering.
|
||||
|
||||
You can elect to perform method authorization using AspectJ or Spring AOP, or you can elect to perform web request authorization using filters.
|
||||
You can use zero, one, two or three of these approaches together.
|
||||
The mainstream usage pattern is to perform some web request authorization, coupled with some Spring AOP method invocation authorization on the services layer.
|
||||
|
||||
|
||||
[[secure-objects]]
|
||||
==== Secure Objects and the AbstractSecurityInterceptor
|
||||
So what __is__ a "secure object" anyway? Spring Security uses the term to refer to any object that can have security (such as an authorization decision) applied to it.
|
||||
The most common examples are method invocations and web requests.
|
||||
|
||||
Each supported secure object type has its own interceptor class, which is a subclass of `AbstractSecurityInterceptor`.
|
||||
Importantly, by the time the `AbstractSecurityInterceptor` is called, the `SecurityContextHolder` will contain a valid `Authentication` if the principal has been authenticated.
|
||||
|
||||
`AbstractSecurityInterceptor` provides a consistent workflow for handling secure object requests, typically:
|
||||
|
||||
. Look up the "configuration attributes" associated with the present request
|
||||
. Submitting the secure object, current `Authentication` and configuration attributes to the `AccessDecisionManager` for an authorization decision
|
||||
. Optionally change the `Authentication` under which the invocation takes place
|
||||
. Allow the secure object invocation to proceed (assuming access was granted)
|
||||
. Call the `AfterInvocationManager` if configured, once the invocation has returned.
|
||||
If the invocation raised an exception, the `AfterInvocationManager` will not be invoked.
|
||||
|
||||
[[tech-intro-config-attributes]]
|
||||
===== What are Configuration Attributes?
|
||||
A "configuration attribute" can be thought of as a String that has special meaning to the classes used by `AbstractSecurityInterceptor`.
|
||||
They are represented by the interface `ConfigAttribute` within the framework.
|
||||
They may be simple role names or have more complex meaning, depending on the how sophisticated the `AccessDecisionManager` implementation is.
|
||||
The `AbstractSecurityInterceptor` is configured with a `SecurityMetadataSource` which it uses to look up the attributes for a secure object.
|
||||
Usually this configuration will be hidden from the user.
|
||||
Configuration attributes will be entered as annotations on secured methods or as access attributes on secured URLs.
|
||||
For example, when we saw something like `<intercept-url pattern='/secure/**' access='ROLE_A,ROLE_B'/>` in the namespace introduction, this is saying that the configuration attributes `ROLE_A` and `ROLE_B` apply to web requests matching the given pattern.
|
||||
In practice, with the default `AccessDecisionManager` configuration, this means that anyone who has a `GrantedAuthority` matching either of these two attributes will be allowed access.
|
||||
Strictly speaking though, they are just attributes and the interpretation is dependent on the `AccessDecisionManager` implementation.
|
||||
The use of the prefix `ROLE_` is a marker to indicate that these attributes are roles and should be consumed by Spring Security's `RoleVoter`.
|
||||
This is only relevant when a voter-based `AccessDecisionManager` is in use.
|
||||
We'll see how the `AccessDecisionManager` is implemented in the <<authz-arch,authorization chapter>>.
|
||||
|
||||
|
||||
===== RunAsManager
|
||||
Assuming `AccessDecisionManager` decides to allow the request, the `AbstractSecurityInterceptor` will normally just proceed with the request.
|
||||
Having said that, on rare occasions users may want to replace the `Authentication` inside the `SecurityContext` with a different `Authentication`, which is handled by the `AccessDecisionManager` calling a `RunAsManager`.
|
||||
This might be useful in reasonably unusual situations, such as if a services layer method needs to call a remote system and present a different identity.
|
||||
Because Spring Security automatically propagates security identity from one server to another (assuming you're using a properly-configured RMI or HttpInvoker remoting protocol client), this may be useful.
|
||||
|
||||
|
||||
===== AfterInvocationManager
|
||||
Following the secure object invocation proceeding and then returning - which may mean a method invocation completing or a filter chain proceeding - the `AbstractSecurityInterceptor` gets one final chance to handle the invocation.
|
||||
At this stage the `AbstractSecurityInterceptor` is interested in possibly modifying the return object.
|
||||
We might want this to happen because an authorization decision couldn't be made "on the way in" to a secure object invocation.
|
||||
Being highly pluggable, `AbstractSecurityInterceptor` will pass control to an `AfterInvocationManager` to actually modify the object if needed.
|
||||
This class can even entirely replace the object, or throw an exception, or not change it in any way as it chooses.
|
||||
The after-invocation checks will only be executed if the invocation is successful.
|
||||
If an exception occurs, the additional checks will be skipped.
|
||||
|
||||
`AbstractSecurityInterceptor` and its related objects are shown in <<abstract-security-interceptor>>
|
||||
|
||||
[[abstract-security-interceptor]]
|
||||
.Security interceptors and the "secure object" model
|
||||
image::images/security-interception.png[Abstract Security Interceptor]
|
||||
|
||||
===== Extending the Secure Object Model
|
||||
Only developers contemplating an entirely new way of intercepting and authorizing requests would need to use secure objects directly.
|
||||
For example, it would be possible to build a new secure object to secure calls to a messaging system.
|
||||
Anything that requires security and also provides a way of intercepting a call (like the AOP around advice semantics) is capable of being made into a secure object.
|
||||
Having said that, most Spring applications will simply use the three currently supported secure object types (AOP Alliance `MethodInvocation`, AspectJ `JoinPoint` and web request `FilterInvocation`) with complete transparency.
|
|
@ -81,7 +81,7 @@ These names are largely self-explanatory, except `NamedCasProxyDecider` which al
|
|||
* `CasAuthenticationProvider` will next request a `AuthenticationUserDetailsService` to load the `GrantedAuthority` objects that apply to the user contained in the `Assertion`.
|
||||
* If there were no problems, `CasAuthenticationProvider` constructs a `CasAuthenticationToken` including the details contained in the `TicketResponse` and the ``GrantedAuthority``s.
|
||||
* Control then returns to `CasAuthenticationFilter`, which places the created `CasAuthenticationToken` in the security context.
|
||||
* The user's browser is redirected to the original page that caused the `AuthenticationException` (or a <<form-login-flow-handling,custom destination>> depending on the configuration).
|
||||
* The user's browser is redirected to the original page that caused the `AuthenticationException` (or a custom destination depending on the configuration).
|
||||
|
||||
It's good that you're still here!
|
||||
Let's now look at how this is configured
|
||||
|
|
|
@ -49,9 +49,8 @@ OpenIDAuthenticationToken token =
|
|||
List<OpenIDAttribute> attributes = token.getAttributes();
|
||||
----
|
||||
|
||||
We can obtain the `OpenIDAuthenticationToken` from the <<servlet-authentication-securitycontextholder>>.
|
||||
The `OpenIDAttribute` contains the attribute type and the retrieved value (or values in the case of multi-valued attributes).
|
||||
We'll see more about how the `SecurityContextHolder` class is used when we look at core Spring Security components in the <<core-components,technical overview>> chapter.
|
||||
Multiple attribute exchange configurations are also be supported, if you wish to use multiple identity providers.
|
||||
You can supply multiple `attribute-exchange` elements, using an `identifier-matcher` attribute on each.
|
||||
This contains a regular expression which will be matched against the OpenID identifier supplied by the user.
|
||||
See the OpenID sample application in the codebase for an example configuration, providing different attribute lists for the Google, Yahoo and MyOpenID providers.
|
||||
|
|
|
@ -74,8 +74,7 @@ The `PreAuthenticatedGrantedAuthoritiesUserDetailsService` class does this.
|
|||
Alternatively, it may delegate to a standard `UserDetailsService` via the `UserDetailsByNameServiceWrapper` implementation.
|
||||
|
||||
==== Http403ForbiddenEntryPoint
|
||||
The `AuthenticationEntryPoint` was discussed in the <<tech-intro-auth-entry-point,technical overview>> chapter.
|
||||
Normally it is responsible for kick-starting the authentication process for an unauthenticated user (when they try to access a protected resource), but in the pre-authenticated case this doesn't apply.
|
||||
The <<servlet-authentication-authenticationentrypoint,`AuthenticationEntryPoint`>> is responsible for kick-starting the authentication process for an unauthenticated user (when they try to access a protected resource), but in the pre-authenticated case this doesn't apply.
|
||||
You would only configure the `ExceptionTranslationFilter` with an instance of this class if you aren't using pre-authentication in combination with other authentication mechanisms.
|
||||
It will be called if the user is rejected by the `AbstractPreAuthenticatedProcessingFilter` resulting in a null authentication.
|
||||
It always returns a `403`-forbidden response code if called.
|
||||
|
|
|
@ -35,7 +35,7 @@ All `AuthenticationProvider` s included with the security architecture use `Simp
|
|||
|
||||
[[authz-pre-invocation]]
|
||||
== Pre-Invocation Handling
|
||||
As we've also seen in the <<secure-objects,Technical Overview>> chapter, Spring Security provides interceptors which control access to secure objects such as method invocations or web requests.
|
||||
Spring Security provides interceptors which control access to secure objects such as method invocations or web requests.
|
||||
A pre-invocation decision on whether the invocation is allowed to proceed is made by the `AccessDecisionManager`.
|
||||
|
||||
|
||||
|
|
|
@ -198,7 +198,7 @@ It's worth cross-checking this if you want to start understanding what the impor
|
|||
|
||||
The configuration above defines two users, their passwords and their roles within the application (which will be used for access control).
|
||||
It is also possible to load user information from a standard properties file using the `properties` attribute on `user-service`.
|
||||
See the section on <<core-services-in-memory-service,in-memory authentication>> for more details on the file format.
|
||||
See the section on <<servlet-authentication-inmemory,in-memory authentication>> for more details on the file format.
|
||||
Using the `<authentication-provider>` element means that the user information will be used by the authentication manager to process authentication requests.
|
||||
You can have multiple `<authentication-provider>` elements to define different authentication sources and each will be consulted in turn.
|
||||
|
||||
|
@ -224,7 +224,6 @@ This is useful if your application always requires that the user starts at a "ho
|
|||
|
||||
For even more control over the destination, you can use the `authentication-success-handler-ref` attribute as an alternative to `default-target-url`.
|
||||
The referenced bean should be an instance of `AuthenticationSuccessHandler`.
|
||||
You'll find more on this in the <<form-login-flow-handling,Core Filters>> chapter and also in the namespace appendix, as well as information on how to customize the flow when authentication fails.
|
||||
|
||||
[[ns-web-advanced]]
|
||||
== Advanced Web Features
|
||||
|
|
Loading…
Reference in New Issue