Spring Security"

From Documentation
m ((via JWB))
 
(7 intermediate revisions by 2 users not shown)
Line 18: Line 18:
 
We need to add dependencies for Spring Security and Maven's transitive dependency management can include all necessary dependencies of Spring for us.
 
We need to add dependencies for Spring Security and Maven's transitive dependency management can include all necessary dependencies of Spring for us.
  
<source lang='xml' high='4, 16, 21'>
+
<source lang='xml' highlight='4, 16, 21'>
 
<!-- Spring Security -->
 
<!-- Spring Security -->
 
<dependency>
 
<dependency>
Line 43: Line 43:
 
</dependency>
 
</dependency>
 
</source>
 
</source>
* Line 4: Becuase we use the security namespace in the application context, we need <tt>spring-security-config</tt>.
+
* Line 4: Becuase we use the security namespace in the application context, we need <code>spring-security-config</code>.
 
* Line 16: Spring-core depends on commons-logging.
 
* Line 16: Spring-core depends on commons-logging.
 
* Line 21: The cglib is optional. We add it because we use CGLIB-based class proxy.
 
* Line 21: The cglib is optional. We add it because we use CGLIB-based class proxy.
Line 53: Line 53:
 
== Spring ==
 
== Spring ==
  
Our example application also integrates Spring framework, the required configuration in <tt>web.xml</tt> is as follows:
+
Our example application also integrates Spring framework, the required configuration in <code>web.xml</code> is as follows:
  
 
'''web.xml'''
 
'''web.xml'''
Line 67: Line 67:
 
</source>
 
</source>
  
The <tt>ContextLoaderListener</tt> will load <tt>/WEB-INF/applicationContext.xml</tt> (Spring configuration file) by default, and we follow this convention so we don't need to add extra configuration in <tt>web.xml</tt>.
+
The <code>ContextLoaderListener</code> will load <code>/WEB-INF/applicationContext.xml</code> (Spring configuration file) by default, and we follow this convention so we don't need to add extra configuration in <code>web.xml</code>.
  
 
'''applicationContext.xml'''
 
'''applicationContext.xml'''
<source lang='xml' high='9, 11'>
+
<source lang='xml' highlight='9, 11'>
 
<?xml version="1.0" encoding="UTF-8"?>
 
<?xml version="1.0" encoding="UTF-8"?>
 
<beans xmlns="http://www.springframework.org/schema/beans"
 
<beans xmlns="http://www.springframework.org/schema/beans"
Line 90: Line 90:
 
== Security Namespace Configuration ==
 
== Security Namespace Configuration ==
  
The first configuration you should add to use Spring Security is a filter declaration in <tt>web.xml</tt>:
+
The first configuration you should add to use Spring Security is a filter declaration in <code>web.xml</code>:
  
 
<source lang='xml'>
 
<source lang='xml'>
Line 106: Line 106:
 
This filter is a hook into Spring Security's web infrastructure. It intercepts all requests and hands over them to be processed by Spring Security internal filters.
 
This filter is a hook into Spring Security's web infrastructure. It intercepts all requests and hands over them to be processed by Spring Security internal filters.
  
Namespace configuration has been supported by Spring framework since version 2.0 and it is an alternative configuration syntax which is closer to problem domain. It also can reduce configuration's complexity because one element may contain multiple beans and processing steps. To use the security namespace, you should have <tt>spring-security-config</tt> in your classpath and add the schema declaration to your application context file:
+
Namespace configuration has been supported by Spring framework since version 2.0 and it is an alternative configuration syntax which is closer to problem domain. It also can reduce configuration's complexity because one element may contain multiple beans and processing steps. To use the security namespace, you should have <code>spring-security-config</code> in your classpath and add the schema declaration to your application context file:
  
 
'''applicationContext-security.xml'''
 
'''applicationContext-security.xml'''
<source lang='xml' high='1,8, 12, 32,33'>
+
<source lang='xml' highlight='1,8, 12, 32,33'>
  
 
<beans:beans xmlns="http://www.springframework.org/schema/security"  
 
<beans:beans xmlns="http://www.springframework.org/schema/security"  
Line 153: Line 153:
 
Here we introduce some main elements and will leave the details in the subsequent sections.  
 
Here we introduce some main elements and will leave the details in the subsequent sections.  
  
* LIne 12: The <tt><http></tt> element is the parent for all web-related namespace functions and we use <tt>auto-config</tt> to save configuration efforts. We also create a HTTPS configuration sample in <tt>applicationContext-security.xml</tt>. Please see source code for details.
+
* LIne 12: The <code><http></code> element is the parent for all web-related namespace functions and we use <code>auto-config</code> to save configuration efforts. We also create a HTTPS configuration sample in <code>applicationContext-security.xml</code>. Please see source code for details.
  
* Line 32: Each Spring Security application which uses the namespace configuration must  include <tt><authentication-manager></tt> . It is responsible for registering the  <tt>AuthenticationManager</tt> which provides authentication services to the application.  
+
* Line 32: Each Spring Security application which uses the namespace configuration must  include <code><authentication-manager></code> . It is responsible for registering the  <code>AuthenticationManager</code> which provides authentication services to the application.  
* Line 33:We implement our <tt>MyUserDetailsService</tt> bean to provide authentication service and configure it in <tt><authentication-provider></tt> element.
+
* Line 33:We implement our <code>MyUserDetailsService</code> bean to provide authentication service and configure it in <code><authentication-provider></code> element.
  
 
= Secure Pages =
 
= Secure Pages =
  
In Spring Security, pages are protected by <tt><intercept-url></tt> element under <tt><http></tt>. We can specify in <tt>pattern</tt> to match against the URLs of incoming requests using an ant path style syntax in <tt><intercept-url> </tt> element. The  <tt>access</tt> attribute defines the access permission for requests which match the given <tt>pattern</tt>. Here we use simple role-based access control.
+
In Spring Security, pages are protected by <code><intercept-url></code> element under <code><http></code>. We can specify in <code>pattern</code> to match against the URLs of incoming requests using an ant path style syntax in <code><intercept-url></code> element. The  <code>access</code> attribute defines the access permission for requests which match the given <code>pattern</code>. Here we use simple role-based access control.
  
 
In most cases, we usually secure all pages with :
 
In most cases, we usually secure all pages with :
  
<tt> <intercept-url pattern="/**" access="ROLE_USER" /> </tt>
+
<code><intercept-url pattern="/**" access="ROLE_USER" /></code>
  
The "ROLE_USER" is an authority string we define and give for each authenticated user in our custom user service, <tt>MyUserDetailsService</tt>.
+
The "ROLE_USER" is an authority string we define and give for each authenticated user in our custom user service, <code>MyUserDetailsService</code>.
  
 
Then we can selectively allow some pages for anonymous access like:
 
Then we can selectively allow some pages for anonymous access like:
  
<tt> <intercept-url pattern="/login.zul" access="IS_AUTHENTICATED_ANONYMOUSLY" /></tt>
+
<code><intercept-url pattern="/login.zul" access="IS_AUTHENTICATED_ANONYMOUSLY" /></code>
  
<tt>IS_AUTHENTICATED_ANONYMOUSLY</tt> is a built-in permission value used to grant access to anonymous users
+
<code>IS_AUTHENTICATED_ANONYMOUSLY</code> is a built-in permission value used to grant access to anonymous users
  
 
'''applicationContext-security.xml'''
 
'''applicationContext-security.xml'''
<source lang='xml' high='4,6, 11'>
+
<source lang='xml' highlight='4,6, 11'>
 
  <!--  HTTP configuration sample -->
 
  <!--  HTTP configuration sample -->
 
<http auto-config="true">
 
<http auto-config="true">
Line 193: Line 193:
 
* Line 4: ZK AU requests must be available for anonymous access or ZK can't work normally.
 
* Line 4: ZK AU requests must be available for anonymous access or ZK can't work normally.
 
* Line 6: Remember to set login page URL available to anonymous users,  otherwise users wont be able to access the log-in page (this is a common configuration error).
 
* Line 6: Remember to set login page URL available to anonymous users,  otherwise users wont be able to access the log-in page (this is a common configuration error).
* Line 14: Restrict all page requests with permission <tt>ROLE_USER</tt>.
+
* Line 14: Restrict all page requests with permission <code>ROLE_USER</code>.
  
 
= Authentication =
 
= Authentication =
Line 200: Line 200:
 
-->
 
-->
  
Setting <tt>auto-config</tt> enables form-based login process automatically but it uses Spring Security's built-in login page. We usually build our own login page so we can specify our custom login page URL to override the default configuration.
+
Setting <code>auto-config</code> enables form-based login process automatically but it uses Spring Security's built-in login page. We usually build our own login page so we can specify our custom login page URL to override the default configuration.
  
 
'''applicationContext-security.xml'''
 
'''applicationContext-security.xml'''
<source lang='xml' high='5,6,8'>
+
<source lang='xml' highlight='5,6,8'>
  
 
  <!--  HTTP configuration sample -->
 
  <!--  HTTP configuration sample -->
Line 215: Line 215:
 
</http>  
 
</http>  
 
</source>
 
</source>
* Line 5: Specify the URL used to render the login page at <tt>login-page</tt>.
+
* Line 5: Specify the URL used to render the login page at <code>login-page</code>.
 
* Line 5: Specify the URL to redirect the browser on login failure,
 
* Line 5: Specify the URL to redirect the browser on login failure,
 
* Line 8: Specify the destination URL in which the user will be redirected to after logging out.  
 
* Line 8: Specify the destination URL in which the user will be redirected to after logging out.  
Line 222: Line 222:
  
 
'''login.zul'''
 
'''login.zul'''
<source lang='xml' high='2, 6,7'>
+
<source lang='xml' highlight='2, 6,7'>
  
 
...
 
...
Line 241: Line 241:
 
     </html:form>
 
     </html:form>
 
</source>
 
</source>
* Line 2: The default action URL monitored by Spring Security filter is <tt>j_spring_security_check</tt>.
+
* Line 2: The default action URL monitored by Spring Security filter is <code>j_spring_security_check</code>.
* Line 6,7: The login form should contain <tt>j_username</tt> and <tt>j_password</tt> input fields.
+
* Line 6,7: The login form should contain <code>j_username</code> and <code>j_password</code> input fields.
  
  
In most cases, each application will have its own way to authenticate a user and Spring Security provides various authentication provider to achieve it. We can create a simple <tt>MyUserDetailsService</tt> which implements Spring Security's <tt>UserDetailsService</tt> interface to perform our own authentication.  
+
In most cases, each application will have its own way to authenticate a user and Spring Security provides various authentication provider to achieve it. We can create a simple <code>MyUserDetailsService</code> which implements Spring Security's <code>UserDetailsService</code> interface to perform our own authentication.  
  
 
'''MyUserDetailsService '''
 
'''MyUserDetailsService '''
<source lang='java' high='10, 11'>
+
<source lang='java' highlight='10, 11'>
  
 
@Service
 
@Service
Line 279: Line 279:
 
}
 
}
 
</source>
 
</source>
* Line 10: <tt>MyUser</tt> extends <tt>org.springframework.security.core.userdetails.User</tt> which implements <tt>org.springframework.security.core.userdetails.UserDetails</tt>.
+
* Line 10: <code>MyUser</code> extends <code>org.springframework.security.core.userdetails.User</code> which implements <code>org.springframework.security.core.userdetails.UserDetails</code>.
* Line 11: Here we define two authorities, <tt>ROLE_USER</tt> and <tt>ROLE_EDITOR</tt>.
+
* Line 11: Here we define two authorities, <code>ROLE_USER</code> and <code>ROLE_EDITOR</code>.
  
  
Then specify <tt>user-service-ref</tt> with our <tt>MyUserDetailsService</tt>.
+
Then specify <code>user-service-ref</code> with our <code>MyUserDetailsService</code>.
  
 
'''applicationContext-security.xml'''
 
'''applicationContext-security.xml'''
<source lang='xml' high='2'>
+
<source lang='xml' highlight='2'>
  
 
<authentication-manager>
 
<authentication-manager>
Line 316: Line 316:
  
  
How do we achieve this security control in a zul? We can implement a custom tag library to check current user's authorities and apply the tag library on <tt>if</tt> or <tt>disable</tt> attribute. Please refer to [[ZUML_Reference/ZUML/Processing_Instructions/taglib/Custom_Taglib]] for details.
+
How do we achieve this security control in a zul? We can implement a custom tag library to check current user's authorities and apply the tag library on <code>if</code> or <code>disable</code> attribute. Please refer to [[ZUML_Reference/ZUML/Processing_Instructions/taglib/Custom_Taglib]] for details.
  
The tag library's function is implemented in <tt>org.zkoss.reference.developer.spring.security.SecurityUtil</tt>. Here we just briefly explain how <tt>isAllGranted()</tt> is implemented and you can read  other methods in the source code .  
+
The tag library's function is implemented in <code>org.zkoss.reference.developer.spring.security.SecurityUtil</code>. Here we just briefly explain how <code>isAllGranted()</code> is implemented and you can read  other methods in the source code .  
  
The <tt>SecurityContextHolder</tt> is the most fundamental object and is where Spring Security stores the present security context of the application, which includes details of the principal currently using the application. We can obtain user information from <tt>SecurityContextHolder</tt> including his authorities.
+
The <code>SecurityContextHolder</code> is the most fundamental object and is where Spring Security stores the present security context of the application, which includes details of the principal currently using the application. We can obtain user information from <code>SecurityContextHolder</code> including his authorities.
  
 
'''SecurityUtil.java'''
 
'''SecurityUtil.java'''
<source lang='java' high='7'>
+
<source lang='java' highlight='7'>
 
package org.zkoss.reference.developer.spring.security;
 
package org.zkoss.reference.developer.spring.security;
  
Line 356: Line 356:
 
* Line 7: Return true if the authenticated principal is granted ALL of the roles specified in authorities. The input parameter is a  comma separated list of roles which the user have been granted.
 
* Line 7: Return true if the authenticated principal is granted ALL of the roles specified in authorities. The input parameter is a  comma separated list of roles which the user have been granted.
  
Then we still have to write a description file to describe the functions that we can use in a zul. In our example, it is <tt>/WEB-INF/security.tld</tt>. You can read the file in the source code.
+
Then we still have to write a description file to describe the functions that we can use in a zul. In our example, it is <code>/WEB-INF/security.tld</code>. You can read the file in the source code.
  
 
'''security.tld'''
 
'''security.tld'''
<source lang='xml' high='8,9,10'>
+
<source lang='xml' highlight='8,9,10'>
 
<taglib>
 
<taglib>
 
<uri>http://www.zkoss.org/demo/integration/security</uri>
 
<uri>http://www.zkoss.org/demo/integration/security</uri>
Line 382: Line 382:
  
 
'''articleContent.zul'''
 
'''articleContent.zul'''
<source lang='xml' high='1,5,6'>
+
<source lang='xml' highlight='1,5,6'>
 
<?taglib uri="http://www.zkoss.org/zkspring/security" prefix="sec"?>
 
<?taglib uri="http://www.zkoss.org/zkspring/security" prefix="sec"?>
 
...
 
...
Line 393: Line 393:
 
* Line 1: Use a directive to load a custom tag library's tld file.
 
* Line 1: Use a directive to load a custom tag library's tld file.
 
* Line 5: Hide this button for anonymous users.
 
* Line 5: Hide this button for anonymous users.
* Line 6: Disable the button for those users without <tt>ROLE_EDITOR</tt> authority.
+
* Line 6: Disable the button for those users without <code>ROLE_EDITOR</code> authority.
  
The function <tt>isAllGranted()</tt> will return true if the authenticated principal is granted all of the roles specified in authorities. An anonymous user doesn't have authority "ROLE_USER", so the "Delete" button will not be created. If a user have authority "ROLE_EDITOR", he can see an enabled "Delete" button (the <tt>disable</tt> will be <tt>false</tt>).
+
The function <code>isAllGranted()</code> will return true if the authenticated principal is granted all of the roles specified in authorities. An anonymous user doesn't have authority "ROLE_USER", so the "Delete" button will not be created. If a user have authority "ROLE_EDITOR", he can see an enabled "Delete" button (the <code>disable</code> will be <code>false</code>).
  
  
You can use our <tt>SecurityUtil</tt> and <tt>security.tld</tt> as reference and write your own one to apply in your application.
+
You can use our <code>SecurityUtil</code> and <code>security.tld</code> as reference and write your own one to apply in your application.
  
 
= Secure Events =
 
= Secure Events =
Line 414: Line 414:
 
</source>
 
</source>
  
Then add <tt>@Secure</tt> to those methods you want to secure with permissions.
+
Then add <code>@Secure</code> to those methods you want to secure with permissions.
  
 
'''ArticleService.java'''
 
'''ArticleService.java'''
Line 437: Line 437:
 
</source>
 
</source>
  
If a user uses the service and has no permission, Spring Security will throw its <tt>AccessDeniedException</tt>.
+
If a user uses the service and has no permission, Spring Security will throw its <code>AccessDeniedException</code>.
  
  
Line 443: Line 443:
  
 
'''permission checking in an event listener'''
 
'''permission checking in an event listener'''
<source lang='java' high='9,10,11'>
+
<source lang='java' highlight='9,10,11'>
 
@VariableResolver(DelegatingVariableResolver.class)
 
@VariableResolver(DelegatingVariableResolver.class)
 
public class ArticleContentViewCtrl extends SelectorComposer<Component> {
 
public class ArticleContentViewCtrl extends SelectorComposer<Component> {
Line 462: Line 462:
 
}
 
}
 
</source>
 
</source>
* Line 9~11: If the current login user is neither the owner of the article nor has the authority "ROLE_EDITOR", we will not allow the editing of the article and throw a Spring Security's <tt>AccessDeniedException</tt>.
+
* Line 9~11: If the current login user is neither the owner of the article nor has the authority "ROLE_EDITOR", we will not allow the editing of the article and throw a Spring Security's <code>AccessDeniedException</code>.
  
  
 
If we throw a runtime exception for an access with insufficient permission, ZK will show the error message on the page by default. But for an unauthenticated user (not log in yet), we can even do more: redirect the anonymous user to the login page. We will show how to achieve this in ZK:  
 
If we throw a runtime exception for an access with insufficient permission, ZK will show the error message on the page by default. But for an unauthenticated user (not log in yet), we can even do more: redirect the anonymous user to the login page. We will show how to achieve this in ZK:  
  
First, we have to catch the exception thrown in an event listener by [[ZK%20Developer's%20Reference/UI%20Patterns/Error%20Handling| ZK error handling mechanism]], configure <tt><error-page></tt> in <tt>zk.xml</tt>.
+
First, we have to catch the exception thrown in an event listener by [[ZK%20Developer's%20Reference/UI%20Patterns/Error%20Handling| ZK error handling mechanism]], configure <code><error-page></code> in <code>zk.xml</code>.
  
 
'''zk.xml'''
 
'''zk.xml'''
<source lang='xml' high='2,3'>
+
<source lang='xml' highlight='2,3'>
  
 
<error-page>
 
<error-page>
Line 479: Line 479:
  
  
Then, create the error handling page. To avoid users visiting the page directly, we put it under <tt>/WEB-INF</tt>. This error handling page displays nothing but  a [[ZK Developer's Reference/UI Patterns/Page Initialization| page initiator]] to redirect an unauthenticated user to the login page.
+
Then, create the error handling page. To avoid users visiting the page directly, we put it under <code>/WEB-INF</code>. This error handling page displays nothing but  a [[ZK Developer's Reference/UI Patterns/Page Initialization| page initiator]] to redirect an unauthenticated user to the login page.
  
 
'''handleAccessDenied.zul'''
 
'''handleAccessDenied.zul'''
<source lang='xml' high='1'>
+
<source lang='xml' highlight='1'>
  
 
<?init class="org.zkoss.reference.developer.spring.security.ui.error.AjaxAccessDeniedHandler"?>
 
<?init class="org.zkoss.reference.developer.spring.security.ui.error.AjaxAccessDeniedHandler"?>
Line 511: Line 511:
 
}
 
}
 
</source>
 
</source>
 +
 +
= Login Page =
 +
If you implement a login page with zul, you need to configure Spring Security filter to ignore all AU requests (starting with <code>/zkau</code>). Because ZK framework communicates with a server via that channel for various things including firing events and getting resources. If the security filter blocks AU requests, your login page cannot work.
 +
 +
But not intercepting ZK AU requests is equivalent to opening an unchecked channel, which may result in security vulnerabilities.
 +
 +
== Non-ZK login entrypoint ==
 +
Hence, to ensure all zk components are under the security filter's protection, a good practice is to implement authentication without relying on ZK.
 +
 +
This can be done with form-based authentication by implementing the login form in HTML or JSP. And this can also be achieved with other authentication methods which don't require a ZK page to be served, such as redirecting to an external provider, using a SSO provider, etc.
 +
 +
With these options, the security filter doesn't have to be configured to allow anonymous access to ZK AU requests. After a user logs in, all requests including ZK AU can be intercepted by the security filter and rejected if the user is unauthorized or unauthenticated.
  
 
=Example Source Code =
 
=Example Source Code =
 
All source code of examples used in this chapter can be found in [https://github.com/zkoss/zkbooks/tree/master/developersreference/integration.spring.security here].
 
All source code of examples used in this chapter can be found in [https://github.com/zkoss/zkbooks/tree/master/developersreference/integration.spring.security here].
 
=Version History=
 
{{LastUpdated}}
 
{| class='wikitable' | width="100%"
 
! Version !! Date !! Content
 
|-
 
| 6.5.1
 
| March 2013
 
| Initial
 
|}
 
 
  
  
  
 
{{ZKDevelopersReferencePageFooter}}
 
{{ZKDevelopersReferencePageFooter}}

Latest revision as of 05:17, 13 July 2023



Overview

Spring Security is an application framework that provides security services for J2EE-based enterprise software application. It is a popular and widely adopted framework, in this article we will demonstrate how to integrate it to secure a ZK application including securing pages, handling authentication process, securing components, and securing events. Our example is a simple forum-like application. Users can read, create, edit, and delete an article according to his authorities.

Configuration

Maven

We need to add dependencies for Spring Security and Maven's transitive dependency management can include all necessary dependencies of Spring for us.

		<!-- Spring Security -->
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<version>${springsecurity.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
			<version>${springsecurity.version}</version>
		</dependency>

		<!-- extra -->
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1.1</version>
		</dependency>
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>2.2</version>
		</dependency>
  • Line 4: Becuase we use the security namespace in the application context, we need spring-security-config.
  • Line 16: Spring-core depends on commons-logging.
  • Line 21: The cglib is optional. We add it because we use CGLIB-based class proxy.

Icon info.png Note: If you don't use Maven, please refer to Spring Security Reference Documentation to check which JAR files are needed.

Spring

Our example application also integrates Spring framework, the required configuration in web.xml is as follows:

web.xml

	<!-- Loads the Spring application context configuration -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	 <!-- For using web scoped bean -->
	<listener>
		<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
	</listener>

The ContextLoaderListener will load /WEB-INF/applicationContext.xml (Spring configuration file) by default, and we follow this convention so we don't need to add extra configuration in web.xml.

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation=
	"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
	
	<context:component-scan base-package="org.zkoss.reference.developer.spring.security.model"/>

	<import resource="applicationContext-security.xml"/>
</beans>
  • Line 9: We can register beans by class-path scanning to reduce XML configuration effort.
  • Line 11: We can import another configuration file for Spring Security.

Security Namespace Configuration

The first configuration you should add to use Spring Security is a filter declaration in 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 filter is a hook into Spring Security's web infrastructure. It intercepts all requests and hands over them to be processed by Spring Security internal filters.

Namespace configuration has been supported by Spring framework since version 2.0 and it is an alternative configuration syntax which is closer to problem domain. It also can reduce configuration's complexity because one element may contain multiple beans and processing steps. To use the security namespace, you should have spring-security-config in your classpath and add the schema declaration to your application context file:

applicationContext-security.xml

<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" 
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation=
	"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
	 http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">


 	<!--  HTTP configuration sample -->
	<http auto-config="true">
		<!-- ZK AU reqeust -->
		<intercept-url pattern="/zkau/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
		<!-- the login page -->
		<intercept-url pattern="/login.zul" access="IS_AUTHENTICATED_ANONYMOUSLY" />
		<!-- pages for anonymous access in an application -->
		<intercept-url pattern="/index.zul" access="IS_AUTHENTICATED_ANONYMOUSLY" />
		<intercept-url pattern="/articleContent.zul" access="IS_AUTHENTICATED_ANONYMOUSLY" />
		<!-- secure pages -->
		<intercept-url pattern="/**" access="ROLE_USER" />
		
		<form-login login-page="/login.zul" 
			authentication-failure-url="/login.zul?login_error=1" 
			login-processing-url="/j_spring_security_check"/>
			
		<logout logout-success-url="/index.zul" invalidate-session="true" />
	</http> 	

	<!-- omit inactive configurations -->

	<authentication-manager>
		<authentication-provider user-service-ref="myUserDetailsService">
			<password-encoder hash="md5" />
		</authentication-provider>
	</authentication-manager>
	
</beans:beans>

Here we introduce some main elements and will leave the details in the subsequent sections.

  • LIne 12: The <http> element is the parent for all web-related namespace functions and we use auto-config to save configuration efforts. We also create a HTTPS configuration sample in applicationContext-security.xml. Please see source code for details.
  • Line 32: Each Spring Security application which uses the namespace configuration must include <authentication-manager> . It is responsible for registering the AuthenticationManager which provides authentication services to the application.
  • Line 33:We implement our MyUserDetailsService bean to provide authentication service and configure it in <authentication-provider> element.

Secure Pages

In Spring Security, pages are protected by <intercept-url> element under <http>. We can specify in pattern to match against the URLs of incoming requests using an ant path style syntax in <intercept-url> element. The access attribute defines the access permission for requests which match the given pattern. Here we use simple role-based access control.

In most cases, we usually secure all pages with :

<intercept-url pattern="/**" access="ROLE_USER" />

The "ROLE_USER" is an authority string we define and give for each authenticated user in our custom user service, MyUserDetailsService.

Then we can selectively allow some pages for anonymous access like:

<intercept-url pattern="/login.zul" access="IS_AUTHENTICATED_ANONYMOUSLY" />

IS_AUTHENTICATED_ANONYMOUSLY is a built-in permission value used to grant access to anonymous users

applicationContext-security.xml

 	<!--  HTTP configuration sample -->
	<http auto-config="true">
		<!-- ZK AU requests -->
		<intercept-url pattern="/zkau/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
		<!-- the login page -->
		<intercept-url pattern="/login.zul" access="IS_AUTHENTICATED_ANONYMOUSLY" />
		<!-- pages for anonymous access in an application -->
		<intercept-url pattern="/index.zul" access="IS_AUTHENTICATED_ANONYMOUSLY" />
		<intercept-url pattern="/articleContent.zul" access="IS_AUTHENTICATED_ANONYMOUSLY" />
		<!-- secure pages -->
		<intercept-url pattern="/**" access="ROLE_USER" />
		
		...
	</http>
  • Line 4: ZK AU requests must be available for anonymous access or ZK can't work normally.
  • Line 6: Remember to set login page URL available to anonymous users, otherwise users wont be able to access the log-in page (this is a common configuration error).
  • Line 14: Restrict all page requests with permission ROLE_USER.

Authentication

Setting auto-config enables form-based login process automatically but it uses Spring Security's built-in login page. We usually build our own login page so we can specify our custom login page URL to override the default configuration.

applicationContext-security.xml

 	<!--  HTTP configuration sample -->
	<http auto-config="true">
		...
		
		<form-login login-page="/login.zul" 
			authentication-failure-url="/login.zul?login_error=1" />
			
		<logout logout-success-url="/index.zul" invalidate-session="true" />
	</http>
  • Line 5: Specify the URL used to render the login page at login-page.
  • Line 5: Specify the URL to redirect the browser on login failure,
  • Line 8: Specify the destination URL in which the user will be redirected to after logging out.

In order to let Spring Security handle authentication, we should use HTML's form in a zul.

login.zul

	...
	<html:form action="j_spring_security_check" method="POST" 
		xmlns:html="native">
    	<grid>
    		<rows>
    			<row>User: <textbox id="u" name="j_username"/></row>
    			<row>Password: <textbox id="p" type="password" name="j_password"/></row>
    			<row spans="2">
    				<hbox>
    					<button type="reset" label="Reset" />
    					<button type="submit" label="Submit" />
    				</hbox>
    			</row>
    		</rows>
    	</grid>
    	</html:form>
  • Line 2: The default action URL monitored by Spring Security filter is j_spring_security_check.
  • Line 6,7: The login form should contain j_username and j_password input fields.


In most cases, each application will have its own way to authenticate a user and Spring Security provides various authentication provider to achieve it. We can create a simple MyUserDetailsService which implements Spring Security's UserDetailsService interface to perform our own authentication.

MyUserDetailsService

@Service
public class MyUserDetailsService implements UserDetailsService {

	private static final Map<String, MyUser> USERS = new HashMap<String,MyUser>();
	private static void add(MyUser mu){
		USERS.put(mu.getUsername(), mu);
	}
	static{
		
		add(new MyUser("rod","81dc9bdb52d04dc20036dbd8313ed055", //password:1234 
			new String[]{"ROLE_USER", "ROLE_EDITOR"} ));
		
		add(new MyUser("dianne","81dc9bdb52d04dc20036dbd8313ed055", 
			new String[]{"ROLE_USER", "ROLE_EDITOR"} ));
		
		add(new MyUser("scott","81dc9bdb52d04dc20036dbd8313ed055", 
			new String[]{"ROLE_USER"} ));
		
		add(new MyUser("peter","81dc9bdb52d04dc20036dbd8313ed055", 
			new String[]{"ROLE_USER"} ));
	}
	
	// must return a value or throw UsernameNotFoundException
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		//perform authentication
	}
}
  • Line 10: MyUser extends org.springframework.security.core.userdetails.User which implements org.springframework.security.core.userdetails.UserDetails.
  • Line 11: Here we define two authorities, ROLE_USER and ROLE_EDITOR.


Then specify user-service-ref with our MyUserDetailsService.

applicationContext-security.xml

	<authentication-manager>
		<authentication-provider user-service-ref="myUserDetailsService">
			<password-encoder hash="md5" />
		</authentication-provider>
	</authentication-manager>
  • LIne 2: Configure Spring Security to use our custom user service.

Secure Components

Every authenticated user has his/her own authorities. A common scenario is where we want to control UI's status according to current user's authorities. In our example, an anonymous user can only view an article, and a user with "ROLE_USER" can see a disabled "Delete" button. But a user with "ROLE_EDITOR" can see the "Delete" button and be able to click it.

Spring-security-anonymous.png
What a anonymous user see


Spring-security-user.png
What a user with "ROLE_USER" see


Spring-security-editor.png
What a user with "ROLE_EDITOR" see


How do we achieve this security control in a zul? We can implement a custom tag library to check current user's authorities and apply the tag library on if or disable attribute. Please refer to ZUML_Reference/ZUML/Processing_Instructions/taglib/Custom_Taglib for details.

The tag library's function is implemented in org.zkoss.reference.developer.spring.security.SecurityUtil. Here we just briefly explain how isAllGranted() is implemented and you can read other methods in the source code .

The SecurityContextHolder is the most fundamental object and is where Spring Security stores the present security context of the application, which includes details of the principal currently using the application. We can obtain user information from SecurityContextHolder including his authorities.

SecurityUtil.java

package org.zkoss.reference.developer.spring.security;

//omit import

public class SecurityUtil {

	public static boolean isAllGranted(String authorities) {
		if (null == authorities || "".equals(authorities)) {
			return false;
		}
		final Collection<? extends GrantedAuthority> granted = getPrincipalAuthorities();
		boolean isAllGranted = granted.containsAll(parseAuthorities(authorities)); 
		return isAllGranted;
	}

	private static Collection<? extends GrantedAuthority> getPrincipalAuthorities() {
		Authentication currentUser = SecurityContextHolder.getContext().getAuthentication();
		if (null == currentUser) {
			return Collections.emptyList();
		}
		if ((null == currentUser.getAuthorities()) || (currentUser.getAuthorities().isEmpty())) {
			return Collections.emptyList();
		}
		Collection<? extends GrantedAuthority> granted = currentUser.getAuthorities();
		return granted;
	}

	//omit other methods
}
  • Line 7: Return true if the authenticated principal is granted ALL of the roles specified in authorities. The input parameter is a comma separated list of roles which the user have been granted.

Then we still have to write a description file to describe the functions that we can use in a zul. In our example, it is /WEB-INF/security.tld. You can read the file in the source code.

security.tld

<taglib>
	<uri>http://www.zkoss.org/demo/integration/security</uri>
	<description>
		Methods and actions for ZK + Spring Security
	</description>

	<function>
		<name>isAllGranted</name>
		<function-class>org.zkoss.reference.developer.spring.security.SecurityUtil</function-class>
		<function-signature> boolean isAllGranted(java.lang.String authorities) 
		</function-signature>
		<description> 
			Return true if the authenticated principal is granted authorities of ALL the specified roles.
		</description>
	</function>
	...
</taglib>

Before using a tag library in a zul, we should load its tld file with a directive.

articleContent.zul

<?taglib uri="http://www.zkoss.org/zkspring/security" prefix="sec"?>
...

			<button id="deleteBtn" label="Delete"
			if="${sec:isAllGranted('ROLE_USER')}"
			disabled="${not sec:isAllGranted('ROLE_EDITOR')}"/>
  • Line 1: Use a directive to load a custom tag library's tld file.
  • Line 5: Hide this button for anonymous users.
  • Line 6: Disable the button for those users without ROLE_EDITOR authority.

The function isAllGranted() will return true if the authenticated principal is granted all of the roles specified in authorities. An anonymous user doesn't have authority "ROLE_USER", so the "Delete" button will not be created. If a user have authority "ROLE_EDITOR", he can see an enabled "Delete" button (the disable will be false).


You can use our SecurityUtil and security.tld as reference and write your own one to apply in your application.

Secure Events

If you want to restrict available actions according to a business rule or a dynamic status, this cannot be achieved by tag library. To do this, Spring Security provides a "method security" which can add security to your service layer methods. To use this feature, you should declare as follows:

applicationContext-security.xml

<global-method-security secured-annotations="enabled" />

Then add @Secure to those methods you want to secure with permissions.

ArticleService.java

public interface ArticleService {

	@Secured({"ROLE_USER", "IS_AUTHENTICATED_ANONYMOUSLY"})
	public List<Article> findAll();
	
	@Secured({"ROLE_USER", "IS_AUTHENTICATED_ANONYMOUSLY"})
	public Article find(long id);
	
	@Secured({"ROLE_USER"})
	public void create(Article a);
	
	@Secured({"ROLE_EDITOR","ROLE_USER"})
	public void update(Article a);
	
	@Secured({"ROLE_EDITOR"})
	public void delete(long id);
}

If a user uses the service and has no permission, Spring Security will throw its AccessDeniedException.


If the security checking is more dynamic and cannot be determined in compile time, we can check a user's permission in an event listener of a controller. In our example, a user with "ROLE_EDITOR" can edit any article but a user with "ROLE_USER" can only edit those articles written by himself/herself. We can check this when a user clicks the "Edit" button:

permission checking in an event listener

@VariableResolver(DelegatingVariableResolver.class)
public class ArticleContentViewCtrl extends SelectorComposer<Component> {

	//omit other methods

	@Listen("onClick=#openEditorBtn")
	public void edit(){
		//ownership & permission check.
		if(!(isOwner() || SecurityUtil.isAllGranted("ROLE_EDITOR"))){
			throw new AccessDeniedException(
				"The user is neither the author, nor a privileged user.");
		}
		ArticleEditor editor = new ArticleEditor();
		editor.setParent(container);
		editor.doHighlighted();
	}
}
  • Line 9~11: If the current login user is neither the owner of the article nor has the authority "ROLE_EDITOR", we will not allow the editing of the article and throw a Spring Security's AccessDeniedException.


If we throw a runtime exception for an access with insufficient permission, ZK will show the error message on the page by default. But for an unauthenticated user (not log in yet), we can even do more: redirect the anonymous user to the login page. We will show how to achieve this in ZK:

First, we have to catch the exception thrown in an event listener by ZK error handling mechanism, configure <error-page> in zk.xml.

zk.xml

	<error-page>
		<exception-type>org.springframework.security.access.AccessDeniedException</exception-type>
		<location>/WEB-INF/errors/handleAccessDenied.zul</location>
	</error-page>


Then, create the error handling page. To avoid users visiting the page directly, we put it under /WEB-INF. This error handling page displays nothing but a page initiator to redirect an unauthenticated user to the login page.

handleAccessDenied.zul

<?init class="org.zkoss.reference.developer.spring.security.ui.error.AjaxAccessDeniedHandler"?>
<zk>
<!-- Forward a unauthenticated user to login page. -->
</zk>


The page initiator redirects the browser to login page if current user principle doesn't exist, otherwise, it displays exception's detail in a custom page.

AjaxAccessDeniedHandler.java

public class AjaxAccessDeniedHandler extends GenericInitiator {

	public void doInit(Page page, Map<String, Object> args) throws Exception {
		// when this initiator has been executed that means users encounter access denied problem.
		
		Execution exec = Executions.getCurrent();
		
		if (null == SecurityUtil.getUser()){ //unauthenticated user
			exec.sendRedirect("/login.zul");
		}else{
			//display error's detail
			Executions.createComponents("/WEB-INF/errors/displayAccessDeniedException.zul", null, args);
		}
	}
}

Login Page

If you implement a login page with zul, you need to configure Spring Security filter to ignore all AU requests (starting with /zkau). Because ZK framework communicates with a server via that channel for various things including firing events and getting resources. If the security filter blocks AU requests, your login page cannot work.

But not intercepting ZK AU requests is equivalent to opening an unchecked channel, which may result in security vulnerabilities.

Non-ZK login entrypoint

Hence, to ensure all zk components are under the security filter's protection, a good practice is to implement authentication without relying on ZK.

This can be done with form-based authentication by implementing the login form in HTML or JSP. And this can also be achieved with other authentication methods which don't require a ZK page to be served, such as redirecting to an external provider, using a SSO provider, etc.

With these options, the security filter doesn't have to be configured to allow anonymous access to ZK AU requests. After a user logs in, all requests including ZK AU can be intercepted by the security filter and rejected if the user is unauthorized or unauthenticated.

Example Source Code

All source code of examples used in this chapter can be found in here.




Last Update : 2023/07/13

Copyright © Potix Corporation. This article is licensed under GNU Free Documentation License.