0

SecurityContextHolder.getContext().getAuthentication() is null

asked 2010-10-18 04:31:10 +0800

pandukish gravatar image pandukish
68 1 1 4

Dear All,

I got into the problem which makes me got struck to move further,

I am using ZK5.0.2, Spring Security 3.0.2, ZK Wed Flow and Hibernate. My application is running without any exceptions. Recently I wanted to implement Spring Method security in the application. I have implemented with MethodIntercepter and BeanProxey to do the same. I am getting the below exception when I try to call the secured method.

SEVERE: >>org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
>> at org.springframework.security.access.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:321)
>> at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:195)
>> at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:64)
>> at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
>> at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:625)


Here my Spring security xml file

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

    <bean id="springSecurityFilterChain" class="org.springframework.security.web.FilterChainProxy">
        <security:filter-chain-map path-type="ant"  >
            <security:filter-chain pattern="/js/**" filters="none" />
            <security:filter-chain pattern="/img/**" filters="none"/>
            <security:filter-chain pattern="/css/**" filters="none"/>
            <security:filter-chain pattern="/zkau/**" filters="none"/>
            <security:filter-chain pattern="/**" filters="httpSessionContextIntegrationFilter,authenticationProcessingFilter,logoutFilter,rememberMeProcessingFilter,concurrentSessionFilter,anonymousProcessingFilter,exceptionTranslationFilter,filterSecurityInterceptor,securityContextHolderAwareRequestFilter"/>

        </security:filter-chain-map>

        <!--<security:intercept-methods access-decision-manager-ref="authenticationManager" >
            <security:protect method="com.maxxprism.module.admin.operations.UserInfoOperations.modifyUser" access="ROLE_USER"/>
            <security:protect method="com.maxxprism.module.admin.operations.UserInfoOperations.deleteUser" access="ROLE_USER"/>
        </security:intercept-methods>-->
    </bean>

   
    <bean id="httpSessionContextIntegrationFilter" class="org.springframework.security.web.context.SecurityContextPersistenceFilter"/>

    <bean id="logoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">
        <constructor-arg value="/logout.zul" />
        <constructor-arg>
            <list>
                <ref bean="rememberMeServices" />
                <bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler">
                    <property name="invalidateHttpSession" value="true"/>
                </bean>
            </list>
        </constructor-arg>
        <property name="filterProcessesUrl" value="/j_spring_security_logout" />
    </bean>

    <bean id="authenticationProcessingFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
        <property name="filterProcessesUrl" value="/j_spring_security_check" />
        <property name="usernameParameter" value="j_username" />
        <property name="passwordParameter" value="j_password" />
        <property name="authenticationManager" ref="authenticationManager" />
        <property name="rememberMeServices" ref="rememberMeServices" />
        <property name="authenticationSuccessHandler" ref="authenticationSuccessHandler" />
        <property name="authenticationFailureHandler" ref="authenticationFailureHandler"/>
        <property name="sessionAuthenticationStrategy" ref="concurrentSessionControlStrategy"/>
    </bean>

    <bean id="authenticationSuccessHandler" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler" >
        <property name="defaultTargetUrl" value="/init/init.zul"/>
        <property name="alwaysUseDefaultTargetUrl" value="true"/>
    </bean>
    <!--<bean id="authenticationFailureHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler" >
        <property name="defaultFailureUrl" value="/login.zul?error=true" />
        <property name="useForward" value="true"/>
    </bean>-->
    <bean id="authenticationFailureHandler" class="org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler" >
        <property name="exceptionMappings">
            <props>
                <prop key="org.springframework.security.authentication.BadCredentialsException">/loginFail.zul</prop>
                <prop key="org.springframework.security.web.authentication.session.SessionAuthenticationException">/multiLogin.zul</prop>
                <prop key="org.springframework.security.authentication.DisabledException">/userDisabled.zul</prop>

            </props>
        </property>
        <property name="useForward" value="true"/>
    </bean>

    <bean id="securityContextHolderAwareRequestFilter" class="org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter" />

    <bean id="rememberMeProcessingFilter" class="org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter">
        <property name="authenticationManager" ref="authenticationManager" />
        <property name="rememberMeServices" ref="rememberMeServices" />
    </bean>

    <bean id="anonymousProcessingFilter" class="org.springframework.security.web.authentication.AnonymousAuthenticationFilter">
        <property name="key" value="anonymous" />
        <property name="userAttribute" value="anonymous,ROLE_ANONYMOUS" />
    </bean>


    <bean id="exceptionTranslationFilter" class="org.springframework.security.web.access.ExceptionTranslationFilter">
        <property name="authenticationEntryPoint" ref="authenticationEntryPoint"/>
        <property name="accessDeniedHandler" ref="accessDeniedHandler"/>
    </bean>

    <bean id="accessDeniedHandler" class="org.springframework.security.web.access.AccessDeniedHandlerImpl">
        <property name="errorPage" value="/unauthorizedAccess.zul"/>
    </bean>


    <bean id="authenticationEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
        <property name="loginFormUrl" value="/loginRequired.zul" />
        <property name="forceHttps" value="false" />
    </bean>

    <bean id="filterSecurityInterceptor" class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
        <property name="authenticationManager" ref="authenticationManager" />
        <property name="accessDecisionManager" ref="accessDecisionManager" />
        <property name="securityMetadataSource" ref="databaseObjectDefinitionSource" />
        <property name="rejectPublicInvocations" value="true"/>
        <property name="validateConfigAttributes" value="true"/>
    </bean>

    <bean id="databaseObjectDefinitionSource" class="org.springframework.security.web.access.intercept.DefaultFilterInvocationSecurityMetadataSource" >
        <constructor-arg ref="antUrlPathMatcher" />
        <constructor-arg ref="requestMap" />
    </bean>

    <bean id="antUrlPathMatcher" class="org.springframework.security.web.util.AntUrlPathMatcher" />

    <bean id="requestMap" class="com.maxxprism.core.util.RequestMapFactoryBean" init-method="init"/>

    <bean id="accessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
        <property name="allowIfAllAbstainDecisions" value="true" />
        <property name="decisionVoters">
            <list>
                <bean class="org.springframework.security.access.vote.RoleVoter" >
                    <!--<property name="rolePrefix" value="" />-->
                </bean>
                <bean class="org.springframework.security.access.vote.AuthenticatedVoter"/>
            </list>
        </property>

    </bean>

    <bean id="rememberMeServices" class="org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices">
        <property name="key" value="MOZAMBIQUE-MLI-92-59" />
        <property name="parameter" value="_spring_security_remember_me" />
        <property name="cookieName" value="SPRING_SECURITY_REMEMBER_ME_COOKIE" />
        <property name="tokenValiditySeconds" value="1209600" /><!-- 14 days -->
        <property name="userDetailsService" ref="userDetailsService" />
    </bean>

    <bean id="authenticationManager" class="org.springframework.security.authentication.ProviderManager">
        <property name="providers">
            <list>
                <ref bean="daoAuthenticationProvider" />
                <ref bean="anonymousAuthenticationProvider" />
                <ref bean="rememberMeAuthenticationProvider" />
            </list>
        </property>
    </bean>

    <bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
        <property name="userDetailsService" ref="userDetailsService" />
        <property name="passwordEncoder" ref="passwordEncoder" />
    </bean>

    <bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder">

    </bean>

    <bean id="anonymousAuthenticationProvider" class="org.springframework.security.authentication.AnonymousAuthenticationProvider">
        <property name="key" value="doesNotMatter" />
    </bean>

    <bean id="rememberMeAuthenticationProvider" class="org.springframework.security.authentication.RememberMeAuthenticationProvider">
        <property name="key" value="MOZAMBIQUE-MLI-92-59" />
    </bean>

    <!-- Disable a user after a number of failed logins listener -->
        <!--<bean id="applicationListenerImpl" class="com.nemada.gescarga.listener.ApplicationListenerImpl"/>-->

        <!-- Automatically receives AuthenticationEvent messages -->
    <bean id="loggerListener" class="org.springframework.security.authentication.event.LoggerListener"/>
    <bean id="userDetailsService" class="com.maxxprism.core.service.UserDetailServiceImplementation"/>
    <bean id="authorityService" class="com.maxxprism.core.service.AuthorityService" />
    <bean id="maxxMethodCofigConstruction" class="com.maxxprism.core.util.MaxxMethodCofigConstruction" />
    <bean id="maxxMethodSecurityMetadataSource" class="com.maxxprism.core.util.MaxxMethodSecurityMetadataSource" >
        <constructor-arg name="maxxMethodCofigConstruction" ref="maxxMethodCofigConstruction"/>
    </bean>

    <bean id="concurrentSessionFilter" class="org.springframework.security.web.session.ConcurrentSessionFilter">
        <property name="expiredUrl" value="/timeout.zul"/>
        <property name="sessionRegistry" ref="sessionRegistry"/>
    </bean>
    <bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl"/>

    <bean id="concurrentSessionControlStrategy" class="org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy">
        <constructor-arg ref="sessionRegistry"/>
        <property name="alwaysCreateSession" value="true"/>
        <property name="exceptionIfMaximumExceeded" value="true"/>
        <property name="maximumSessions" value="1"/>
    </bean>

  <bean id="methodSecurityInterceptor" class="org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor">
        <property name="authenticationManager" ref="authenticationManager"/>
        <property name="accessDecisionManager" ref="accessDecisionManager"/>
        <property name="securityMetadataSource" ref="maxxMethodSecurityMetadataSource"/>
    </bean>

    <bean id="autoProxyCreator" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator" >
        <property name="interceptorNames">
            <list>
                <value>methodSecurityInterceptor</value>
            </list>
        </property>
        <property name="beanNames" >
            <list>
                <value>userInfoOperations</value>
            </list>
        </property>
        <property name="proxyTargetClass" value="true"/>
    </bean>

</beans>

and my zk.xml is

<?xml version="1.0" encoding="UTF-8"?>

<zk>
    <library-property>
        <name>org.zkoss.zul.Button.mold</name>
        <value>trendy</value>
    </library-property>
    <library-property>
        <name>org.zkoss.zul.grid.rod</name>
        <value>true</value>
    </library-property>

    <library-property>
        <name>org.zkoss.zul.listbox.rod</name>
        <value>true</value>
    </library-property>
    <library-property>
        <name>org.zkoss.util.label.web.location</name>
        <value>/WEB-INF/i3-label.properties</value>
    </library-property>
    <library-property>
        <name>org.zkoss.zul.progressbox.position</name>
        <value>mouse</value>
    </library-property>

    <client-config>
        <debug-js>true</debug-js>
    </client-config>



    <!-- Optional -->
    <device-config>
        <device-type>ajax</device-type>
        <timeout-uri></timeout-uri>
    </device-config>

    <desktop-config>
        <theme-uri>/css/maxxprism.css</theme-uri>
    </desktop-config>

    <library-property>
        <name>org.zkoss.zul.theme.browserDefault</name>
        <value>true</value>
    </library-property>
    <system-config >
        <disable-event-thread />
    </system-config>
    <listener>
        <description>ThreadLocal Synchronization Listener</description>
        <listener-class>org.zkoss.zkplus.util.ThreadLocalListener</listener-class>
    </listener>


    <preference>
        <name>ThreadLocal</name>
        <value>
            org.springframework.security.core.context.ThreadLocalSecurityContextHolderStrategy=contextHolder;
        </value>
    </preference>

</zk>

Can you please any body help me in this regard.

Regards,
Kishore

delete flag offensive retag edit

21 Replies

Sort by ยป oldest newest

answered 2010-10-18 05:40:41 +0800

ashishd gravatar image ashishd flag of Taiwan
1972 6

Hi pandukish,
It seems there is a problem in your zk.xml becuase of threadlocal issue You should either disable event thread or use ThreadLocalListener but not both at the same time.

link publish delete flag offensive edit

answered 2010-10-18 05:52:37 +0800

pandukish gravatar image pandukish
68 1 1 4

Hi Ashishd,

I tried by removing of

<system-config >
<disable-event-thread />
</system-config>

instead placed

<listener>
<description>ThreadLocal Synchronization Listener</description>
<listener-class>org.zkoss.zkplus.util.ThreadLocalListener</listener-class>
</listener>

and I did vice versa, But I could not able to succeed.

Regards,
Kishore

link publish delete flag offensive edit

answered 2010-10-18 06:05:43 +0800

ashishd gravatar image ashishd flag of Taiwan
1972 6

Hi pandikish,
try

<system-config >
<disable-event-thread>false<disable-event-thread/>
</system-config>

link publish delete flag offensive edit

answered 2010-10-18 06:15:32 +0800

pandukish gravatar image pandukish
68 1 1 4

Hi Ashish,

I tried as you suggested, but same error. FYI... please see my updated zk.xml

<?xml version="1.0" encoding="UTF-8"?>

<zk>
    <library-property>
        <name>org.zkoss.zul.Button.mold</name>
        <value>trendy</value>
    </library-property>
    <library-property>
        <name>org.zkoss.zul.grid.rod</name>
        <value>true</value>
    </library-property>

    <library-property>
        <name>org.zkoss.zul.listbox.rod</name>
        <value>true</value>
    </library-property>
    <library-property>
        <name>org.zkoss.util.label.web.location</name>
        <value>/WEB-INF/i3-label.properties</value>
    </library-property>
    <library-property>
        <name>org.zkoss.zul.progressbox.position</name>
        <value>mouse</value>
    </library-property>

    <client-config>
        <debug-js>true</debug-js>
    </client-config>

    <!-- Optional -->
    <device-config>
        <device-type>ajax</device-type>
        <timeout-uri></timeout-uri>
    </device-config>

    <desktop-config>
        <theme-uri>/css/maxxprism.css</theme-uri>
    </desktop-config>

    <library-property>
        <name>org.zkoss.zul.theme.browserDefault</name>
        <value>true</value>
    </library-property>
    <system-config >
        <disable-event-thread>false</disable-event-thread>
    </system-config>
    <!--<listener>
        <description>ThreadLocal Synchronization Listener</description>
        <listener-class>org.zkoss.zkplus.util.ThreadLocalListener</listener-class>
    </listener>-->
    <preference>
        <name>ThreadLocal</name>
        <value>
            org.springframework.security.core.context.ThreadLocalSecurityContextHolderStrategy=contextHolder
        </value>
    </preference>

</zk>

Regards,
Kishore

link publish delete flag offensive edit

answered 2010-10-18 08:01:45 +0800

ashishd gravatar image ashishd flag of Taiwan
1972 6

Hi Pandukish
Ok in that case I need to know more details. When do you call SecurityContextHolder.getContext().getAuthentication() in your code? Is there some place you get the Authentication object or is it null everywhere?

link publish delete flag offensive edit

answered 2010-10-19 01:20:34 +0800

pandukish gravatar image pandukish
68 1 1 4

Dear Ashish,

I ahead a step above, I have identified the issue where it is, but we have to come out of the solution for the same.

We can able to get the SecurityContextHolder.getContext().getAuthentication() with ZK, Spring and Spring Security. When we are trying to use ZK Ajax Web Flow system we are getting the SecurityContextHolder.getContext().getAuthentication() is null.

Let me explain the scenario. I have zul where the web flow system starts.

users.zul

<?page title="User Information" contentType="text/html;charset=UTF-8"?>
<?init class="org.zkoss.zwf.FlowHandler" arg0="/admin/users.xml"?>
<?variable-resolver class="org.zkoss.zkplus.spring.DelegatingVariableResolver" ?>

<zk 	xmlns="http://www.zkoss.org/2005/zk/native"
        xmlns:zul="http://www.zkoss.org/2005/zul">
    <zul:div id="usersMain"  self="@{view(content)}">
      
    </zul:div>
</zk>

From here the flow will get start, which was defined in the users.xml file as below


<?xml version="1.0" encoding="UTF-8"?>
<flow xmlns="http://www.zkoss.org/2009/zwf"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.zkoss.org/2009/zwf http://www.zkoss.org/2009/zwf/zwf.xsd"
      id="usersFlow" >

    <view-state id="userInfo" onEntry='flowScope.put("users",new com.maxxprism.core.model.Users())'>
        <transition id="add" to="userOperations" >
            <attribute name="onTransit" >
                userInfoOperations.kishore();
                flowScope.put("actionValue", "Add");
                flowScope.put("readonly", "false");
                flowScope.put("windowTitle", "admin.user.window.add.title");
            </attribute>
        </transition>
        <transition id="modify"  to="modify-action-state" />
        <transition id="view"  to="view-action-state" />
        <transition id="delete" to="userInfo" >
            <attribute name="onTransit" >
                userInfoOperations.deleteUser(userListBox.getSelectedItem());
            </attribute>
        </transition>
        <transition id="viewAuthorities" to="view-authorities-action-state" />
        <transition id="refresh" to="userInfo" />
    </view-state>

    <view-state id="userOperations" >
        <transition id="save" to="save-action-state" />
        <transition id="update" to="userInfo" >
            <attribute name="onTransit" >
                users.setEnabled(enabled.checked==true?'1':'0');
                userInfoOperations.updateUser(users,flowScope.get("usersCloned"))
            </attribute>
        </transition>
        <transition id="back" to="userInfo"/>
    </view-state>
    <view-state id="userAuthorities">
        <transition id="back-to-users" to="userInfo"/>
    </view-state>
    <action-state id="save-action-state" test="maxxValidations.passwordVerification(password.value,passwordReenter.value)">
        <transition id="yes" to="userInfo">
            <attribute name="onTransit" >
                users.setEnabled(enabled.checked==true?'1':'0');
                userInfoOperations.addUser(users);
            </attribute>
        </transition>
        <transition id="no" to="userOperations" />
    </action-state>
    <action-state id="modify-action-state" test="maxxValidations.checkIsRecordSelected(userListBox.getSelectedItem())">
        <transition id="yes" to="userOperations">
            <attribute name="onTransit" >
                flowScope.put("actionValue", "Modify");
                flowScope.put("readonly", "false");
                flowScope.put("windowTitle", "admin.user.window.modify.title");
                flowScope.put("users",  userInfoOperations.modifyUser(userListBox.getSelectedItem()));
                flowScope.put("usersCloned",  userInfoOperations.modifyUser(userListBox.getSelectedItem()));
            </attribute>
        </transition>
        <transition id="no" to="userInfo" />
    </action-state>
    <action-state id="view-action-state" test="maxxValidations.checkIsRecordSelected(userListBox.getSelectedItem())">
        <transition id="yes" to="userOperations">
            <attribute name="onTransit" >
                flowScope.put("actionValue", "View");
                flowScope.put("readonly", "true");
                flowScope.put("windowTitle", "admin.user.window.view.title");
                flowScope.put("users",  userInfoOperations.modifyUser(userListBox.getSelectedItem()));
            </attribute>
        </transition>
        <transition id="no" to="userInfo" />
    </action-state>

    <action-state id="view-authorities-action-state" test="maxxValidations.checkIsRecordSelected(userListBox.getSelectedItem())">
        <transition id="yes" to="userAuthorities">
            <attribute name="onTransit" >
                flowScope.put("windowTitle", "admin.user.role.window.view.title");
                flowScope.put("map",  userInfoOperations.getUserAuthorities(userListBox.getSelectedItem()));
                flowScope.put("maxxListboxWithServiceObject",  map.get("maxxListboxWithServiceObject"));
                flowScope.put("size",  map.get("maxxListboxWithServiceObjectSize"));
                flowScope.put("username",  map.get("username"));
            </attribute>
        </transition>
        <transition id="no" to="userInfo" />
    </action-state>
</flow>

when the flow starts, initially it will come to state "userInfo". where it will load the userInfo.zul page as mentioned below.


<?xml version="1.0" encoding="UTF-8"?>
<?page title="userInfo" ?>
<?taglib uri="http://www.zkoss.org/dsp/web/core" prefix="c" ?>
<?variable-resolver class="org.zkoss.zkplus.spring.DelegatingVariableResolver"?>

<zk xmlns:zul="http://www.zkoss.org/2005/zul"
    xmlns="http://www.zkoss.org/2005/zk/native">

    <zul:window title="${c:l('admin.user.window.title')}" border="normal" >
        <zul:div height="10px" />
        <zul:div align="center">
            <zul:listbox id="userListBox" apply="${userListbox}"  mold="paging" pageSize="3" oddRowSclass="false" width="47%"/>
        </zul:div>

        <zul:div height="10px"/>
        <zul:div  width="100%" align="center" class="btndiv" >
            <zul:button  id="add" label="${c:l('common.button.add')}" sclass="maxxprismButton" self="@{action(add)}"/>
            <zul:button id="modify" label="${c:l('common.button.modify')}" sclass="maxxprismButton" self="@{action(modify)}"/>
            <zul:button id="view" label="${c:l('common.button.view')}" sclass="maxxprismButton" self="@{action(view)}"/>
            <zul:button id="delete" label="${c:l('common.button.delete')}" sclass="maxxprismButton" self="@{action(delete)}"/>
            <zul:button id="viewRoles" label="${c:l('common.button.viewRoles')}" sclass="maxxprismButton" self="@{action(viewAuthorities)}"/>
            <zul:button id="refresh" label="${c:l('common.button.refresh')}" sclass="maxxprismButton" self="@{action(refresh)}"/>
        </zul:div>
        <zul:div height="10px"/>
    </zul:window>

</zk>

In the above zul page when I click on "add" button a method will be called "userInfoOperations.kishore();". The method signature are follows.

UserInfoOperations.java

package com.maxxprism.module.admin.operations;

import com.maxxprism.core.model.Users;
import com.maxxprism.core.service.GenericService;
import com.maxxprism.core.util.MaxxListboxWithServiceObject;
import com.maxxprism.core.util.MaxxValidations;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;

/**
 * @author Kishore Kumar Karanam
 * @version $Revision: 1.0 $ $Date: 23-Aug-2010 $
 **/
@SuppressWarnings({"unchecked"})
public class UserInfoOperations implements java.io.Serializable {

    @Autowired
    @Qualifier("maxxParametersService")
    private GenericService _maxxParametersService;
    @Autowired
    @Qualifier("usersService")
    private GenericService _usersService;
    @Autowired
    @Qualifier("maxxValidations")
    private MaxxValidations _maxxValidations;
    @Autowired
    @Qualifier("usersAuthoritiesService")
    private GenericService _usersAuthoritiesService;

    public UserInfoOperations() {
    }

    public void kishore(){

        System.out.println("Kishore Kumar Karanam::"+SecurityContextHolder.getContext().getAuthentication());
    }

    public void addUser(Users users) {
        /* To encode the password with MD5 password algorithm
         * with helper class provided by the Spring Security Md5PasswordEncoder
         * without salt object
         */
        String tempPassoword = users.getPassword();
        PasswordEncoder passwordEncoder = new Md5PasswordEncoder();
        users.setPassword(passwordEncoder.encodePassword(tempPassoword, null));

        /* To set the password expiry date with number of days configured at PASSWORD_EXPIRY_DAYS 
         *  in the table called MAXX_PARAMETERS
         */

        String passwordExpiryDaysQuery = "select passwordExpiryDays from MaxxParameters";
        List passwordExpiryDaysList = (List) _maxxParametersService.findByHSQLQuery(passwordExpiryDaysQuery);
        int passwordExpiryDays = 0;
        for (Iterator passwordExpiryDaysIterator = passwordExpiryDaysList.iterator(); passwordExpiryDaysIterator.hasNext();) {
            passwordExpiryDays = new BigDecimal(passwordExpiryDaysIterator.next().toString()).intValue();
        }
        Calendar cal = new GregorianCalendar();
        cal.add(Calendar.DATE, passwordExpiryDays);
        users.setPasswordExpirydate(cal.getTime());
        Users usersToBeValidated = (Users) _usersService.get(users.getUsername());
        if (_maxxValidations.recordIntegrityValidation(usersToBeValidated)) {
            _usersService.save(users);
        }
    }

    public void updateUser(Users users, Users usersCloned) {
        /* To Update the user with modified object
         */
        Users usersFromDSAsofNow = (Users) _usersService.get(usersCloned.getUsername());
        if (_maxxValidations.objectModifiedValidation(usersFromDSAsofNow, usersCloned)) {
            _usersService.update(users);
        }
    }

    public Users modifyUser(Listitem listitem) {
        List listcellList = listitem.getChildren();
        Listcell listcell = (Listcell) listcellList.get(0);
        Users userObject = (Users) _usersService.get(listcell.getLabel());
        if (_maxxValidations.beforeModifyValidation(userObject)) {
            return userObject;
        }
        return null;
    }

    public void deleteUser(Listitem listitem) throws InterruptedException {
        if (_maxxValidations.checkIsRecordSelected(listitem)) {
            List listcellList = listitem.getChildren();
            Listcell listcell = (Listcell) listcellList.get(0);
            Users userObject = (Users) _usersService.get(listcell.getLabel());
            if (_maxxValidations.deleteValidation(userObject)) {
                _usersService.delete(userObject);
            }
        }
    }

    public Map getUserAuthorities(Listitem listitem) throws InterruptedException {
        if (_maxxValidations.checkIsRecordSelected(listitem)) {
            List listcellList = listitem.getChildren();
            Listcell listcell = (Listcell) listcellList.get(0);
            Users userObject = (Users) _usersService.get(listcell.getLabel());
            Collection authoritiesList = _usersAuthoritiesService.findByHSQLQuery("from UsersAuthorities a where a.username='" + userObject.getUsername() + "'");
            MaxxListboxWithServiceObject maxxListboxWithServiceObject = new MaxxListboxWithServiceObject(authoritiesList, new String[]{"Authority"}, new String[]{"authority"});
            Map map = new HashMap();
            map.put("maxxListboxWithServiceObject", maxxListboxWithServiceObject);
            map.put("maxxListboxWithServiceObjectSize", authoritiesList.size());
            map.put("username", userObject.getUsername());
            return map;
        }
        return null;
    }
}


Here its its giving the authentication object as "null"

So, Do I need to configure anything for ZK Ajax Web Flow system other than above?

Regards,
Kishore

link publish delete flag offensive edit

answered 2010-10-19 02:51:58 +0800

ashishd gravatar image ashishd flag of Taiwan
1972 6

Hi pandukish,
ZK Spring 3.0RC does not support Spring Webflow. For Spring webflow you will have to work with ZK Spring 1.2RC (which in turn will not work with Spring 3.x version)

link publish delete flag offensive edit

answered 2010-10-19 06:11:56 +0800

pandukish gravatar image pandukish
68 1 1 4

Dear Ashish,

ZK Spring 3.0RC its supporting ZK Web Flow, I dont have any issues apart from "SecurityContextHolder.getContext().getAuthentication() is null". I belove its requires some configuration to hold the context authentication object.

Already we have completed half of the application. When we are trying MethodSecurity the above said exception is coming. That too in the Spring Web Flow. Normally ZK Spring3.0.RC will work with Spring Web Flow.

Regards,
Kishore

link publish delete flag offensive edit

answered 2010-10-19 07:02:21 +0800

terrytornado gravatar image terrytornado flag of Germany
9393 3 7 16
http://www.oxitec.de/

updated 2010-10-19 07:05:05 +0800

pandukish,

can you evaluate at which place you lost the Authentication object ?

have a search on the project for ' SecurityContextHolder.clearContext() '

link publish delete flag offensive edit

answered 2010-10-19 07:43:57 +0800

pandukish gravatar image pandukish
68 1 1 4

Dear terrytornado,

When I use Spring method security in ZK Ajax Web Flow, its throwing below exception.


SEVERE: >>org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
>> at org.springframework.security.access.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:321)
>> at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:195)
>> at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:64)
>> at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
>> at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:625)
>>...


I have explained the scenario above. If I am not using ZK AJAX web Flow. I can able to do by that time there is no exception.

I searched the project with your search criteria "SecurityContextHolder.clearContext()" with no result.

Regards,
Kishore

link publish delete flag offensive edit
Your reply
Please start posting your answer anonymously - your answer will be saved within the current session and published after you log in or create a new account. Please try to give a substantial answer, for discussions, please use comments and please do remember to vote (after you log in)!

[hide preview]

Question tools

Follow

RSS

Stats

Asked: 2010-10-18 04:31:10 +0800

Seen: 8,114 times

Last updated: Mar 10 '15

Support Options
  • Email Support
  • Training
  • Consulting
  • Outsourcing
Learn More