Spring Security FAQ

它使用灵活的配置模型,允许开发人员根据应用程序的特定需求定制安全设置。Spring Security 还提供了对各种安全机制的强大支持,例如 LDAP、JWT 和 OAuth2。

该框架集成了 Spring 生态系统,无缝地与其他 Spring 组件协作。此外,Spring Security 提供了全面的文档和示例,使开发人员能够轻松地集成和配置该框架。

使用 Spring Security 的主要优点包括:

  • 可靠性:经过广泛的测试和使用,Spring Security 提供了一个稳定的安全基础。

  • 灵活性:可定制的配置模型允许根据应用程序的需求进行全面配置。

  • 可扩展性:Spring Security 支持各种安全机制,并可以轻松集成到现有的系统中。

  • 用户友好:全面的文档和示例简化了集成和配置过程。

此常见问题解答有以下部分:

This FAQ has the following sections:

General Questions

此常见问题解答回答了以下一般性问题:

This FAQ answers the following general questions:

Can Spring Security take care of all my application security requirements?

Spring Security 为你的身份验证和授权需求提供了一个灵活的框架,但还有许多其他考虑因素在构建安全应用程序时超出其范围。Web 应用程序容易受到各种攻击,你应该熟悉这些攻击,最好在开始开发之前,以便你可以从一开始就考虑它们进行设计和编码。查看 OWASP website ,了解 Web 应用程序开发人员面临的主要问题以及你可以针对这些问题采取的对策。

Spring Security provides you with a flexible framework for your authentication and authorization requirements, but there are many other considerations for building a secure application that are outside its scope. Web applications are vulnerable to all kinds of attacks with which you should be familiar, preferably before you start development so that you can design and code with them in mind from the beginning. Check out the OWASP website for information on the major issues that face web application developers and the countermeasures you can use against them.

Why Not Use web.xml Security?

假设您正在基于 Spring 开发企业应用程序。您通常需要解决四个安全问题:身份验证、Web 请求安全、服务层安全(实现业务逻辑的方法)和域对象实例安全(不同的域对象可以具有不同的权限)。考虑到这些典型要求,我们有以下注意事项:

Suppose you are developing an enterprise application based on Spring. You typically need to address four security concerns : authentication, web request security, service layer security (your methods that implement business logic), and domain object instance security (different domain objects can have different permissions). With these typical requirements in mind, we have the following considerations:

  • Authentication: The servlet specification provides an approach to authentication. However, you need to configure the container to perform authentication, which typically requires editing of container-specific “realm” settings. This makes a non-portable configuration. Also, if you need to write an actual Java class to implement the container’s authentication interface, it becomes even more non-portable. With Spring Security, you achieve complete portability — right down to the WAR level. Also, Spring Security offers a choice of production-proven authentication providers and mechanisms, meaning you can switch your authentication approaches at deployment time. This is particularly valuable for software vendors writing products that need to work in an unknown target environment.

  • Web request security: The servlet specification provides an approach to secure your request URIs. However, these URIs can be expressed only in the servlet specification’s own limited URI path format. Spring Security provides a far more comprehensive approach. For instance, you can use Ant paths or regular expressions, you can consider parts of the URI other than simply the requested page (for example, you can consider HTTP GET parameters), and you can implement your own runtime source of configuration data. This means that you can dynamically change your web request security during the actual execution of your web application.

  • Service layer and domain object security: The absence of support in the servlet specification for services layer security or domain object instance security represents serious limitations for multi-tiered applications. Typically, developers either ignore these requirements or implement security logic within their MVC controller code (or, even worse, inside the views). There are serious disadvantages with this approach:

    • Separation of concerns: Authorization is a crosscutting concern and should be implemented as such. MVC controllers or views that implement authorization code makes it more difficult to test both the controller and the authorization logic, is more difficult to debug, and often leads to code duplication.

    • Support for rich clients and web services: If an additional client type must ultimately be supported, any authorization code embedded within the web layer is non-reusable. It should be considered that Spring remoting exporters export only service layer beans (not MVC controllers). As a result, authorization logic needs to be located in the services layer to support a multitude of client types.

    • Layering issues: An MVC controller or view is the incorrect architectural layer in which to implement authorization decisions concerning services layer methods or domain object instances. While the principal may be passed to the services layer to enable it to make the authorization decision, doing so would introduce an additional argument on every services layer method. A more elegant approach is to use a ThreadLocal to hold the principal, although this would likely increase development time to a point where it would become more economical (on a cost-benefit basis) to use a dedicated security framework.

    • Authorization code quality: It is often said of web frameworks that they “make it easier to do the right things, and harder to do the wrong things”. Security frameworks are the same, because they are designed in an abstract manner for a wide range of purposes. Writing your own authorization code from scratch does not provide the “design check” a framework would offer, and in-house authorization code typically lacks the improvements that emerge from widespread deployment, peer review, and new versions.

对于简单的应用程序,servlet 规范安全性可能就足够了。尽管在 Web 容器可移植性、配置要求、受限的 Web 请求安全性灵活性和不存在的服务层和域对象实例安全性的情况下,很明显,为什么开发人员经常寻找替代解决方案。

For simple applications, servlet specification security may be enough. Although when considered within the context of web container portability, configuration requirements, limited web request security flexibility, and non-existent services layer and domain object instance security, it becomes clear why developers often look to alternative solutions.

What Java and Spring Framework versions are required?

Spring Security 3.0 和 3.1 至少需要 JDK 1.5,并且至少需要 Spring 3.0.3。理想情况下,您应该使用最新版本以避免出现问题。

Spring Security 3.0 and 3.1 require at least JDK 1.5 and also require Spring 3.0.3 as a minimum. Ideally, you should use the latest release versions to avoid problems.

Spring Security 2.0.x 至少需要 JDK 版本 1.4,并且针对 Spring 2.0.x 构建。它还应与使用 Spring 2.5.x 的应用程序兼容。

Spring Security 2.0.x requires a minimum JDK version of 1.4 and is built against Spring 2.0.x. It should also be compatible with applications that use Spring 2.5.x.

I have a complex scenario. What could be wrong?

(此答案通过解决特定情况来一般性地解决复杂场景。)

(This answer address complex scenarios in general by dealing with a particular scenario.)

假设您不熟悉 Spring Security,并且需要构建一个应用程序,该应用程序支持通过 HTTPS 进行 CAS 单点登录,同时允许对某些 URL 本地进行基本身份验证,针对多个后端用户信息源(LDAP 和 JDBC)进行身份验证。您已复制了一些配置文件,但发现无法正常工作。出了什么问题?

Suppose you are new to Spring Security and need to build an application that supports CAS single sign-on over HTTPS while allowing basic authentication locally for certain URLs, authenticating against multiple back end user information sources (LDAP and JDBC). You have copied some configuration files but have found that it does not work. What could be wrong?

在您可以成功使用它们构建应用程序之前,您需要了解您打算使用的技术。安全性很复杂。使用登录表单和一些 Spring Security 命名空间的硬编码用户设置一个简单的配置是相当直接的。转换到使用支持的 JDBC 数据库也足够简单。但是,如果您尝试直接跳到此类情况的复杂部署场景,您几乎肯定会感到沮丧。设置诸如 CAS、配置 LDAP 服务器和正确安装 SSL 证书之类的系统需要进行大幅的学习曲线飞跃。因此,您需要一步一步进行。

You need an understanding of the technologies you intend to use before you can successfully build applications with them. Security is complicated. Setting up a simple configuration by using a login form and some hard-coded users with Spring Security’s namespace is reasonably straightforward. Moving to using a backed JDBC database is also easy enough. However, if you try to jump straight to a complicated deployment scenario like this scenario, you are almost certain to be frustrated. There is a big jump in the learning curve required to set up systems such as CAS, configure LDAP servers, and install SSL certificates properly. So you need to take things one step at a time.

从 Spring Security 的角度来看,您应该做的第一件事是遵循网站上的“入门”指南。这将引导您完成一系列步骤以启动并运行,并了解框架如何操作。如果您使用其他不熟悉的技术,您应该进行一些研究并尝试确保您可以在将它们组合到复杂系统中之前单独使用它们。

From a Spring Security perspective, the first thing you should do is follow the “Getting Started” guide on the website. This will take you through a series of steps to get up and running and get some idea of how the framework operates. If you use other technologies with which you are not familiar, you should do some research and try to make sure you can use them in isolation before combining them in a complex system.

Common Problems

本部分讨论了人们在使用 Spring Security 时遇到的最常见问题:

This section addresses the most common problems that people encounter when using Spring Security:

When I try to log in, I get an error message that says, “Bad Credentials”. What is wrong?

这意味着身份验证失败。它没有说明原因,因为它是一种避免提供可能帮助攻击者猜出帐户名或密码的详细信息的良好做法。

This means that authentication has failed. It does not say why, as it is good practice to avoid giving details that might help an attacker guess account names or passwords.

这也意味着如果您在线提出此问题,除非提供其他信息,否则不应期望得到答复。与任何问题一样,您应该检查调试日志的输出并注意任何异常堆栈跟踪和相关消息。您应该在调试器中逐步检查代码以查看身份验证失败的位置以及原因。您还应该编写一个测试用例在应用程序外部演练您的身份验证配置。如果您使用哈希密码,请确保存储在数据库中的值与应用程序中配置的 PasswordEncoder 生成的值完全相同。

This also means that, if you ask this question online, you should not expect an answer unless you provide additional information. As with any issue, you should check the output from the debug log and note any exception stacktraces and related messages. You should step through the code in a debugger to see where the authentication fails and why. You should also write a test case which exercises your authentication configuration outside the application. If you use hashed passwords, make sure the value stored in your database is exactly the same as the value produced by the PasswordEncoder configured in your application.

My application goes into an “endless loop” when I try to log in. What is going on?

使用无限循环并重定向到登录页面时,会发生常见的用户问题,这个的原因是意外地配置了登录页面为“安全”资源。确保你的配置允许以匿名方式访问登录页面,可以通过从安全过滤器链中排除登录页面或标记为需要 ROLE_ANONYMOUS 来做到这一点。

A common user problem with infinite loop and redirecting to the login page is caused by accidentally configuring the login page as a “secured” resource. Make sure your configuration allows anonymous access to the login page, either by excluding it from the security filter chain or marking it as requiring ROLE_ANONYMOUS.

如果你的 AccessDecisionManager 包含一个 AuthenticatedVoter,则可以使用 IS_AUTHENTICATED_ANONYMOUSLY 属性。如果你使用标准的命名空间配置设置,它会自动可用。

If your AccessDecisionManager includes an AuthenticatedVoter, you can use the IS_AUTHENTICATED_ANONYMOUSLY attribute. This is automatically available if you use the standard namespace configuration setup.

从 Spring Security 2.0.1 开始,当你使用基于命名空间的配置时,会在加载应用程序上下文时执行检查,如果你的登录页面似乎受到保护,则会记录一条警告消息。

From Spring Security 2.0.1 onwards, when you use namespace-based configuration, a check is made on loading the application context and a warning message logged if your login page appears to be protected.

I get an exception with the message "Access is denied (user is anonymous);". What’s wrong?

这是一条调试级别消息,当匿名用户首次尝试访问受保护的资源时发生。

This is a debug level message which occurs the first time an anonymous user attempts to access a protected resource.

DEBUG [ExceptionTranslationFilter] - Access is denied (user is anonymous); redirecting to authentication entry point
org.springframework.security.AccessDeniedException: Access is denied
at org.springframework.security.vote.AffirmativeBased.decide(AffirmativeBased.java:68)
at org.springframework.security.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:262)

这是正常的,不应感到担心。

It is normal and shouldn’t be anything to worry about.

Why can I still see a secured page even after I have logged out of my application?

最常见的原因是你的浏览器已缓存该页面,你看到的是从浏览器缓存中检索的副本。通过检查浏览器是否实际发送请求(检查你的服务器访问日志和调试日志或使用合适的浏览器调试插件,例如为 Firefox 使用“Tamper Data”)来验证这一点。这与 Spring Security 无关,你应该配置应用程序或服务器来设置合适的 Cache-Control 响应标头。请注意,SSL 请求绝不会被缓存。

The most common reason for this is that your browser has cached the page, and you are seeing a copy that is being retrieved from the browsers cache. Verify this by checking whether the browser is actually sending the request (check your server access logs and the debug log or use a suitable browser debugging plugin, such as “Tamper Data” for Firefox). This has nothing to do with Spring Security, and you should configure your application or server to set the appropriate Cache-Control response headers. Note that SSL requests are never cached.

I get an exception with a message of "An Authentication object was not found in the SecurityContext". What is wrong?

以下清单显示了匿名用户第一次尝试访问受保护时发生的另一个调试级别消息。然而,此清单展示了当过滤器链配置中没有 AnonymousAuthenticationFilter 时的处理。

The following listing shows another debug-level message that occurs the first time an anonymous user attempts to access a protected resource. However, this listing shows what happens when you do not have an AnonymousAuthenticationFilter in your filter chain configuration:

DEBUG [ExceptionTranslationFilter] - Authentication exception occurred; redirecting to authentication entry point
org.springframework.security.AuthenticationCredentialsNotFoundException:
							An Authentication object was not found in the SecurityContext
at org.springframework.security.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:342)
at org.springframework.security.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:254)

这是正常的,不必为此感到担心。

It is normal and is not something to worry about.

I can’t get LDAP authentication to work. What’s wrong with my configuration?

请注意,LDAP 目录的权限通常不允许你读取用户的密码。因此,通常无法在 Spring Security 将存储的密码与用户提交的密码进行比较时使用 What is a UserDetailsService and do I need one? 。最常见的方法是使用 LDAP “bind” ,这是 the LDAP protocol 支持的操作之一。通过这种方法,Spring Security 通过尝试以用户身份对目录进行身份验证来验证密码。

Note that the permissions for an LDAP directory often do not let you read the password for a user. Hence, it is often not possible to use the What is a UserDetailsService and do I need one? where Spring Security compares the stored password with the one submitted by the user. The most common approach is to use LDAP “bind”, which is one of the operations supported by the LDAP protocol. With this approach, Spring Security validates the password by trying to authenticate to the directory as the user.

LDAP 认证最常见的问题是对目录服务器树结构和配置缺乏了解。这在不同公司之间有所不同,所以你必须自己找出答案。在向应用程序添加 Spring Security LDAP 配置之前,你应该使用标准的 Java LDAP 代码(不涉及 Spring Security)编写一个简单的测试,并确保首先让它正常运行。例如,要对用户进行身份验证,可以使用以下代码:

The most common problem with LDAP authentication is a lack of knowledge of the directory server tree structure and configuration. This differs from one company to another, so you have to find it out yourself. Before adding a Spring Security LDAP configuration to an application, you should write a simple test by using standard Java LDAP code (without Spring Security involved) and make sure you can get that to work first. For example, to authenticate a user, you could use the following code:

  • Java

  • Kotlin

@Test
public void ldapAuthenticationIsSuccessful() throws Exception {
		Hashtable<String,String> env = new Hashtable<String,String>();
		env.put(Context.SECURITY_AUTHENTICATION, "simple");
		env.put(Context.SECURITY_PRINCIPAL, "cn=joe,ou=users,dc=mycompany,dc=com");
		env.put(Context.PROVIDER_URL, "ldap://mycompany.com:389/dc=mycompany,dc=com");
		env.put(Context.SECURITY_CREDENTIALS, "joespassword");
		env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

		InitialLdapContext ctx = new InitialLdapContext(env, null);

}
@Test
fun ldapAuthenticationIsSuccessful() {
    val env = Hashtable<String, String>()
    env[Context.SECURITY_AUTHENTICATION] = "simple"
    env[Context.SECURITY_PRINCIPAL] = "cn=joe,ou=users,dc=mycompany,dc=com"
    env[Context.PROVIDER_URL] = "ldap://mycompany.com:389/dc=mycompany,dc=com"
    env[Context.SECURITY_CREDENTIALS] = "joespassword"
    env[Context.INITIAL_CONTEXT_FACTORY] = "com.sun.jndi.ldap.LdapCtxFactory"
    val ctx = InitialLdapContext(env, null)
}

Session Management

会话管理问题是一个常见的问题来源。如果你正在开发 Java Web 应用程序,你应该了解会话是如何在 servlet 容器和用户的浏览器之间保持的。你应该还了解安全和非安全 cookie 之间的差异,以及使用 HTTP、HTTPS 和在这两者之间切换的影响。Spring Security 与维护会话或提供会话标识符无关。这完全由 servlet 容器处理。

Session management issues are a common source of questions. If you are developing Java web applications, you should understand how the session is maintained between the servlet container and the user’s browser. You should also understand the difference between secure and non-secure cookies and the implications of using HTTP and HTTPS and switching between the two. Spring Security has nothing to do with maintaining the session or providing session identifiers. This is entirely handled by the servlet container.

I am using Spring Security’s concurrent session control to prevent users from logging in more than once at the same time. When I open another browser window after logging in, it does not stop me from logging in again. Why can I log in more than once?

浏览器通常为每个浏览器实例维护一个会话。你不能同时有两个独立的会话。因此,如果你在另一个窗口或标签中重新登录,你只是在同一会话中重新进行身份验证。因此,如果你在另一个窗口或标签中重新登录,你是在同一会话中重新进行身份验证。服务器不了解标签、窗口或浏览器实例。它看到的只是 HTTP 请求,并且根据它们包含的 JSESSIONID cookie 的值将这些请求绑定到特定会话。当用户在会话期间进行身份验证时,Spring Security 的并发会话控制检查他们有多少个其他经过身份验证的会话。如果他们已经使用相同的会话进行身份验证,则重新进行身份验证不会产生影响。

Browsers generally maintain a single session per browser instance. You cannot have two separate sessions at once. So if you log in again in another window or tab you are just reauthenticating in the same session. So, if you log in again in another window or tab, you are reauthenticating in the same session. The server does not know anything about tabs, windows, or browser instances. All it sees are HTTP requests, and it ties those to a particular session according to the value of the JSESSIONID cookie that they contain. When a user authenticates during a session, Spring Security’s concurrent session control checks the number of other authenticated sessions that they have. If they are already authenticated with the same session, re-authenticating has no effect.

Why does the session ID change when I authenticate through Spring Security?

在默认配置中,Spring Security 会在用户进行身份验证时更改会话 ID。如果你使用 Servlet 3.1 或更新的容器,会话 ID 只会被更改。如果你使用较旧的容器,Spring Security 会使现有会话失效,创建一个新会话,并将会话数据传输到新会话。以这种方式更改会话标识符可以防止“会话固定”攻击。你可以在网上和参考手册中找到更多这方面的信息。

With the default configuration, Spring Security changes the session ID when the user authenticates. If you use a Servlet 3.1 or newer container, the session ID is simply changed. If you use an older container, Spring Security invalidates the existing session, creates a new session, and transfers the session data to the new session. Changing the session identifier in this manner prevents “session-fixation” attacks. You can find more about this online and in the reference manual.

I use Tomcat (or some other servlet container) and have enabled HTTPS for my login page, switching back to HTTP afterward. It does not work. I end up back at the login page after authenticating.

不起作用 - 我在认证后刚刚回到登录页面。

It doesn’t work - I just end up back at the login page after authenticating.

这是因为在 HTTPS 下创建的会话(其中会话 Cookie 被标记为 “secure” )随后无法在 HTTP 下使用。浏览器不会将 Cookie 发送回服务器,任何会话状态(包括安全上下文信息)都将丢失。首先在 HTTP 中启动会话应该可以工作,因为会话 Cookie 未标记为安全。但是,Spring Security 的 Session Fixation Protection 会干扰此操作,因为它导致向用户的浏览器发送新的会话 ID Cookie,通常带有安全标志。为了解决这个问题,你可以禁用会话固定保护。但是,在较新的 Servlet 容器中,你还可以配置会话 Cookie 永远不使用安全标志。

This happens because sessions created under HTTPS, for which the session cookie is marked as “secure”, cannot subsequently be used under HTTP. The browser does not send the cookie back to the server, and any session state (including the security context information) is lost. Starting a session in HTTP first should work, as the session cookie is not marked as secure. However, Spring Security’s Session Fixation Protection can interfere with this because it results in a new session ID cookie being sent back to the user’s browser, usually with the secure flag. To get around this, you can disable session fixation protection. However, in newer Servlet containers, you can also configure session cookies to never use the secure flag.

在 HTTP 和 HTTPS 之间切换通常不是一个好主意,因为任何使用 HTTP 的应用程序都容易受到中间人攻击。为了真正安全,用户应开始以 HTTPS 方式访问你的网站,并继续使用它,直到他们注销。甚至从通过 HTTP 访问的页面单击 HTTPS 链接都可能存在风险。如果你需要更有说服力的证据,可以查阅如 sslstrip 这样的工具。

Switching between HTTP and HTTPS is not a good idea in general, as any application that uses HTTP at all is vulnerable to man-in-the-middle attacks. To be truly secure, the user should begin accessing your site in HTTPS and continue using it until they log out. Even clicking on an HTTPS link from a page accessed over HTTP is potentially risky. If you need more convincing, check out a tool like sslstrip.

I am not switching between HTTP and HTTPS, but my session is still lost. What happened?

会话的维护是通过交换会话 cookie 或将 jsessionid 参数添加到 URL 来进行的(如果你使用 JSTL 输出 URL,或者在你对 URL 调用 HttpServletResponse.encodeUrl(例如在重定向之前)),则会自动发生这种情况。如果客户端禁用了 cookie,并且你没有重写 URL 以包含 jsessionid,则会话会丢失。请注意,出于安全原因,建议使用 cookie,因为它不会在 URL 中暴露会话信息。

Sessions are maintained either by exchanging a session cookie or by adding a jsessionid parameter to URLs (this happens automatically if you use JSTL to output URLs or if you call HttpServletResponse.encodeUrl on URLs (before a redirect, for example). If clients have cookies disabled, and you are not rewriting URLs to include the jsessionid, the session is lost. Note that the use of cookies is preferred for security reasons, as it does not expose the session information in the URL.

I am trying to use the concurrent session-control support, but it does not let me log back in, even if I am sure I have logged out and have not exceeded the allowed sessions. What is wrong?

确保你在 web.xml 文件中添加了侦听器。确保在会话被销毁时通知 Spring Security 会话注册表至关重要。如果没有它,会话信息将不会从注册表中删除。以下示例在 web.xml 文件中添加一个侦听器:

Make sure you have added the listener to your web.xml file. It is essential to make sure that the Spring Security session registry is notified when a session is destroyed. Without it, the session information is not removed from the registry. The following example adds a listener in a web.xml file:

<listener>
		<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>

Spring Security creates a session somewhere, even though I have configured it not to, by setting the create-session attribute to never. What is wrong?

这通常意味着用户的应用程序在某个地方创建了一个会话,但他们不知道它。最常见的罪魁祸首是 JSP。许多人不知道 JSP 默认创建会话。为了防止 JSP 创建会话,请在页面的顶部添加 <%@ page session="false" %> 指令。

This usually means that the user’s application is creating a session somewhere but that they are not aware of it. The most common culprit is a JSP. Many people are not aware that JSPs create sessions by default. To prevent a JSP from creating a session, add the <%@ page session="false" %> directive to the top of the page.

如果你难以弄清楚会话是在哪里创建的,则可以添加一些调试代码来跟踪位置。实现此目的的一种方法是向应用程序添加一个 javax.servlet.http.HttpSessionListener,它在 sessionCreated 方法中调用 Thread.dumpStack()

If you have trouble working out where a session is being created, you can add some debugging code to track down the location(s). One way to do this is to add a javax.servlet.http.HttpSessionListener, which calls Thread.dumpStack() in the sessionCreated method, to your application.

I get a 403 Forbidden when performing a POST. What is wrong?

如果是 HTTP POST 则返回 HTTP 403 禁用错误,但对于 HTTP GET 则有效,问题很可能是与 CSRF 相关。提供 CSRF 令牌或禁用 CSRF 保护(不推荐后者)。

If an HTTP 403 Forbidden error is returned for HTTP POST, but it works for HTTP GET, the issue is most likely related to CSRF. Either provide the CSRF Token or disable CSRF protection (the latter is not recommended).

I am forwarding a request to another URL by using the RequestDispatcher, but my security constraints are not being applied.

默认情况下,过滤器不会应用于转发或包含。如果你真的希望安全过滤器应用于转发或包含,则必须使用 <dispatcher> 元素(这是 <filter-mapping> 元素的子元素)在你自己的 web.xml 文件中明确配置这些过滤器。

By default, filters are not applied to forwards or includes. If you really want the security filters to be applied to forwards or includes, you have to configure these explicitly in your web.xml file by using the <dispatcher> element, which is a child element of the <filter-mapping> element.

I have added Spring Security’s <global-method-security> element to my application context, but, if I add security annotations to my Spring MVC controller beans (Struts actions etc.), they do not seem to have an effect. Why not?

在 Spring web 应用程序中,容纳调度程序servlet的 Spring MVC bean 的应用程序上下文通常独立于主应用程序上下文,它通常在名为 myapp-servlet.xml 的文件中定义,其中 myapp 是在 web.xml 文件中分配给 Spring DispatcherServlet 的名称。一个应用程序可以有多个 DispatcherServlet 实例,每个实例都有自己独立的应用程序上下文,这些“子代”上下文中的 bean 对应用程序的其他部分是不可见的。通过在 web.xml 文件中定义的 ContextLoaderListener 加载“父代”应用程序上下文,并且它对所有子代上下文可见,此父上下文通常是你定义安全配置(包括 <global-method-security> 元素)的位置,因此,应用于这些 Web bean 中的方法的任何安全约束都不会得到实施,因为从 DispatcherServlet 上下文无法看到这些 bean,你需要将 <global-method-security> 声明移到 Web 上下文或将你想要保护的 bean 移到主应用程序上下文中。

In a Spring web application, the application context that holds the Spring MVC beans for the dispatcher servlet is often separate from the main application context. It is often defined in a file called myapp-servlet.xml, where myapp is the name assigned to the Spring DispatcherServlet in the web.xml file. An application can have multiple DispatcherServlet instances, each with its own isolated application context. The beans in these “child” contexts are not visible to the rest of the application. The “parent” application context is loaded by the ContextLoaderListener you define in your web.xml file and is visible to all the child contexts. This parent context is usually where you define your security configuration, including the <global-method-security> element. As a result, any security constraints applied to methods in these web beans are not enforced, since the beans cannot be seen from the DispatcherServlet context. You need to either move the <global-method-security> declaration to the web context or move the beans you want secured into the main application context.

我们通常建议在服务层而不是各个 web 控制器上应用方法安全性。

Generally, we recommend applying method security at the service layer rather than on individual web controllers.

I have a user who has definitely been authenticated, but, when I try to access the SecurityContextHolder during some requests, the Authentication is null. Why can I not see the user information?

为什么我看不到用户信息?

Why can’t I see the user information?

如果你已使用与 URL 模式匹配的 intercept-url 元素中的 filters='none' 属性将请求排除在安全过滤器链之外,那么 SecurityContextHolder 并未为此请求填充,查看调试日志以查看请求是否通过了过滤器链(你正在阅读调试日志,对吧?)。

If you have excluded the request from the security filter chain by using the filters='none' attribute in the <intercept-url> element that matches the URL pattern, the SecurityContextHolder is not populated for that request. Check the debug log to see whether the request is passing through the filter chain. (You are reading the debug log, right?)

The authorize JSP Tag does not respect my method security annotations when using the URL attribute. Why not?

使用 <sec:authorize> 中的 url 属性时,方法安全性不会隐藏链接,因为我们无法轻松逆向工程哪些 URL 映射到哪个控制器端点,我们的限制在于控制器可以依赖标头、当前用户和其他详细信息来确定要调用哪个方法。

Method security does not hide links when using the url attribute in <sec:authorize>, because we cannot readily reverse engineer what URL is mapped to what controller endpoint. We are limited because controllers can rely on headers, the current user, and other details to determine what method to invoke.

Spring Security Architecture Questions

本节解决了常见的 Spring Security 架构问题:

This section addresses common Spring Security architecture questions:

How do I know which package class X is in?

查找类的最佳方式是在你的 IDE 中安装 Spring Security 源,该发行版包含项目划分的每个模块的源 jar,将这些添加到你的项目源路径,然后你可以直接导航到 Spring Security 类(在 Eclipse 中为 Ctrl-Shift-T),这也使得调试变得更容易,允许你通过直接查看引发异常的代码来进行故障排除,以查看那里发生了什么。

The best way of locating classes is by installing the Spring Security source in your IDE. The distribution includes source jars for each of the modules the project is divided up into. Add these to your project source path, and then you can navigate directly to Spring Security classes (Ctrl-Shift-T in Eclipse). This also makes debugging easier and lets you troubleshoot exceptions by looking directly at the code where they occur to see what is going on there.

How do the namespace elements map to conventional bean configurations?

参考指南的命名空间附录中概述了命名空间创建的 bean。在 blog.springsource.com 上还有一篇名为“Spring Security 命名空间的背后”的详细博客文章。如果你想了解全部详细信息,Spring Security 3.0 发行版中的 spring-security-config 模块中包含此代码。你可能应该首先阅读 Spring Framework 参考文档中有关命名空间解析的章节。

There is a general overview of what beans are created by the namespace in the namespace appendix of the reference guide. There is also a detailed blog article called "Behind the Spring Security Namespace" on blog.springsource.com. If you want to know the full details, then the code is in the spring-security-config module within the Spring Security 3.0 distribution. You should probably read the chapters on namespace parsing in the standard Spring Framework reference documentation first.

What does "ROLE_" mean and why do I need it on my role names?

Spring Security 具有基于投票者的架构,这意味着访问决策通过一系列 AccessDecisionVoter 实例来做的,投票者根据为受保护资源(如方法调用)指定“配置属性”进行投票,通过这种方法,并非所有属性都可能对所有投票者都相关,而且投票者需要知道何时应该忽略属性(弃权)以及何时应该基于属性值投票授予或拒绝访问,最常见的投票者是 RoleVoter,它在默认情况下每当找到具有 ROLE_ 前缀的属性时都会投票,它将属性(如 ROLE_USER)与分配给当前用户的权限名称进行简单的比较,如果找到匹配项(他们有一个称为 ROLE_USER 的权限),它会投票授予访问权限,否则,它会投票拒绝访问。

Spring Security has a voter-based architecture, which means that an access decision is made by a series of AccessDecisionVoter instances. The voters act on the “configuration attributes”, which are specified for a secured resource (such as a method invocation). With this approach, not all attributes may be relevant to all voters, and a voter needs to know when it should ignore an attribute (abstain) and when it should vote to grant or deny access based on the attribute value. The most common voter is the RoleVoter, which, by default, votes whenever it finds an attribute with the ROLE_ prefix. It makes a simple comparison of the attribute (such as ROLE_USER) with the names of the authorities that the current user has been assigned. If it finds a match (they have an authority called ROLE_USER), it votes to grant access. Otherwise, it votes to deny access.

你可以通过设置 RoleVoterrolePrefix 属性来更改前缀,如果你只需要在你的应用程序中使用角色,并且不需要其他自定义投票者,则可以将前缀设置为一个空字符串,在这种情况下,RoleVoter 将所有属性视为角色。

You can change the prefix by setting the rolePrefix property of RoleVoter. If you need only to use roles in your application and have no need for other custom voters, you can set the prefix to a blank string. In that case, the RoleVoter treats all attributes as roles.

How do I know which dependencies to add to my application to work with Spring Security?

这取决于你使用什么功能以及你正在开发的应用程序类型,使用 Spring Security 3.0,项目 jar 被划分为清晰不同的功能区域,因此可以直接找出你的应用程序需求所需的 Spring Security jar,所有应用程序都需要 spring-security-core jar,如果你正在开发一个 web 应用程序,则需要 spring-security-web jar,如果你正在使用安全命名空间配置,则需要 spring-security-config jar,对于 LDAP 支持,你需要 spring-security-ldap jar,依此类推。

It depends on what features you are using and what type of application you are developing. With Spring Security 3.0, the project jars are divided into clearly distinct areas of functionality, so it is straightforward to work out which Spring Security jars you need from your application requirements. All applications need the spring-security-core jar. If you are developing a web application, you need the spring-security-web jar. If you are using security namespace configuration, you need the spring-security-config jar. For LDAP support, you need the spring-security-ldap jar. And so on.

对于第三方 jar,情况并不总是那么明显,一个好的起点是从某个预构建的示例应用程序 WEB-INF/lib 目录中复制那些 jar,对于一个基本的应用程序,你可以从教程示例开始,对于一个基本应用程序,你可以从教程示例开始,如果你想要使用具有嵌入式测试服务器的 LDAP,则使用 LDAP 示例作为起点,参考手册还包括 appendix-namespace,其中列出了每个 Spring Security 模块的一级依赖项,并包含有关它们是可选的还是必需的的一些信息。

For third-party jars, the situation is not always quite so obvious. A good starting point is to copy those from one of the pre-built sample applications WEB-INF/lib directories. For a basic application, you can start with the tutorial sample. For a basic application, you can start with the tutorial sample. If you want to use LDAP with an embedded test server, use the LDAP sample as a starting point. The reference manual also includes appendix-namespace that lists the first-level dependencies for each Spring Security module, with some information on whether they are optional and when they are required.

如果你使用 Maven 构建项目,那么将相应的 Spring Security 模块作为依赖项添加到你的 pom.xml 文件会自动提取框架所需的 core jar,任何在 Spring Security pom.xml 文件中标记为“optional”的 jar 都必须添加到你自己的 pom.xml 文件(如果你需要它们)。

If you build your project with Maven, adding the appropriate Spring Security modules as dependencies to your pom.xml file automatically pulls in the core jars that the framework requires. Any that are marked as “optional” in the Spring Security pom.xml files have to be added to your own pom.xml file if you need them.

What dependencies are needed to run an embedded ApacheDS LDAP server?

如果你使用 Maven,则需要将以下内容添加到 pom.xml 文件依赖项:

If you use Maven, you need to add the following to your pom.xml file dependencies:

<dependency>
		<groupId>org.apache.directory.server</groupId>
		<artifactId>apacheds-core</artifactId>
		<version>1.5.5</version>
		<scope>runtime</scope>
</dependency>
<dependency>
		<groupId>org.apache.directory.server</groupId>
		<artifactId>apacheds-server-jndi</artifactId>
		<version>1.5.5</version>
		<scope>runtime</scope>
</dependency>

其他必需的 jar 应该被传递地提取。

The other required jars should be pulled in transitively.

What is a UserDetailsService and do I need one?

UserDetailsService 是用于加载特定于用户帐户的 DAO 接口,它没有其他功能,只是为框架内的其他组件加载数据,它不负责对用户进行身份验证,使用用户名和密码组合对用户进行身份验证通常由 DaoAuthenticationProvider 执行,其中注入了一个 UserDetailsService 以允许它为用户加载密码(和其他数据),以便与提交的值进行比较,请注意,如果你使用 LDAP,[这种方法可能不起作用,appendix-faq-ldap-authentication]

UserDetailsService is a DAO interface for loading data that is specific to a user account. It has no function other than to load that data for use by other components within the framework. It is not responsible for authenticating the user. Authenticating a user with a username and password combination is most commonly performed by the DaoAuthenticationProvider, which is injected with a UserDetailsService to let it load the password (and other data) for a user, to compare it with the submitted value. Note that, if you use LDAP, appendix-faq-ldap-authentication.

如果你想自定义认证流程,则应该自己实现 AuthenticationProvider。请参阅 blog article 以获取一个将 Spring Security 认证与 Google App Engine 相集成的示例。

If you want to customize the authentication process, you should implement AuthenticationProvider yourself. See this blog article for an example that integrate Spring Security authentication with Google App Engine.

Common How-to Questions

本节解决了有关 Spring Security 的常见操作问题:

This section addresses common how-to questions about Spring Security:

I need to log in with more information than just the username. How do I add support for extra login fields (such as a company name)?

这个问题一再出现,因此您可以在线搜索以查找更多信息。

This question comes up repeatedly, so you can find more information by searching online.

提交的登录信息由 UsernamePasswordAuthenticationFilter 实例处理。您需要自定义此类以处理额外的数据字段。一种方法是使用自己自定义的身份验证令牌类(而不是标准的 UsernamePasswordAuthenticationToken)。另一种方法是将额外字段与用户名连接(例如,使用 : 字符作为分隔符),然后将它们传递到 UsernamePasswordAuthenticationToken 的用户名属性中。

The submitted login information is processed by an instance of UsernamePasswordAuthenticationFilter. You need to customize this class to handle the extra data fields. One option is to use your own customized authentication token class (rather than the standard UsernamePasswordAuthenticationToken). Another option is to concatenate the extra fields with the username (for example, by using a : character as the separator) and pass them in the username property of UsernamePasswordAuthenticationToken.

您还需要自定义实际的身份验证过程。例如,如果您使用自定义的身份验证令牌类,那么您将必须编写一个 AuthenticationProvider(或扩展标准的 DaoAuthenticationProvider)来处理它。如果您已连接各个字段,那么您可以实现自己的 UserDetailsService 以拆分这些字段并加载用于身份验证的适当用户数据。

You also need to customize the actual authentication process. If you use a custom authentication token class, for example, you will have to write an AuthenticationProvider (or extend the standard DaoAuthenticationProvider) to handle it. If you have concatenated the fields, you can implement your own UserDetailsService to split them up and load the appropriate user data for authentication.

How do I apply different intercept-url constraints where only the fragment value of the requested URLs differs (such as /thing1#thing2 and /thing1#thing3)?

您无法执行此操作,因为片段不会从浏览器传输到服务器。从服务器的角度来看,URL 是相同的。这是 GWT 用户的一个常见问题。

You cannot do this, since the fragment is not transmitted from the browser to the server. From the server’s perspective, the URLs are identical. This is a common question from GWT users.

How do I access the user’s IP Address (or other web-request data) in a UserDetailsService?

您无法执行此操作(不用求助于诸如线程局部变量之类的内容),因为提供给接口的唯一信息是用户名。不要实现 UserDetailsService,应该直接实现 AuthenticationProvider 并从提供的 Authentication 令牌中提取信息。

You cannot (without resorting to something like thread-local variables), since the only information supplied to the interface is the username. Instead of implementing UserDetailsService, you should implement AuthenticationProvider directly and extract the information from the supplied Authentication token.

在标准的 Web 设置中,Authentication 对象上的 getDetails() 方法将返回 WebAuthenticationDetails 实例。如果您需要更多信息,可以将自定义 AuthenticationDetailsSource 注入您正在使用的身份验证过滤器中。如果您正在使用命名空间,例如使用 <form-login> 元素,那么您应该删除此元素,并用指向显式配置的 UsernamePasswordAuthenticationFilter<custom-filter> 声明替换它。

In a standard web setup, the getDetails() method on the Authentication object will return an instance of WebAuthenticationDetails. If you need additional information, you can inject a custom AuthenticationDetailsSource into the authentication filter you are using. If you are using the namespace, for example with the <form-login> element, then you should remove this element and replace it with a <custom-filter> declaration pointing to an explicitly configured UsernamePasswordAuthenticationFilter.

How do I access the HttpSession from a UserDetailsService?

您无法完成此操作,因为 UserDetailsService 不了解 servlet API。如果您要存储自定义用户数据,则应自定义返回的 UserDetails 对象。然后可以通过线程局部 SecurityContextHolder 随时进行访问。调用 SecurityContextHolder.getContext().getAuthentication().getPrincipal() 会返回此自定义对象。

You cannot, since the UserDetailsService has no awareness of the servlet API. If you want to store custom user data, you should customize the UserDetails object that is returned. This can then be accessed at any point, through the thread-local SecurityContextHolder. A call to SecurityContextHolder.getContext().getAuthentication().getPrincipal() returns this custom object.

如果您确实需要访问会话,则必须通过自定义 Web 层来执行此操作。

If you really need to access the session, you must do so by customizing the web tier.

How do I access the user’s password in a UserDetailsService?

您不能(而且不应该,即使您找到了执行此操作的方法)。您可能误解了它的目的。请参见本文档前面《“什么是 UserDetailsService?”,附录常见问答 - 什么是 UserDetailsService》中的相关内容。

You cannot (and should not, even if you find a way to do so). You are probably misunderstanding its purpose. See "appendix-faq-what-is-userdetailservice", earlier in the FAQ.

How do I dynamically define the secured URLs within an application?

人们经常询问如何将受保护的 URL 与安全元数据属性之间的映射存储在数据库中,而不是存储在应用程序上下文中。

People often ask about how to store the mapping between secured URLs and security metadata attributes in a database rather than in the application context.

您应该首先问问自己是否真的需要这样做。如果应用程序需要安全,那么它还要求基于已定义的策略对安全性进行全面测试。在将其推广到生产环境中之前,可能需要进行审计和验收测试。注重安全性的组织应该意识到其严格的测试过程带来的好处可能因为改变配置数据库中的一两行而导致安全设置在运行时被修改而立即消失。如果您已考虑到这一点(也许通过在您的应用程序中使用多层安全),那么 Spring Security 会让您可以完全自定义安全元数据的来源。如果您选择,可以使其完全动态。

The first thing you should ask yourself is if you really need to do this. If an application needs to be secure, it also requires that the security be tested thoroughly based on a defined policy. It may require auditing and acceptance testing before being rolled out into a production environment. A security-conscious organization should be aware that the benefits of their diligent testing process could be wiped out instantly by letting the security settings be modified at runtime by changing a row or two in a configuration database. If you have taken this into account (perhaps by using multiple layers of security within your application), Spring Security lets you fully customize the source of security metadata. You can make it fully dynamic if you choose.

方法和 Web 安全性均受 AbstractSecurityInterceptor 的子类的保护,其配置了一个 SecurityMetadataSource,它从中获取特定方法或过滤器调用所需元数据。对于 Web 安全性,拦截器类是 FilterSecurityInterceptor,它使用 FilterInvocationSecurityMetadataSource 标记接口。它操作的“安全对象”类型是 FilterInvocation。默认实现(在命名空间 <http> 和显式配置拦截器时均使用)在内存映射中存储 URL 模式列表及其相对应的“配置属性”(ConfigAttribute 实例)列表。

Both method and web security are protected by subclasses of AbstractSecurityInterceptor, which is configured with a SecurityMetadataSource from which it obtains the metadata for a particular method or filter invocation. For web security, the interceptor class is FilterSecurityInterceptor, and it uses the FilterInvocationSecurityMetadataSource marker interface. The “secured object” type it operates on is a FilterInvocation. The default implementation (which is used both in the namespace <http> and when configuring the interceptor explicitly) stores the list of URL patterns and their corresponding list of “configuration attributes” (instances of ConfigAttribute) in an in-memory map.

要从备用来源加载数据,您必须使用显式声明的安全过滤器链(通常情况下是 Spring Security 的 FilterChainProxy)来自定义 FilterSecurityInterceptor Bean。您无法使用命名空间。然后,您将实现 FilterInvocationSecurityMetadataSource 来加载您想要用于特定 FilterInvocation 的数据。FilterInvocation 对象包含 HttpServletRequest,因此您可以基于其对返回的属性列表中包含的内容做出决策而获取 URL 或其他任何相关信息。基本提纲类似于以下示例:

To load the data from an alternative source, you must use an explicitly declared security filter chain (typically Spring Security’s FilterChainProxy) to customize the FilterSecurityInterceptor bean. You cannot use the namespace. You would then implement FilterInvocationSecurityMetadataSource to load the data as you please for a particular FilterInvocation. The FilterInvocation object contains the HttpServletRequest, so you can obtain the URL or any other relevant information on which to base your decision, based on what the list of returned attributes contains. A basic outline would look something like the following example:

  • Java

  • Kotlin

	public class MyFilterSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

		public List<ConfigAttribute> getAttributes(Object object) {
			FilterInvocation fi = (FilterInvocation) object;
				String url = fi.getRequestUrl();
				String httpMethod = fi.getRequest().getMethod();
				List<ConfigAttribute> attributes = new ArrayList<ConfigAttribute>();

				// Lookup your database (or other source) using this information and populate the
				// list of attributes

				return attributes;
		}

		public Collection<ConfigAttribute> getAllConfigAttributes() {
			return null;
		}

		public boolean supports(Class<?> clazz) {
			return FilterInvocation.class.isAssignableFrom(clazz);
		}
	}
class MyFilterSecurityMetadataSource : FilterInvocationSecurityMetadataSource {
    override fun getAttributes(securedObject: Any): List<ConfigAttribute> {
        val fi = securedObject as FilterInvocation
        val url = fi.requestUrl
        val httpMethod = fi.request.method

        // Lookup your database (or other source) using this information and populate the
        // list of attributes
        return ArrayList()
    }

    override fun getAllConfigAttributes(): Collection<ConfigAttribute>? {
        return null
    }

    override fun supports(clazz: Class<*>): Boolean {
        return FilterInvocation::class.java.isAssignableFrom(clazz)
    }
}

有关更多信息,请查看 DefaultFilterInvocationSecurityMetadataSource 的代码。

For more information, look at the code for DefaultFilterInvocationSecurityMetadataSource.

How do I authenticate against LDAP but load user roles from a database?

LdapAuthenticationProvider bean(它处理 Spring Security 中的正常 LDAP 身份验证)配置了两个单独的策略接口,一个执行身份验证,另一个加载用户权限,它们分别称为 LdapAuthenticatorLdapAuthoritiesPopulatorDefaultLdapAuthoritiesPopulator 从 LDAP 目录中加载用户权限,并具有可用于指定如何检索这些用户权限的各种配置参数。

The LdapAuthenticationProvider bean (which handles normal LDAP authentication in Spring Security) is configured with two separate strategy interfaces, one that performs the authentication and one that loads the user authorities, called LdapAuthenticator and LdapAuthoritiesPopulator, respectively. The DefaultLdapAuthoritiesPopulator loads the user authorities from the LDAP directory and has various configuration parameters to let you specify how these should be retrieved.

相反,要使用 JDBC,您可以使用适用于您架构的任何 SQL 自行实现接口:

To use JDBC instead, you can implement the interface yourself, by using whatever SQL is appropriate for your schema:

  • Java

  • Kotlin

public class MyAuthoritiesPopulator implements LdapAuthoritiesPopulator {
    @Autowired
    JdbcTemplate template;

    List<GrantedAuthority> getGrantedAuthorities(DirContextOperations userData, String username) {
        return template.query("select role from roles where username = ?",
                new String[] {username},
                new RowMapper<GrantedAuthority>() {
             /**
             *  We're assuming here that you're using the standard convention of using the role
             *  prefix "ROLE_" to mark attributes which are supported by Spring Security's RoleVoter.
             */
            @Override
            public GrantedAuthority mapRow(ResultSet rs, int rowNum) throws SQLException {
                return new SimpleGrantedAuthority("ROLE_" + rs.getString(1));
            }
        });
    }
}
class MyAuthoritiesPopulator : LdapAuthoritiesPopulator {
    @Autowired
    lateinit var template: JdbcTemplate

    override fun getGrantedAuthorities(userData: DirContextOperations, username: String): MutableList<GrantedAuthority?> {
        return template.query("select role from roles where username = ?",
            arrayOf(username)
        ) { rs, _ ->
            /**
             * We're assuming here that you're using the standard convention of using the role
             * prefix "ROLE_" to mark attributes which are supported by Spring Security's RoleVoter.
             */
            SimpleGrantedAuthority("ROLE_" + rs.getString(1))
        }
    }
}

然后,可以向应用程序上下文添加此类型的 bean,并将其注入到 LdapAuthenticationProvider 中。参考手册的 LDAP 章节中关于使用明确 Spring bean 配置 LDAP 的部分介绍了这一点。请注意,在这种情况下,不能将命名空间用于配置。你還應查閱 security-api-url[Javadoc],以獲取相關的類別和介面。

You would then add a bean of this type to your application context and inject it into the LdapAuthenticationProvider. This is covered in the section on configuring LDAP by using explicit Spring beans in the LDAP chapter of the reference manual. Note that you cannot use the namespace for configuration in this case. You should also consult the security-api-url[Javadoc] for the relevant classes and interfaces.

I want to modify the property of a bean that is created by the namespace, but there is nothing in the schema to support it. What can I do short of abandoning namespace use?

命名空间功能是有意限定的,因此它不能涵盖你可以用纯 bean 做的所有事情。如果你想做一些简单的事情,比如修改 bean 或注入不同的依赖关系,则可以通过向配置添加 BeanPostProcessor 来实现。你可以在 Spring Reference Manual 中找到更多信息。为此,你需要了解创建哪些 bean,因此你也应该阅读前面问题中的博客文章 how the namespace maps to Spring beans

The namespace functionality is intentionally limited, so it does not cover everything that you can do with plain beans. If you want to do something simple, such as modifying a bean or injecting a different dependency, you can do so by adding a BeanPostProcessor to your configuration. You can find more information in the Spring Reference Manual. To do so, you need to know a bit about which beans are created, so you should also read the blog article mentioned in the earlier question on appendix-faq-namespace-to-bean-mapping.

通常,您将所需功能添加到 BeanPostProcessorpostProcessBeforeInitialization 方法。假设您想自定义 UsernamePasswordAuthenticationFilter(由 form-login 元素创建)使用的 AuthenticationDetailsSource。您想从请求中提取一个名为 CUSTOM_HEADER 的特定标头,并在此标头验证用户身份时使用它。处理器类如下列清单所示:

Normally, you would add the functionality you require to the postProcessBeforeInitialization method of BeanPostProcessor. Suppose that you want to customize the AuthenticationDetailsSource used by the UsernamePasswordAuthenticationFilter (created by the form-login element). You want to extract a particular header called CUSTOM_HEADER from the request and use it while authenticating the user. The processor class would look like the following listing:

  • Java

  • Kotlin

public class CustomBeanPostProcessor implements BeanPostProcessor {

		public Object postProcessAfterInitialization(Object bean, String name) {
				if (bean instanceof UsernamePasswordAuthenticationFilter) {
						System.out.println("********* Post-processing " + name);
						((UsernamePasswordAuthenticationFilter)bean).setAuthenticationDetailsSource(
										new AuthenticationDetailsSource() {
												public Object buildDetails(Object context) {
														return ((HttpServletRequest)context).getHeader("CUSTOM_HEADER");
												}
										});
				}
				return bean;
		}

		public Object postProcessBeforeInitialization(Object bean, String name) {
				return bean;
		}
}
class CustomBeanPostProcessor : BeanPostProcessor {
    override fun postProcessAfterInitialization(bean: Any, name: String): Any {
        if (bean is UsernamePasswordAuthenticationFilter) {
            println("********* Post-processing $name")
            bean.setAuthenticationDetailsSource(
                AuthenticationDetailsSource<HttpServletRequest, Any?> { context -> context.getHeader("CUSTOM_HEADER") })
        }
        return bean
    }

    override fun postProcessBeforeInitialization(bean: Any, name: String?): Any {
        return bean
    }
}

然后,您将在应用程序上下文中注册此 Bean。Spring 将自动在应用程序上下文中定义的 Bean 上调用它。

You would then register this bean in your application context. Spring automatically invoke it on the beans defined in the application context.