Spring Security(二十七):Part II. Architecture and Implementation
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 SecurityContextHolderto 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 Authenticationobject. 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 theAuthenticationand 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 aUserDetailswhen 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 theAuthenticationinterface, which we saw earlier).获取用户名和密码并将其组合到UsernamePasswordAuthenticationToken(Authentication接口的实例,我们之前看到)的实例中。 - The token is passed to an instance of 
AuthenticationManagerfor validation. 令牌传递给AuthenticationManager的实例以进行验证。 - The 
AuthenticationManagerreturns a fully populatedAuthenticationinstance 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.Spring Security(二十七):Part II. Architecture and Implementation的更多相关文章
- Spring Security(二) —— Guides
		
摘要: 原创出处 https://www.cnkirito.moe/spring-security-2/ 「老徐」欢迎转载,保留摘要,谢谢! 2 Spring Security Guides 上一篇文 ...
 - Spring Security(十七):5.8 Method Security
		
From version 2.0 onwards Spring Security has improved support substantially for adding security to y ...
 - Spring Security(二):一、Preface(前言)
		
Spring Security is a powerful and highly customizable authentication and access-control framework. I ...
 - Spring Security(三) —— 核心配置解读
		
摘要: 原创出处 https://www.cnkirito.moe/spring-security-3/ 「老徐」欢迎转载,保留摘要,谢谢! 3 核心配置解读 上一篇文章<Spring Secu ...
 - 学习Spring Security OAuth认证(一)-授权码模式
		
一.环境 spring boot+spring security+idea+maven+mybatis 主要是spring security 二.依赖 <dependency> <g ...
 - 基于Spring Boot+Spring Security+JWT+Vue前后端分离的开源项目
		
一.前言 最近整合Spring Boot+Spring Security+JWT+Vue 完成了一套前后端分离的基础项目,这里把它开源出来分享给有需要的小伙伴们 功能很简单,单点登录,前后端动态权限配 ...
 - Spring Security(四) —— 核心过滤器源码分析
		
摘要: 原创出处 https://www.cnkirito.moe/spring-security-4/ 「老徐」欢迎转载,保留摘要,谢谢! 4 过滤器详解 前面的部分,我们关注了Spring Sec ...
 - 整合Spring Security(二十七)
		
在这一节,我们将对/hello页面进行权限控制,必须是授权用户才能访问.当没有权限的用户访问后,跳转到登录页面. 添加依赖 在pom.xml中添加如下配置,引入对Spring Security的依赖. ...
 - Spring Boot教程(二十七)整合Spring Security
		
在这一节,我们将对/hello页面进行权限控制,必须是授权用户才能访问.当没有权限的用户访问后,跳转到登录页面. 添加依赖 在pom.xml中添加如下配置,引入对Spring Security的依赖. ...
 
随机推荐
- css3制作商品展示
			
今天看到一个用css3制作的简单的展示页面所以,我自己又是初学者所以决定模仿着写一个,下面右边是一开始的,右边是鼠标放上去暂时的.这个是由下到上逐渐显示的首先直接上代码. <!DOCTYPE h ...
 - C# 添加Windows服务,定时任务。
			
源码下载地址:http://files.cnblogs.com/files/lanyubaicl/20160830Windows%E6%9C%8D%E5%8A%A1.zip 步骤 一 . 创建服务项目 ...
 - html/css更改子级继承的父级属性
			
一个精美的网页需要的样式很多,在父级上设置的字体颜色或者大小,在其子元素中不一定全部相同,这时候要更改其中某一项的样式怎么办呢. 很多新手朋友就不明白,会迷惑为什么我使用class单独命名了,重新设置 ...
 - Android 进度条按钮实现(ProgressButton)
			
有些App在点击下载按钮的时候,可以在按钮上显示进度,我们可以通过继承原生Button,重写onDraw来实现带进度条的按钮. Github:https://github.com/imcloudflo ...
 - codeforces 2A Winner (好好学习英语)
			
Winner 题目链接:http://codeforces.com/contest/2/problem/A ——每天在线,欢迎留言谈论. 题目大意: 最后结果的最高分 maxscore.在最后分数都为 ...
 - exports与module.exports的区别,export与export.defult区别
			
在JS模块化编程中,之前使用的是require.js或者sea.js.随着前端工程化工具webpack的推出,使得前端js可以使用CommonJS模块标准或者使用ES6 moduel特性. 在Comm ...
 - pycharm 中按照文档引包方式,引包错误
			
* python使用pycharm ide,如果电脑上有多个解释器的,在项目解释器配置的应该是当前使用的解释器: * 可以把当前使用的解释器目录添加到系统环境变量中,这样就不会报错了 另外,如果目录中 ...
 - SQL Server中通用数据库角色权限处理
			
SQL Server中通用数据库角色权限处理 最近和同事在做数据库权限清理的事情,主要是删除一些账号:取消一些账号的较大的权限等,例如,有一些有db_owner权限,我们取消账号的数据库角色db_ ...
 - html常见标签和属性
			
主体 body中常见属性 属性 表格 列表 表单 其他 input字段属性 form字段属性
 - 使用GDB调试gp(转载)
			
使用 gdb 调试 postgres greenplum zalax3030人评论715人阅读2012-07-11 10:07:15 错误信息的获取途径有几种 : 1. 最简单的就是看Postg ...