Sunday, May 27, 2012

Spring ACL based permission management

Key Concepts
Spring Security's domain object instance security capabilities center on the concept of an access control  list  (ACL). Every domain object instance in your system has its own ACL, and the ACL records details of  ho can and can't work with that domain object. With this in mind, Spring Security delivers three main  CL-related  capabilities to your application :
  • A way of efficiently retrieving ACL entries for all of your domain objects (and modifying those  CLs)
  •  A way of ensuring a given principal is permitted to work with your objects, before methods  re called
  •  A way of ensuring a given principal is permitted to work with your objects (or something they  return), after methods are called.
The tables are presented below in order of size in a typical Spring Security ACL deployment, with the table with the most rows listed last :
  • ACL_SID allows us to uniquely identify any principal or authority in the system ("SID" stands for "security identity"). The only columns are the ID, a textual representation of the SID, and a flag to indicate whether the textual representation refers to a principal name or a GrantedAuthority. Thus, there is a single row for each unique principal or GrantedAuthority. When used in the context of receiving a permission, a SID is generally called a "recipient".
  •  ACL_CLASS allows us to uniquely identify any domain object class in the system. The only columns are the ID and the Java class name. Thus, there is a single row for each unique Class we wish to store ACL permissions for.
  •  ACL_OBJECT_IDENTITY stores information for each unique domain object instance in the system. Columns include the ID, a foreign key to the ACL_CLASS table, a unique identifier so we know which ACL_CLASS instance we're providing information for, the parent, a foreign key to the ACL_SID table to represent the owner of the domain object instance, and whether we allow ACL entries to inherit from any parent ACL. We have a single row for every domain object instance we're storing ACL permissions for.
  •  Finally, ACL_ENTRY stores the individual permissions assigned to each recipient. Columns include a foreign key to the ACL_OBJECT_IDENTITY, the recipient (ie a foreign key to ACL_SID), whether we'll be auditing or not, and the integer bit mask that represents the actual permission being granted or denied. We have a single row for every recipient that receives a permission to work with a domain object.
Now that we've provided a basic overview of what the ACL system does, and what it looks like at a table structure, let's explore the key interfaces. The key interfaces are:
  • Acl: Every domain object has one and only one  Acl object, which internally holds the AccessControlEntrys as well as knows the owner of the Acl. An Acl does not refer directly to the domain object, but instead to an ObjectIdentity. The Acl is stored in the ACL_OBJECT_IDENTITY table.
  •  AccessControlEntry: An  Acl holds multiple  AccessControlEntrys, which are often abbreviated as ACEs in the framework. Each ACE refers to a specific tuple of Permission, Sid and Acl. An ACE an also be granting or non-granting and contain audit settings. The ACE is stored in the ACL_ENTRY table.
  •  Permission: A permission represents a particular immutable bit mask, and offers convenience functions for bit masking and outputting information. The basic permissions presented above (bits 0 through 4) are contained in the BasePermission class.
  •  Sid: The ACL module needs to refer to principals and  GrantedAuthority[]s. A level of indirection is provided by the Sid interface, which is an abbreviation of "security identity". Common classes include PrincipalSid (to represent the principal inside an Authentication object) and GrantedAuthoritySid. The security identity information is stored in the ACL_SID table.
  •  ObjectIdentity: Each domain object is represented internally within the ACL module by an ObjectIdentity. The default implementation is called ObjectIdentityImpl.
  •  AclService: Retrieves the  Acl applicable for a given  ObjectIdentity. In the included implementation (JdbcAclService), retrieval operations are delegated to a LookupStrategy. The LookupStrategy provides a highly optimized strategy for retrieving ACL information, using  atched retrievals (BasicLookupStrategy) and supporting custom implementations that leverage  aterialized views, hierarchical queries and similar performance-centric, non-ANSI SQL  apabilities.
  •  MutableAclService: Allows a modified Acl to be presented for persistence. It is not essential to  se this interface if you do not wish.
Getting Started :
To get starting using Spring Security's ACL capability, you will need to store your ACL information somewhere. This necessitates the instantiation of a DataSource using Spring. The DataSource is then injected into a JdbcMutableAclService and BasicLookupStrategy instance. The latter provides high-performance ACL retrieval capabilities, and the former provides mutator capabilities. Refer to one of the samples that ship with Spring Security for an example configuration. You'll also need to populate the database with the four ACL-specific tables listed in the last section (refer to the ACL samples for the appropriate SQL statements).
Once you've created the required schema and instantiated JdbcMutableAclService, you'll next need to ensure your domain model supports interoperability with the Spring Security ACL package. Hopefully ObjectIdentityImpl will prove sufficient, as it provides a large number of ways in which it can be used. Most people will have domain objects that contain a public Serializable getId() method. If the return type is long, or compatible with long (eg an int), you will find you  need not give further consideration to ObjectIdentity issues. Many parts of the ACL module rely on long identifiers. If you're not using long (or an int, byte etc), there is a very good chance you'll need to reimplement a number of classes. We do not intend to support non-long identifiers in Spring Security's ACL module, as longs are already compatible with all database sequences, the most common identifier data type, and are of sufficient length to accommodate all common usage scenarios.
The following fragment of code shows how to create an Acl, or modify an existing Acl:

 // Prepare the information we'd like in our access control entry (ACE)
ObjectIdentity oi = new ObjectIdentityImpl(Foo.class, new Long(44));
Sid sid = new PrincipalSid("Samantha");
Permission p = BasePermission.ADMINISTRATION;
// Create or update the relevant ACL
MutableAcl acl = null;
try {
  acl = (MutableAcl) aclService.readAclById(oi);
} catch (NotFoundException nfe) {
  acl = aclService.createAcl(oi);
}
// Now grant some permissions via an access control entry (ACE)
acl.insertAce(acl.getEntries().length, p, sid, true);
aclService.updateAcl(acl);
 
In the example above, we're retrieving the ACL associated with the "Foo" domain object with identifier number 44. We're then adding an ACE so that a principal named "Samantha" can "administer" the object. The code fragment is  relatively self-explanatory, except the insertAce method. The first argument to the insertAce method is determining at what position in the Acl the new entry will be inserted. In the example above, we're just putting the new ACE at the end of the existing ACEs. The final argument is a boolean indicating whether the ACE is granting or denying. Most of the time it will be granting (true), but if it is denying (false), the permissions are effectively being blocked.
Spring Security does not provide any special integration to automatically create, update or delete ACLs as part of your DAO or repository operations. Instead, you will need to write code like shown above for your individual domain objects. It's worth considering using AOP on your services layer to automatically integrate the ACL information with your services layer operations. We've found this quite an effective approach in the past.
Once you've used the above techniques to store some ACL information in the database, the next step is to actually use the ACL information as part of authorization decision logic. You have a number of choices here. You could write your  own AccessDecisionVoter or AfterInvocationProvider that respectively fires before or after a method invocation. Such classes would use  AclService to retrieve the relevant ACL and then call  Acl.isGranted(Permission[] permission, Sid[] sids, boolean administrativeMode) to decide whether permission is granted or denied. Alternately, you could use our  AclEntryVoter,  AclEntryAfterInvocationProvider or  AclEntryAfterInvocationCollectionFilteringProvider classes. All of  these classes provide a declarative-based approach to evaluating ACL information at runtime, freeing you from needing to write any code. Please refer to the sample applications to learn how to use these classes.

Exctracted from : Spring Security: Reference Documentation v3.1.0

MyBatis Insert

The Mapper interface method accepts the Object :

void insertAccount(Account account);

The Mapper xml uses the properties :

<insert id="insertAccount" parameterType="x.y.z.Account">

               INSERT INTO ACCOUNT (EMAIL, FIRSTNAME, LASTNAME, STATUS, ADDR1, ADDR2, CITY,
               STATE, ZIP, COUNTRY, PHONE, USERID)

VALUES

              (#{email}, #{firstName}, #{lastName}, #{status}, #{address1},  #{address2,jdbcType=VARCHAR}, 
              #{city}, #{state}, #{zip}, #{country}, #{phone}, #{username})

</insert>

Monday, May 14, 2012

I can't live, If living is without you !!!

Don't hesitate to download Ubuntu 12.4LTS

Http://www.ubuntu.com

Spring - Websphere - JNDI - JMS configuration

Define a JNDI template that other beans will be using for retrieving JNDI objects.
<bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
<property name="environment">
<props>
<prop key="java.naming.provider.url">smqp://localhost:4001/timeout=10000</prop>
<prop key="java.naming.factory.initial">com.swiftmq.jndi.InitialContextFactoryImpl</prop>
</props>
</property>
</bean>

Create a connection factory. I used Topic instead of Queue for my experiment.
<bean id="connectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate" ref ="jndiTemplate"/>
<property name="jndiName" value="TopicConnectionFactory"/>
</bean>
Create a Spring specific JMS template that will be used for sending JMS messages. Note that we are providing connection factory and a destination to the template. Destination is the message destination which is in our case named ‘testtopic’.
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="defaultDestination" ref="destination"/>
<property name="pubSubDomain" value="true"/>
<property name="deliveryPersistent" value="true"/>
<property name="deliveryMode" value="2"/>
</bean>
<bean id="destination" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate" ref="jndiTemplate"/>
<property name="jndiName" value="testtopic"/>
</bean>
I create a MsgSender class and inject jmsTemplate and destination to it. This class simply sends a number of JMS messages to the provided destination using the template.
<bean id="sender" class="myexp.spring.MsgSender">
<property name="destination" ref="destination"/>
<property name="jmsTemplate" ref="jmsTemplate"/>
</bean>
After sending the messages, we need to receive it right? :) So here we are defining a Spring specific message listener container and providing a message listener to the container. For each message received, the onMessage method of the message listener will be called. In my experiment I simply printout the message in console.
<bean id="messageListener" class="myexp.spring.ExampleListener"/>
<bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="destination" ref="destination"/>
<property name="messageListener" ref="messageListener"/>
<property name="sessionAcknowledgeModeName" value="AUTO_ACKNOWLEDGE"/>
</bean>
My message sender is simple, it sends Text Messages a number of times, like this -

jmsTemplate.send(destination, new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
String msgText = "Message " + messageIndex;
System.out.println("Publishing - " + msgText);
Message message = session.createTextMessage(msgText);
message.setLongProperty("startTime", System.currentTimeMillis());
return message;
}
});

I an addition to a String message, I am also adding additional property into the message. The listener class must implement javax.jms.MessageListener and implement the following method -

public void onMessage(Message message) {
TextMessage msg = (TextMessage) message;
System.out.println("Reading - " + msg.getText());
}

see :

Wednesday, May 9, 2012

How t send multiple parameters to mybatis xml mapper file?

Problem

Using a single parameter is very easy. The example on page 30 of the user guide shows this (see below). But How do we use multiple parameters?
UserMapper.xml:
<select id=”selectUser” parameterType=”int” resultType=”User”>
  select id, username, hashedPassword
  from some_table
  where id = #{id}</sql>
UserMapper.java:
public interface UserMapper{
  User selectUser(int id);
}

Solution

  1. Add the @Param("name") to your Mapper.java
  2. Change the parameterType in Mapper.xml to "map"

1. Add the @Param("name") to your Mapper.java

UserMapper.java:
import org.apache.ibatis.annotations.Param;
public interface UserMapper{
   User selectUser(@Param("username") String usrename, 
                   @Param("hashedPassword") String hashedPassword);
}

2. Change the parameterType in Mapper.xml to "map"

UserMapper.xml:
<select id=”selectUser” parameterType=”map” resultType=”User”>
  select id, username, hashedPassword
  from some_table
  where username = #{username}
  and hashedPassword = #{hashedPassword}</sql>
 
 
see :
http://code.google.com/p/mybatis/wiki/HowToSelectMultipleParams