1. 程式人生 > >Spring Security(十九):6. Security Namespace Configuration

Spring Security(十九):6. Security Namespace Configuration

6.1 Introduction

Namespace configuration has been available since version 2.0 of the Spring Framework. It allows you to supplement the traditional Spring beans application context syntax with elements from additional XML schema. You can find more information in the Spring Reference Documentation

. A namespace element can be used simply to allow a more concise way of configuring an individual bean or, more powerfully, to define an alternative configuration syntax which more closely matches the problem domain and hides the underlying complexity from the user.

自Spring Framework 2.0版以來,名稱空間配置已經可用。它允許您使用其他XML模式中的元素來補充傳統的Spring bean應用程式上下文語法。您可以在Spring Reference Documentation中找到更多資訊。名稱空間元素可以簡單地用於允許更簡潔的方式來配置單個bean,或者更有力地用於定義替代配置語法,該語法更緊密地匹配問題域並且隱藏使用者的底層複雜性。    A simple element may conceal the fact that multiple beans and processing steps are being added to the application context. For example, adding the following element from the security namespace to an application context will start up an embedded LDAP server for testing use within the application: 一個簡單的元素可能會隱藏多個bean和處理步驟被新增到應用程式上下文的事實。例如,將以下元素從安全名稱空間新增到應用程式上下文將啟動嵌入式LDAP伺服器,以便在應用程式中測試使用:
<security:ldap-server />

This is much simpler than wiring up the equivalent Apache Directory Server beans. The most common alternative configuration requirements are supported by attributes on the ldap-server element and the user is isolated from worrying about which beans they need to create and what the bean property names are. 

[1]. Use of a good XML editor while editing the application context file should provide information on the attributes and elements that are available. We would recommend that you try out the Spring Tool Suite as it has special features for working with standard Spring namespaces.

這比連線等效的Apache Directory Server bean簡單得多。 ldap-server元素上的屬性支援最常見的備用配置要求,並且使用者可以避免擔心需要建立哪些bean以及bean屬性名稱是什麼。 [1]。在編輯應用程式上下文檔案時使用良好的XML編輯器應該提供有關可用屬性和元素的資訊。我們建議您試用Spring Tool Suite,因為它具有處理標準Spring名稱空間的特殊功能。   To start using the security namespace in your application context, you need to have the  spring-security-config jar on your classpath. Then all you need to do is add the schema declaration to your application context file: 要在應用程式上下文中開始使用安全名稱空間,您需要在類路徑上安裝spring-security-config jar。然後,您需要做的就是將架構宣告新增到應用程式上下文檔案中:  
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/security
		http://www.springframework.org/schema/security/spring-security.xsd">
	...
</beans>

In many of the examples you will see (and in the sample applications), we will often use "security" as the default namespace rather than "beans", which means we can omit the prefix on all the security namespace elements, making the content easier to read. You may also want to do this if you have your application context divided up into separate files and have most of your security configuration in one of them. Your security application context file would then start like this

在您將看到的許多示例中(以及示例應用程式中),我們經常使用“security”作為預設名稱空間而不是“beans”,這意味著我們可以在所有安全名稱空間元素上省略字首,從而製作內容更容易閱讀。如果您將應用程式上下文劃分為單獨的檔案並在其中一個檔案中包含大部分安全配置,則可能還需要執行此操作。然後,您的安全應用程式上下文檔案將如下所示  
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/security
		http://www.springframework.org/schema/security/spring-security.xsd">
	...
</beans:beans>

We’ll assume this syntax is being used from now on in this chapter.

我們假設從現在開始在本章中使用了這種語法。

6.1.1 Design of the Namespace

The namespace is designed to capture the most common uses of the framework and provide a simplified and concise syntax for enabling them within an application. The design is based around the large-scale dependencies within the framework, and can be divided up into the following areas:

名稱空間旨在捕獲框架的最常見用法,並提供簡化和簡潔的語法,以便在應用程式中啟用它們。該設計基於框架內的大規模依賴性,可分為以下幾個方面:  
  • Web/HTTP Security - the most complex part. Sets up the filters and related service beans used to apply the framework authentication mechanisms, to secure URLs, render login and error pages and much more.
  • Web / HTTP安全 - 最複雜的部分。設定用於應用框架身份驗證機制的過濾器和相關服務bean,保護URL,呈現登入和錯誤頁面等等。
  • Business Object (Method) Security - options for securing the service layer.
  • 業務物件(方法)安全性 - 保護服務層的選項。
  • AuthenticationManager - handles authentication requests from other parts of the framework.
  • AuthenticationManager - 處理來自框架其他部分的身份驗證請求。
  • AccessDecisionManager - provides access decisions for web and method security. A default one will be registered, but you can also choose to use a custom one, declared using normal Spring bean syntax.
  • AccessDecisionManager - 提供Web和方法安全性的訪問決策。將註冊一個預設值,但您也可以選擇使用自定義Spring bean語法宣告的自定義。
  • AuthenticationProviders - mechanisms against which the authentication manager authenticates users. The namespace provides supports for several standard options and also a means of adding custom beans declared using a traditional syntax.
  • AuthenticationProviders - 身份驗證管理器對使用者進行身份驗證的機制。名稱空間提供了對多個標準選項的支援,也提供了新增使用傳統語法宣告的自定義bean的方法。
  • UserDetailsService - closely related to authentication providers, but often also required by other beans.
  • UserDetailsS​​ervice - 與身份驗證提供程式密切相關,但通常也需要其他bean。

We’ll see how to configure these in the following sections.

我們將在以下部分中看到如何配置它們。  

6.2 Getting Started with Security Namespace Configuration

In this section, we’ll look at how you can build up a namespace configuration to use some of the main features of the framework. Let’s assume you initially want to get up and running as quickly as possible and add authentication support and access control to an existing web application, with a few test logins. Then we’ll look at how to change over to authenticating against a database or other security repository. In later sections we’ll introduce more advanced namespace configuration options.

在本節中,我們將介紹如何構建名稱空間配置以使用框架的一些主要功能。假設您最初希望儘快啟動並執行,並通過一些測試登入將身份驗證支援和訪問控制新增到現有Web應用程式。然後,我們將瞭解如何更改以對資料庫或其他安全儲存庫進行身份驗證。在後面的部分中,我們將介紹更高階的名稱空間配置選項。  

6.2.1 web.xml Configuration

The first thing you need to do is add the following filter declaration to your web.xml file:

您需要做的第一件事是將以下過濾器宣告新增到您的web.xml檔案中:  
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

This provides a hook into the Spring Security web infrastructure. DelegatingFilterProxy is a Spring Framework class which delegates to a filter implementation which is defined as a Spring bean in your application context. In this case, the bean is named "springSecurityFilterChain", which is an internal infrastructure bean created by the namespace to handle web security. Note that you should not use this bean name yourself. Once you’ve added this to your web.xml, you’re ready to start editing your application context file. Web security services are configured using the <http> element.

這為Spring Security Web基礎結構提供了一個鉤子。 DelegatingFilterProxy是一個Spring Framework類,它委託給一個過濾器實現,該實現在應用程式上下文中定義為一個Spring bean。在這種情況下,bean被命名為“springSecurityFilterChain”,它是由名稱空間建立的內部基礎結構bean,用於處理Web安全性。請注意,您不應自己使用此bean名稱。將此檔案新增到web.xml後,即可開始編輯應用程式上下文檔案。使用<http>元素配置Web安全服務。  

6.2.2 A Minimal <http> Configuration

All you need to enable web security to begin with is

啟用Web安全性所需的只是
<http>
<intercept-url pattern="/**" access="hasRole('USER')" />
<form-login />
<logout />
</http>

Which says that we want all URLs within our application to be secured, requiring the role ROLE_USER to access them, we want to log in to the application using a form with username and password, and that we want a logout URL registered which will allow us to log out of the application. <http> element is the parent for all web-related namespace functionality. The <intercept-url> element defines a pattern which is matched against the URLs of incoming requests using an ant path style syntax [2]

這說明我們希望應用程式中的所有URL都是安全的,需要角色ROLE_USER來訪問它們,我們希望使用帶有使用者名稱和密碼的表單登入應用程式,並且我們希望註冊的登出URL允許我們退出應用程式。 <http>元素是所有與Web相關的名稱空間功能的父元素。 <intercept-url>元素定義了一個模式,該模式使用ant路徑樣式語法[2]與傳入請求的URL匹配。   You can also use regular-expression matching as an alternative (see the namespace appendix for more details). The  access attribute defines the access requirements for requests matching the given pattern. With the default configuration, this is typically a comma-separated list of roles, one of which a user must have to be allowed to make the request.  您還可以使用正則表示式匹配作為替代方法(有關詳細資訊,請參閱名稱空間附錄)。 access屬性定義與給定模式匹配的請求的訪問要求。使用預設配置時,這通常是以逗號分隔的角色列表,其中一個角色必須允許使用者發出請求。   The prefix"ROLE_" is a marker which indicates that a simple comparison with the user’s authorities should be made. In other words, a normal role-based check should be used. Access-control in Spring Security is not limited to the use of simple roles (hence the use of the prefix to differentiate between different types of security attributes). We’ll see later how the interpretation can vary footnote:[The interpretation of the comma-separated values in the  access attribute depends on the implementation of the –1— which is used. In Spring Security 3.0, the attribute can also be populated with an –2—. 字首“ROLE_”是一個標記,表示應該與使用者的許可權進行簡單比較。換句話說,應該使用正常的基於角色的檢查。 Spring Security中的訪問控制不僅限於使用簡單角色(因此使用字首來區分不同型別的安全屬性)。稍後我們將看到解釋如何變化腳註:[訪問屬性中逗號分隔值的解釋取決於所使用的-1的實現。在Spring Security 3.0中,該屬性也可以用-2-填充。   You can use multiple  <intercept-url> elements to define different access requirements for different sets of URLs, but they will be evaluated in the order listed and the first match will be used. So you must put the most specific matches at the top. You can also add a  method attribute to limit the match to a particular HTTP method ( GETPOSTPUT etc.). 您可以使用多個<intercept-url>元素為不同的URL集定義不同的訪問要求,但它們將按列出的順序進行評估,並將使用第一個匹配項。所以你必須把最具體的比賽放在最上面。您還可以新增方法屬性以限制與特定HTTP方法(GET,POST,PUT等)的匹配。   To add some users, you can define a set of test data directly in the namespace: 要新增一些使用者,您可以直接在名稱空間中定義一組測試資料:  
<authentication-manager>
<authentication-provider>
	<user-service>
	<user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN" />
	<user name="bob" password="bobspassword" authorities="ROLE_USER" />
	</user-service>
</authentication-provider>
</authentication-manager>

If you are familiar with pre-namespace versions of the framework, you can probably already guess roughly what’s going on here. The <http> element is responsible for creating a FilterChainProxy and the filter beans which it uses. Common problems like incorrect filter ordering are no longer an issue as the filter positions are predefined.

如果您熟悉框架的名稱空間前版本,那麼您可能已經大致猜測了這裡發生了什麼。 <http>元素負責建立FilterChainProxy及其使用的過濾器bean。由於過濾器位置是預定義的,因此不正確的過濾器排序等常見問題不再是問題。   The  <authentication-provider> element creates a  DaoAuthenticationProvider bean and the  <user-service> element creates an  InMemoryDaoImpl. All  authentication-provider elements must be children of the  <authentication-manager> element, which creates a  ProviderManager and registers the authentication providers with it. You can find more detailed information on the beans that are created in the  namespace appendix. It’s worth cross-checking this if you want to start understanding what the important classes in the framework are and how they are used, particularly if you want to customise things later. <authentication-provider>元素建立一個DaoAuthenticationProvider bean,<user-service>元素建立一個InMemoryDaoImpl。所有身份驗證提供程式元素都必須是<authentication-manager>元素的子元素,這會建立一個ProviderManager並向其註冊身份驗證提供程式。您可以在名稱空間附錄中找到有關bean建立的更多詳細資訊。如果您想要開始瞭解框架中的重要類以及它們的使用方式,特別是如果您想稍後自定義內容,則值得交叉檢查。   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  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. 上面的配置定義了兩個使用者,他們的密碼和他們在應用程式中的角色(將用於訪問控制)。還可以使用user-service上的properties屬性從標準屬性檔案載入使用者資訊。有關檔案格式的更多詳細資訊,請參閱記憶體中身份驗證部分。使用<authentication-provider>元素意味著身份驗證管理器將使用使用者資訊來處理身份驗證請求。您可以使用多個<authentication-provider>元素來定義不同的身份驗證源,並依次查閱每個身份驗證源。   At this point you should be able to start up your application and you will be required to log in to proceed. Try it out, or try experimenting with the "tutorial" sample application that comes with the project. 此時,您應該可以啟動應用程式,並且您將需要登入才能繼續。嘗試一下,或嘗試嘗試專案附帶的“教程”示例應用程式。