`
kobe学java
  • 浏览: 257441 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

spring security 配置详解

 
阅读更多

http://static.springsource.org/spring-security/site/docs/3.0.x/reference/appendix-namespace.html#nsa-form-login

 

 

revious versions of the framework when users had to configure the filter chain explicitly in theFilterChainProxy bean. You can, of course, still do this if you need full control of the configuration.

All filters which require a reference to the AuthenticationManager will be automatically injected with the internal instance created by the namespace configuration (see the introductory chapter for more on the AuthenticationManager).

The <http> namespace block always creates an SecurityContextPersistenceFilter, an ExceptionTranslationFilter and a FilterSecurityInterceptor. These are fixed and cannot be replaced with alternatives.

B.1.1 <http> Attributes

The attributes on the <http> element control some of the properties on the core filters.

servlet-api-provision

Provides versions of HttpServletRequest security methods such as isUserInRole() and getPrincipal() which are implemented by adding aSecurityContextHolderAwareRequestFilter bean to the stack. Defaults to "true".

path-type

Controls whether URL patterns are interpreted as ant paths (the default) or regular expressions. In practice this sets a particular UrlMatcher instance on theFilterChainProxy.

lowercase-comparisons

Whether test URLs should be converted to lower case prior to comparing with defined path patterns. If unspecified, defaults to "true"

realm

Sets the realm name used for basic authentication (if enabled). Corresponds to the realmName property on BasicAuthenticationEntryPoint.

entry-point-ref

Normally the AuthenticationEntryPoint used will be set depending on which authentication mechanisms have been configured. This attribute allows this behaviour to be overridden by defining a customized AuthenticationEntryPoint bean which will start the authentication process.

access-decision-manager-ref

Optional attribute specifying the ID of the AccessDecisionManager implementation which should be used for authorizing HTTP requests. By default anAffirmativeBased implementation is used for with a RoleVoter and an AuthenticatedVoter.

access-denied-page

Deprecated in favour of the access-denied-handler child element.

once-per-request

Corresponds to the observeOncePerRequest property of FilterSecurityInterceptor. Defaults to "true".

create-session

Controls the eagerness with which an HTTP session is created. If not set, defaults to "ifRequired". Other options are "always" and "never". The setting of this attribute affect the allowSessionCreation and forceEagerSessionCreation properties of SecurityContextPersistenceFilterallowSessionCreation will always be true unless this attribute is set to "never". forceEagerSessionCreation is "false" unless it is set to "always". So the default configuration allows session creation but does not force it. The exception is if concurrent session control is enabled, when forceEagerSessionCreation will be set to true, regardless of what the setting is here. Using "never" would then cause an exception during the initialization of SecurityContextPersistenceFilter.

use-expressions

Enables EL-expressions in the access attribute, as described in the chapter on expression-based access-control.

disable-url-rewriting

Prevents session IDs from being appended to URLs in the application. Clients must use cookies if this attribute is set to true.

B.1.2 <access-denied-handler>

This element allows you to set the errorPage property for the default AccessDeniedHandler used by the ExceptionTranslationFilter, (using the error-page attribute, or to supply your own implementation using the ref attribute. This is discussed in more detail in the section on the ExceptionTranslationFilter.

B.1.3 The <intercept-url> Element

This element is used to define the set of URL patterns that the application is interested in and to configure how they should be handled. It is used to construct the FilterInvocationSecurityMetadataSource used by the FilterSecurityInterceptor and to exclude particular patterns from the filter chain entirely (by setting the attribute filters="none"). It is also responsible for configuring a ChannelAuthenticationFilter if particular URLs need to be accessed by HTTPS, for example. When matching the specified patterns against an incoming request, the matching is done in the order in which the elements are declared. So the most specific matches patterns should come first and the most general should come last.

pattern

The pattern which defines the URL path. The content will depend on the path-type attribute from the containing http element, so will default to ant path syntax.

method

The HTTP Method which will be used in combination with the pattern to match an incoming request. If omitted, any method will match. If an identical pattern is specified with and without a method, the method-specific match will take precedence.

access

Lists the access attributes which will be stored in the FilterInvocationSecurityMetadataSource for the defined URL pattern/method combination. This should be a comma-separated list of the security configuration attributes (such as role names).

requires-channel

Can be http or https depending on whether a particular URL pattern should be accessed over HTTP or HTTPS respectively. Alternatively the value anycan be used when there is no preference. If this attribute is present on any <intercept-url> element, then a ChannelAuthenticationFilter will be added to the filter stack and its additional dependencies added to the application context.

If a <port-mappings> configuration is added, this will be used to by the SecureChannelProcessor and InsecureChannelProcessor beans to determine the ports used for redirecting to HTTP/HTTPS.

filters

Can only take the value none. This will cause any matching request to bypass the Spring Security filter chain entirely. None of the rest of the <http>configuration will have any effect on the request and there will be no security context available for its duration. Access to secured methods during the request will fail.

B.1.4 The <port-mappings> Element

By default, an instance of PortMapperImpl will be added to the configuration for use in redirecting to secure and insecure URLs. This element can optionally be used to override the default mappings which that class defines. Each child <port-mapping> element defines a pair of HTTP:HTTPS ports. The default mappings are 80:443 and 8080:8443. An example of overriding these can be found in the namespace introduction.

B.1.5 The <form-login> Element

Used to add an UsernamePasswordAuthenticationFilter to the filter stack and an LoginUrlAuthenticationEntryPoint to the application context to provide authentication on demand. This will always take precedence over other namespace-created entry points. If no attributes are supplied, a login page will be generated automatically at the URL "/spring-security-login" [20] The behaviour can be customized using the following attributes.

login-page

The URL that should be used to render the login page. Maps to the loginFormUrl property of the LoginUrlAuthenticationEntryPoint. Defaults to "/spring-security-login".

login-processing-url

Maps to the filterProcessesUrl property of UsernamePasswordAuthenticationFilter. The default value is "/j_spring_security_check".

default-target-url

Maps to the defaultTargetUrl property of UsernamePasswordAuthenticationFilter. If not set, the default value is "/" (the application root). A user will be taken to this URL after logging in, provided they were not asked to login while attempting to access a secured resource, when they will be taken to the originally requested URL.

always-use-default-target

If set to "true", the user will always start at the value given by default-target-url, regardless of how they arrived at the login page. Maps to thealwaysUseDefaultTargetUrl property of UsernamePasswordAuthenticationFilter. Default value is "false".

authentication-failure-url

Maps to the authenticationFailureUrl property of UsernamePasswordAuthenticationFilter. Defines the URL the browser will be redirected to on login failure. Defaults to "/spring_security_login?login_error", which will be automatically handled by the automatic login page generator, re-rendering the login page with an error message.

authentication-success-handler-ref

This can be used as an alternative to default-target-url and always-use-default-target, giving you full control over the navigation flow after a successful authentication. The value should be he name of an AuthenticationSuccessHandler bean in the application context.

authentication-failure-handler-ref

Can be used as an alternative to authentication-failure-url, giving you full control over the navigation flow after an authentication failure. The value should be he name of an AuthenticationFailureHandler bean in the application context.

B.1.6 The <http-basic> Element

Adds a BasicAuthenticationFilter and BasicAuthenticationEntryPoint to the configuration. The latter will only be used as the configuration entry point if form-based login is not enabled.

B.1.7 The <remember-me> Element

Adds the RememberMeAuthenticationFilter to the stack. This in turn will be configured with either a TokenBasedRememberMeServices, aPersistentTokenBasedRememberMeServices or a user-specified bean implementing RememberMeServices depending on the attribute settings.

data-source-ref

If this is set, PersistentTokenBasedRememberMeServices will be used and configured with a JdbcTokenRepositoryImpl instance.

token-repository-ref

Configures a PersistentTokenBasedRememberMeServices but allows the use of a custom PersistentTokenRepository bean.

services-ref

Allows complete control of the RememberMeServices implementation that will be used by the filter. The value should be the Id of a bean in the application context which implements this interface.

token-repository-ref

Configures a PersistentTokenBasedRememberMeServices but allows the use of a custom PersistentTokenRepository bean.

The key Attribute

Maps to the "key" property of AbstractRememberMeServices. Should be set to a unique value to ensure that remember-me cookies are only valid within the one application [21].

token-validity-seconds

Maps to the tokenValiditySeconds property of AbstractRememberMeServices. Specifies the period in seconds for which the remember-me cookie should be valid. By default it will be valid for 14 days.

user-service-ref

The remember-me services implementations require access to a UserDetailsService, so there has to be one defined in the application context. If there is only one, it will be selected and used automatically by the namespace configuration. If there are multiple instances, you can specify a bean Id explicitly using this attribute.

B.1.8 The <session-management> Element

Session-management related functionality is implemented by the addition of a SessionManagementFilter to the filter stack.

session-fixation-protection

Indicates whether an existing session should be invalidated when a user authenticates and a new session started. If set to "none" no change will be made. "newSession" will create a new empty session. "migrateSession" will create a new session and copy the session attributes to the new session. Defaults to "migrateSession".

If session fixation protection is enabled, the SessionManagementFilter is injected with an appropriately configured DefaultSessionAuthenticationStrategy. See the Javadoc for this class for more details.

B.1.9 The <concurrency-control> Element

Adds support for concurrent session control, allowing limits to be placed on the number of active sessions a user can have. A ConcurrentSessionFilter will be created, and a ConcurrentSessionControlStrategy will be used with the SessionManagementFilter. If a form-login element has been declared, the strategy object will also be injected into the created authentication filter. An instance of SessionRegistry (a SessionRegistryImpl instance unless the user wishes to use a custom bean) will be created for use by the strategy.

The max-sessions attribute

Maps to the maximumSessions property of ConcurrentSessionControlStrategy.

The expired-url attribute

The URL a user will be redirected to if they attempt to use a session which has been "expired" by the concurrent session controller because the user has exceeded the number of allowed sessions and has logged in again elsewhere. Should be set unless exception-if-maximum-exceeded is set. If no value is supplied, an expiry message will just be written directly back to the response.

The error-if-maximum-exceeded attribute

If set to "true" a SessionAuthenticationException will be raised when a user attempts to exceed the maximum allowed number of sessions. The default behaviour is to expire the original session.

The session-registry-alias and session-registry-ref attributes

The user can supply their own SessionRegistry implementation using the session-registry-ref attribute. The other concurrent session control beans will be wired up to use it.

It can also be useful to have a reference to the internal session registry for use in your own beans or an admin interface. You can expose the interal bean using the session-registry-alias attribute, giving it a name that you can use elsewhere in your configuration.

B.1.10 The <anonymous> Element

Adds an AnonymousAuthenticationFilter to the stack and an AnonymousAuthenticationProvider. Required if you are using the IS_AUTHENTICATED_ANONYMOUSLYattribute.

B.1.11 The <x509> Element

Adds support for X.509 authentication. An X509AuthenticationFilter will be added to the stack and an Http403ForbiddenEntryPoint bean will be created. The latter will only be used if no other authentication mechanisms are in use (it's only functionality is to return an HTTP 403 error code). APreAuthenticatedAuthenticationProvider will also be created which delegates the loading of user authorities to a UserDetailsService.

The subject-principal-regex attribute

Defines a regular expression which will be used to extract the username from the certificate (for use with the UserDetailsService).

The user-service-ref attribute

Allows a specific UserDetailsService to be used with X.509 in the case where multiple instances are configured. If not set, an attempt will be made to locate a suitable instance automatically and use that.

B.1.12 The <openid-login> Element

Similar to <form-login> and has the same attributes. The default value for login-processing-url is "/j_spring_openid_security_check". AnOpenIDAuthenticationFilter and OpenIDAuthenticationProvider will be registered. The latter requires a reference to a UserDetailsService. Again, this can be specified by Id, using the user-service-ref attribute, or will be located automatically in the application context.

B.1.13 The <logout> Element

Adds a LogoutFilter to the filter stack. This is configured with a SecurityContextLogoutHandler.

The logout-url attribute

The URL which will cause a logout (i.e. which will be processed by the filter). Defaults to "/j_spring_security_logout".

The logout-success-url attribute

The destination URL which the user will be taken to after logging out. Defaults to "/".

The invalidate-session attribute

Maps to the invalidateHttpSession of the SecurityContextLogoutHandler. Defaults to "true", so the session will be invalidated on logout.

B.1.14 The <custom-filter> Element

This element is used to add a filter to the filter chain. It doesn't create any additional beans but is used to select a bean of type javax.servlet.Filter which is already defined in the appllication context and add that at a particular position in the filter chain maintained by Spring Security. Full details can be found in the namespace chapter.

B.1.15 The request-cache Element

Sets the RequestCache instance which will be used by the ExceptionTranslationFilter to store request information before invoking an AuthenticationEntryPoint.

B.1.16 The <http-firewall> Element

This is a top-level element which can be used to inject a custom implementation of HttpFirewall into the FilterChainProxy created by the namespace. The default implementation should be suitable for most applications.

B.2 Authentication Services

Before Spring Security 3.0, an AuthenticationManager was automatically registered internally. Now you must register one explicitly using the <authentication-manager> element. This creates an instance of Spring Security's ProviderManager class, which needs to be configured with a list of one or moreAuthenticationProvider instances. These can either be created using syntax elements provided by the namespace, or they can be standard bean definitions, marked for addition to the list using the authentication-provider element.

B.2.1 The <authentication-manager> Element

Every Spring Security application which uses the namespace must have include this element somewhere. It is responsible for registering theAuthenticationManager which provides authentication services to the application. It also allows you to define an alias name for the internal instance for use in your own configuration. Its use is described in the namespace introduction. All elements which create AuthenticationProvider instances should be children of this element.

The element also exposes an erase-credentials attribute which maps to the eraseCredentialsAfterAuthentication property of the ProviderManager. This is discussed in the Core Services chapter.

The <authentication-provider> Element

Unless used with a ref attribute, this element is shorthand for configuring a DaoAuthenticationProviderDaoAuthenticationProvider loads user information from aUserDetailsService and compares the username/password combination with the values supplied at login. The UserDetailsService instance can be defined either by using an available namespace element (jdbc-user-service or by using the user-service-ref attribute to point to a bean defined elsewhere in the application context). You can find examples of these variations in the namespace introduction.

The <password-encoder> Element

Authentication providers can optionally be configured to use a password encoder as described in the namespace introduction. This will result in the bean being injected with the appropriate PasswordEncoder instance, potentially with an accompanying SaltSource bean to provide salt values for hashing.

Using <authentication-provider> to refer to an AuthenticationProvider Bean

If you have written your own AuthenticationProvider implementation (or want to configure one of Spring Security's own implementations as a traditional bean for some reason, then you can use the following syntax to add it to the internal ProviderManager's list:

  <security:authentication-manager>
    <security:authentication-provider ref="myAuthenticationProvider" />
  </security:authentication-manager>
  <bean id="myAuthenticationProvider" class="com.something.MyAuthenticationProvider"/>
  

B.3 Method Security

B.3.1 The <global-method-security> Element

This element is the primary means of adding support for securing methods on Spring Security beans. Methods can be secured by the use of annotations (defined at the interface or class level) or by defining a set of pointcuts as child elements, using AspectJ syntax.

Method security uses the same AccessDecisionManager configuration as web security, but this can be overridden as explained above the section called “access-decision-manager-ref, using the same attribute.

The secured-annotations and jsr250-annotations Attributes

Setting these to "true" will enable support for Spring Security's own @Secured annotations and JSR-250 annotations, respectively. They are both disabled by default. Use of JSR-250 annotations also adds a Jsr250Voter to the AccessDecisionManager, so you need to make sure you do this if you are using a custom implementation and want to use these annotations.

Securing Methods using <protect-pointcut>

Rather than defining security attributes on an individual method or class basis using the @Secured annotation, you can define cross-cutting security constraints across whole sets of methods and interfaces in your service layer using the <protect-pointcut> element. This has two attributes:

  • expression - the pointcut expression

  • access - the security attributes which apply

You can find an example in the namespace introduction.

The <after-invocation-provider> Element

This element can be used to decorate an AfterInvocationProvider for use by the security interceptor maintained by the <global-method-security> namespace. You can define zero or more of these within the global-method-security element, each with a ref attribute pointing to an AfterInvocationProvider bean instance within your application context.

B.3.2 LDAP Namespace Options

LDAP is covered in some details in its own chapter. We will expand on that here with some explanation of how the namespace options map to Spring beans. The LDAP implementation uses Spring LDAP extensively, so some familiarity with that project's API may be useful.

Defining the LDAP Server using the <ldap-server> Element

This element sets up a Spring LDAP ContextSource for use by the other LDAP beans, defining the location of the LDAP server and other information (such as a username and password, if it doesn't allow anonymous access) for connecting to it. It can also be used to create an embedded server for testing. Details of the syntax for both options are covered in the LDAP chapter. The actual ContextSource implementation is DefaultSpringSecurityContextSource which extends Spring LDAP's LdapContextSource class. The manager-dn and manager-password attributes map to the latter's userDn and password properties respectively.

If you only have one server defined in your application context, the other LDAP namespace-defined beans will use it automatically. Otherwise, you can give the element an "id" attribute and refer to it from other namespace beans using the server-ref attribute. This is actually the bean id of the ContextSource instance, if you want to use it in other traditional Spring beans.

The <ldap-provider> Element

This element is shorthand for the creation of an LdapAuthenticationProvider instance. By default this will be configured with a BindAuthenticator instance and aDefaultAuthoritiesPopulator. As with all namespace authentication providers, it must be included as a child of the authentication-provider element.

The user-dn-pattern Attribute

If your users are at a fixed location in the directory (i.e. you can work out the DN directly from the username without doing a directory search), you can use this attribute to map directly to the DN. It maps directly to the userDnPatterns property of AbstractLdapAuthenticator.

The user-search-base and user-search-filter Attributes

If you need to perform a search to locate the user in the directory, then you can set these attributes to control the search. The BindAuthenticator will be configured with a FilterBasedLdapUserSearch and the attribute values map directly to the first two arguments of that bean's constructor. If these attributes aren't set and no user-dn-pattern has been supplied as an alternative, then the default search values of user-search-filter="(uid={0})" and user-search-base="" will be used.

group-search-filtergroup-search-basegroup-role-attribute and role-prefix Attributes

The value of group-search-base is mapped to the groupSearchBase constructor argument of DefaultAuthoritiesPopulator and defaults to "ou=groups". The default filter value is "(uniqueMember={0})", which assumes that the entry is of type "groupOfUniqueNames". group-role-attribute maps to the groupRoleAttributeattribute and defaults to "cn". Similarly role-prefix maps to rolePrefix and defaults to "ROLE_".

The <password-compare> Element

This is used as child element to <ldap-provider> and switches the authentication strategy from BindAuthenticator to PasswordComparisonAuthenticator. This can optionally be supplied with a hash attribute or with a child <password-encoder> element to hash the password before submitting it to the directory for comparison.

The <ldap-user-service> Element

This element configures an LDAP UserDetailsService. The class used is LdapUserDetailsService which is a combination of a FilterBasedLdapUserSearch and aDefaultAuthoritiesPopulator. The attributes it supports have the same usage as in <ldap-provider>.

 

分享到:
评论

相关推荐

    springsecurity使用配置详解

    在提供的压缩包`springsecurity配置demo`中,你将找到示例代码和详细说明,这将帮助你更好地理解和实践上述概念。通过学习和实践这些示例,你将能够为自己的Spring应用程序构建强大的安全防护。

    SPRING SECURITY配置

    **Spring Security配置详解** Spring Security是一款强大的安全框架,它为Java应用提供了全面的安全服务,包括认证、授权和访问控制。本文将深入探讨Spring Security的核心概念、配置方式以及常见应用场景。 ### 1...

    Spring Security 基本使用和配置代码

    这是自定义Spring Security配置的主要地方。你可以重写`configure(HttpSecurity http)`方法来定义HTTP安全规则。 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends ...

    Spring Security UserDetails实现原理详解

    只需在项目中引入`spring-boot-starter-security`依赖,Spring Boot就会自动配置安全功能。如果需要监控Spring Security的状态,可以添加`spring-boot-starter-actuator`。此外,还需要`spring-boot-starter-web`来...

    spring-security多登录页面配置

    ### Spring Security 多登录页面配置详解 在许多大型企业级应用中,为了更好地实现权限管理和用户体验,往往会采用多个登录页面的方式来进行用户身份验证。这种方式能够有效地将不同类型的用户(如前台用户、后台...

    SpringBoot + Spring Security 基本使用及个性化登录配置详解

    SpringBoot + Spring Security 基本使用及个性化登录配置详解 Spring Security 是一个功能强大且灵活的安全框架,它提供了认证、授权、攻击防护等功能。SpringBoot 是一个基于 Spring 框架的框架,它提供了很多便捷...

    spring security配置实例

    ### Spring Security配置实例详解 #### 一、Spring Security简介与应用场景 Spring Security 是一个功能强大的安全框架,提供了全面的安全服务,支持认证、授权以及其他安全服务。它为开发人员提供了高度可定制化...

    spring-security-reference

    #### 二、Spring Security 配置详解 ##### 2.1 安全命名空间配置介绍 Spring Security 支持通过 XML 或 Java 配置的方式进行设置。XML 配置文件中引入了特定的安全命名空间,使得配置更加直观和简洁。设计该命名...

    Spring Security OAuth2认证授权示例详解

    Spring Security OAuth2是一个强大的安全框架,它为Web应用程序提供了安全认证和授权的功能。OAuth2则是一种开放标准,允许用户授权第三方应用访问他们存储在另一服务提供商的数据,而无需分享他们的用户名和密码。...

    Spring Security 3多用户登录实现一

    **Spring Security 3 多用户登录实现详解** Spring Security 是一个强大的、高度可定制的身份验证和访问控制框架,广泛应用于Java EE平台上的安全解决方案。在本文中,我们将深入探讨如何在Spring Security 3中实现...

    详解spring security 配置多个AuthenticationProvider

    Spring Security 配置多个 AuthenticationProvider 详解 Spring Security 是一个功能强大且灵活的安全框架,提供了多种身份验证机制和访问控制机制。在实际开发中,我们经常需要配置多个身份验证提供程序...

    spring security 3.0.5中文详解

    ### Spring Security 3.0.5中文详解 #### 一、Spring Security简介 Spring Security是一种基于Spring AOP和Servlet过滤器的安全框架,旨在为应用程序提供全面的安全性解决方案。该框架能够在Web请求级别和方法调用...

    Spring_Security_多页面登录配置教程

    #### 三、多页面登录配置详解 多页面登录指的是允许用户通过不同的登录页面进行身份验证的过程。例如,一个电子商务网站可能需要为普通用户和管理员分别提供不同的登录界面。下面将详细解释如何实现这一功能: ####...

    Spring Security模块

    **Spring Security 模块详解** Spring Security 是一个强大的且高度可定制的身份验证和访问控制框架,主要用于构建安全的 Java Web 应用程序。它提供了一套全面的安全解决方案,包括身份验证、授权、会话管理以及跨...

    springsecurity入门实例

    **Spring Security 入门实例详解** Spring Security 是一个强大的安全框架,用于保护基于 Java 的 Web 应用程序。它提供了一套完整的访问控制和身份验证机制,帮助开发者处理应用程序的安全需求。本教程将引导你...

    SpringSecurity_day03.pdf

    最后,我们需要提供一个Spring Security配置类来覆盖默认的行为。 ```java import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders....

    Spring Security 新手入门级maven实例

    **Spring Security新手入门级Maven实例详解** Spring Security是一个强大且高度可定制的身份验证和访问控制框架,用于Java和Java EE应用。它为应用程序提供了全面的安全解决方案,包括用户认证、授权以及安全配置。...

    spring security4登陆例子

    为了使Spring Security配置生效,我们需要通过`SecurityWebApplicationInitializer`类来注册我们的`SecurityConfig`配置类。 ```java package core.security; import org.springframework.security.web.context....

Global site tag (gtag.js) - Google Analytics