Learning Monk

March 14, 2009

How to write testcase for spring security defined by annotations

Filed under: junit, security, spring — Tags: , , , — gnandiga @ 3:04 pm

Creating testcases in spring is very simple. Sometimes it is so simple that, it is never documneted thinking that everybody would just get it. I tried to search for a solution/tutorial/example to create a good testcase for the spring security annotations, and couldnot find any. After reading some the spring security forum, I came to conclusion that I need to document this.

The Big Question: How do you know that a method is called with the right security permissions?

Step 1: Create your test context.

Create a  test-context.xml with the following application context.

<?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:sec="http://www.springframework.org/schema/security"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-2.5.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security-2.0.xsd">

    <context:annotation-config/>

    <!--Services-->
    <context:component-scan base-package="com.company.name.service" />

    <!--Set method level security, very important to set secured-annotations="enabled"-->
    <global-method-security secured-annotations="enabled" access-decision-manager-ref="accessDecisionManager"/>

    <bean id="accessDecisionManager" class="org.springframework.security.vote.AffirmativeBased">
<property name="allowIfAllAbstainDecisions" value="false"/>
<property name="decisionVoters">
	<list>
                <bean class="org.springframework.security.vote.RoleVoter"/>
            </list>
        </property>
    </bean>
</beans>

Step 2: Create your service with the security annotations


public interface MyService
{
    @Secured({"ROLE_USER"})
    public Object securedServiceCall();
}

Step 3: Create your testcase to load the test-context.xml, and test the service.


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:test-context.xml"})
public class ServiceSecurityAccessTestCase
{
    @Autowired
    private MyService myService;

    @Test
    public void testSimServiceSecured() throws Exception
    {
        GrantedAuthority[] authorities = {new GrantedAuthorityImpl("ROLE_ANONYMOUS")};
        SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken("key", "Any Object", authorities));
        try
        {
            myService.securedServiceCall();
            Assert.fail("The service access should not be granted.");
        } catch (AccessDeniedException e)
        {
            //Your Assertions
        }

    }
}

Vola!. You have your test case for the annotaion based security system.

Advertisements

March 13, 2009

How many palces do you have to set Character encoding for a site

Filed under: spring, tomcat — Tags: — gnandiga @ 12:33 am

I was recently trying to provide character encoding “UTF-8” to our site. This is spring application running on tomcat. We are using velocity templating engine, with mysql backend.

To complete the loop, I had to do all of the following

  1. Update tomcat character encoding setting
  2. Add Filter to set Request objects character encoding
  3. Update Spring VelocityViewResolver to set content-type with correct character encoding
  4. Set character encoding for the database connection
  5. Set character encoding in the database

Update tomcat character encoding setting

In the tomcat server, edit the conf/server.xml to set URIEncoding

        <Connector connectionTimeout="20000" port="80" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/>

Add Filter to set Request objects character encoding

Add the following filter to the web.xml in the tomcat application. If you dont use the spring framework, create a Filter extending the javax.servlet.Filter to set the character encoding on HttpServletRequest to UTF-8


<filter>
    <filter-name>Spring character encoding filter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
    </init-param>
    <init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
    </init-param>
</filter>

Update Spring VelocityLayoutViewResolver to set content-type with correct character encoding

<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver">
<property name="contentType" value="text/html;charset=UTF-8"></property>
</bean>

Set character encoding for the database connection

jdbc:mysql://${database.host}:3306/${database.name}?maxQuerySizeToLog=10000&dumpQueriesOnException=true&useUnicode=true&characterEncoding=UTF-8&includeInnodbStatusInDeadlockExceptions=true

Set character encoding in the database

ALTER TABLE tbl_name DEFAULT CHARACTER SET 'utf8';

Blog at WordPress.com.