Once you are familiar with setting up and running some namespace-configuration based applications, you may wish to develop more of an understanding of how the framework actually works behind the namespace facade. Like most software, Spring Security has certain central interfaces, classes and conceptual abstractions that are commonly used throughout the framework. In this part of the reference guide we will look at some of these and see how they work together to support authentication and access-control within Spring Security.
9. Technical Overview(技术概述)
9.1 Runtime Environment
Spring Security 3.0 requires a Java 5.0 Runtime Environment or higher. As Spring Security aims to operate in a self-contained manner, there is no need to place any special configuration files into your Java Runtime Environment. In particular, there is no need to configure a special Java Authentication and Authorization Service (JAAS) policy file or place Spring Security into common classpath locations.
9.2 Core Components(核心组件)
In 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.
9.2.1 SecurityContextHolder, SecurityContext and Authentication Objects
The most fundamental object is SecurityContextHolder
. This is where we store details of the present security context of the application, which includes details of the principal currently using the application. By default the SecurityContextHolder
uses a ThreadLocal
to store these details, which means that the security context is always available to methods in the same thread of execution, even if the security context is not explicitly passed around as an argument to those methods. Using a ThreadLocal
in this way is quite safe if care is taken to clear the thread after the present principal’s request is processed. Of course, Spring Security takes care of this for you automatically so there is no need to worry about it.
ThreadLocal
, because of the specific way they work with threads. For example, a Swing client might want all threads in a Java Virtual Machine to use the same security context. SecurityContextHolder
can be configured with a strategy on startup to specify how you would like the context to be stored. For a standalone application you would use the SecurityContextHolder.MODE_GLOBAL
strategy. Other applications might want to have threads spawned by the secure thread also assume the same security identity. This is achieved by using SecurityContextHolder.MODE_INHERITABLETHREADLOCAL
. You can change the mode from the default SecurityContextHolder.MODE_THREADLOCAL
in two ways. The first is to set a system property, the second is to call a static method on SecurityContextHolder
. Most applications won’t need to change from the default, but if you do, take a look at the JavaDoc for SecurityContextHolder
to learn more.Obtaining information about the current user(获取有关当前用户的信息)
Inside the SecurityContextHolder
we store details of the principal currently interacting with the application. Spring Security uses an Authentication
object to represent this information. You won’t normally need to create an Authentication
object yourself, but it is fairly common for users to query the Authentication
object. You can use the following code block - from anywhere in your application - to obtain the name of the currently authenticated user, for example:
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof UserDetails) {
String username = ((UserDetails)principal).getUsername();
} else {
String username = principal.toString();
}
The object returned by the call to getContext()
is an instance of the SecurityContext
interface. This is the object that is kept in thread-local storage. As we’ll see below, most authentication mechanisms within Spring Security return an instance of UserDetails
as the principal.
9.2.2 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).
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
: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.
UserDetails
is used to build the Authentication
object that is stored in the SecurityContextHolder
(more on this 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.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.9.2.3 GrantedAuthority
Besides the principal, another important method provided by Authentication
is getAuthorities()
. This method provides an array of GrantedAuthority
objects. A GrantedAuthority
is, not surprisingly, an authority that is granted to the principal. Such authorities are usually "roles", such as ROLE_ADMINISTRATOR
or ROLE_HR_SUPERVISOR
. These roles are later on configured for web authorization, method authorization and domain object authorization. Other parts of Spring Security are capable of interpreting these authorities, and expect them to be present. GrantedAuthority
objects are usually loaded by the UserDetailsService
.
GrantedAuthority
objects are application-wide permissions. They are not specific to a given domain object. Thus, you wouldn’t likely have a GrantedAuthority
to represent a permission to Employee
object number 54, because if there are thousands of such authorities you would quickly run out of memory (or, at the very least, cause the application to take a long time to authenticate a user). Of course, Spring Security is expressly designed to handle this common requirement, but you’d instead use the project’s domain object security capabilities for this purpose.9.2.4 Summary(摘要)
Just to recap, the major building blocks of Spring Security that we’ve seen so far are:
-
SecurityContextHolder
, to provide access to theSecurityContext
. - SecurityContextHolder,提供对SecurityContext的访问。
-
SecurityContext
, to hold theAuthentication
and possibly request-specific security information. - SecurityContext,用于保存身份验证以及可能的特定于请求的安全信息。
-
Authentication
, to represent the principal in a Spring Security-specific manner. - 身份验证,以Spring Security特定的方式表示主体。
-
GrantedAuthority
, to reflect the application-wide permissions granted to a principal. - GrantedAuthority,用于反映授予主体的应用程序范围的权限。
-
UserDetails
, to provide the necessary information to build an Authentication object from your application’s DAOs or other source of security data. - UserDetails,提供从应用程序的DAO或其他安全数据源构建Authentication对象所需的信息。
-
UserDetailsService
, to create aUserDetails
when passed in aString
-based username (or certificate ID or the like). - UserDetailsService,用于在基于字符串的用户名(或证书ID等)中传递时创建UserDetails。
Now that you’ve gained an understanding of these repeatedly-used components, let’s take a closer look at the process of authentication.
9.3 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.
9.3.1 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 three 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 theAuthentication
interface, which we saw earlier).获取用户名和密码并将其组合到UsernamePasswordAuthenticationToken(Authentication接口的实例,我们之前看到)的实例中。 - The token is passed to an instance of
AuthenticationManager
for validation. 令牌传递给AuthenticationManager的实例以进行验证。 - The
AuthenticationManager
returns a fully populatedAuthentication
instance on successful authentication.AuthenticationManager 在成功验证后返回完全填充的Authentication实例。 - The security context is established by calling
SecurityContextHolder.getContext().setAuthentication(…)
, passing in the returned authentication object. 通过调用SecurityContextHolder.getContext()。setAuthentication(...)建立安全上下文,传入返回的身份验证对象。
From that point on, the user is considered to be authenticated. Let’s look at some code as an example.
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:
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.
StrictHttpFirewall
is used. This implementation rejects requests that appear to be malicious. If it is too strict for your needs, then you can customize what types of requests are rejected. However, it is important that you do so knowing that this can open your application up to attacks. For example, if you wish to leverage Spring MVC’s Matrix Variables, the following configuration could be used in XML:<b:bean id="httpFirewall"
class="org.springframework.security.web.firewall.StrictHttpFirewall"
p:allowSemicolon="true"/> <http-firewall ref="httpFirewall"/>
The same thing can be achieved with Java Configuration by exposing a StrictHttpFirewall
bean.
@Bean
public StrictHttpFirewall httpFirewall() {
StrictHttpFirewall firewall = new StrictHttpFirewall();
firewall.setAllowSemicolon(true);
return firewall;
}
9.3.2 Setting the SecurityContextHolder Contents Directly (直接设置SecurityContextHolder内容)
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.
Authentication
object, and put it into the SecurityContextHolder
. AuthenticationManager
is implemented in a real world example, we’ll look at that in the core services chapter.