Importing SSPI context



I am new to SSPI and trying out an app that

1) accepts connections from client (NTLM)
2) impersonates the user
3) exports the security context
4) imports the security context
5) uses the imported security context to impersonate again.

First 4 steps are getting executed correctly but on the 5 th step I am
getting invalid handle error. I am not sure whats going wrong here and
the documentation available is very limited. Any pointers are much
appreciated. Please see the code snippet below: (I have pasted only
the SSPI related calls)

*****
/*
Accept security context from client: Start

rc = (pf->QuerySecurityPackageInfo)( "NTLM", &secPackInfo );
rc = (pf->AcquireCredentialsHandle)( NULL, "NTLM",
SECPKG_CRED_INBOUND,
NULL, NULL, NULL, NULL, &cred, &useBefore );

rc = (pf->AcceptSecurityContext)( &cred, haveContext? &srvCtx: NULL,
&ibd, 0, SECURITY_NATIVE_DREP, &srvCtx, &obd, &ctxAttr,
&useBefore );


if ( rc == SEC_I_COMPLETE_AND_CONTINUE || rc ==
SEC_I_COMPLETE_NEEDED )
{
if ( pf->CompleteAuthToken != NULL ) // only if implemented
(pf->CompleteAuthToken)( &srvCtx, &obd );
if ( rc == SEC_I_COMPLETE_NEEDED )
rc = SEC_E_OK;
else if ( rc == SEC_I_COMPLETE_AND_CONTINUE )
rc = SEC_I_CONTINUE_NEEDED;
}

Accept security context from client: End
*/

PSecBuffer pPackedContext;
rc = (pf->ImpersonateSecurityContext)( &srvCtx );
(pf->RevertSecurityContext)( &srvCtx );

rc = (pf->ExportSecurityContext)((PCtxtHandle)&srvCtx,
SECPKG_CONTEXT_EXPORT_RESET_NEW | SECPKG_CONTEXT_EXPORT_DELETE_OLD,
pPackedContext, 0);

(pf->FreeContextBuffer)( secPackInfo );

CtxtHandle srvCtxGanesh;

rc = (pf->ImportSecurityContext)("NTLM", pPackedContext, 0,
&srvCtxGanesh);

rc = (pf->ImpersonateSecurityContext)( &srvCtxGanesh );

*****






.