1
votes

Background:

I am using programmatic authentication (basic authentication) using java security. I have a Stateless session bean(EJB 3). I can inject the Sessioncontext to get the security Principal, to get the user name. In the same project I am using spring beans for JDBC and Aspect. I want to get the user name in one of the aspect(Audit) which is also a spring bean.

Question:

Is it possible to access the ejb sesssioncontext in the Spring bean. If so how to do that? If no, how can the username be accessed from the Spring bean which is also an aspect.

Thanks, Amit

2
Note: I am not using spring security...Dutta

2 Answers

2
votes

This can be done by injecting the EJB into the spring bean. You can do it through a manual JNDI lookup (like you would in any other EJB Client) or use Spring's JndiObjectFactoryBean. With Spring's JndiObjectFactoryBean:

  1. Inject the SessionContext into the EJB

    @Resource
    private SessionContext ctxt;
    //getter and setter
    
  2. Configure the factory bean in your bean configuration file. postageService being the EJBRef we're interested in (Configuration poached from Apress Spring Recipes)

       <bean id="postageService class="org.springframework.jndi.JndiObjectFactoryBean">
             <property name="jndiEnvironment">
                <props>
                   <prop key="java.naming.factory.initial">
                        org.apache.openejb.client.RemoteInitialContextFactory
                    </prop>
                   <prop key="java.naming.provider.url">
                         ejbd://localhost:4201
                   </prop>
               </props>
             </property>
            <property name="jndiName" value="PostageServiceBeanRemote"/>
      </bean>
    
  3. Wire the ejb reference into your spring bean

         public class PostalServiceClient{
    
           //wired EJB
           private PostageService service;
           //getter and setter
    
           private SessionContext retrieveSessionContext(){
               service.getCtxt(); //get the SessionContext from the EJB injection
           }
    
          } 
    
1
votes

kolossus, Thanks for the reply. There is another way that I could found. Following is the Link to the previous post. So basically I did exactly the same thing : 1) Added the following line to the spring-context xml

<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor">
    <property name="alwaysUseJndiLookup" value="true" />
</bean>

2) Added following line to the my spring bean to access the EJB's session context

@Resource(mappedName = "java:global/TopoServices/MessageRestService!com.myrest.MessageRestService")
    private MessageRestService myBean;

Important thing is Jboss 7.1 does not support custom jndi any more unlike Jboss 5 so I used the default jndi.

I think this is more cleaner way to address my requirement.