Impersonation Implementation Using ASP.NET
When running third-party software (for example, SQL
Server®)
there are times when it is necessary to use impersonation to
perform Windows® authentication in an ASP.NET application.
In deployed applications, impersonated credentials are passed
in from IIS. However, since impersonation operates on a per-thread
basis, this can sometimes present problems when processing the MATLAB® Runtime thread
in a multi-threaded deployed application.
Use the following examples to turn impersonation on and off
in your MATLAB file, to avoid problems stemming from MATLAB Runtime thread
processing issues.
Turning On Impersonation in a MATLAB MEX-file
#include mex.h
#include windows.h
/*
*This mex function is called with a single int which
*represents the user
*identity token. We use this token to impersonate a
*user on the interpreter
*thread. This acts as a workaround for ASP.NET
*applications that use
*impersonation to pass the proper credentials
*to SQL Server for windows
*authentication. The function returns non zero status
*for success, zero otherwise.
**/
void mexFunction( int nlhs,
mxArray * plhs[],
int nrhs,
const mxArray * prhs[] )
{
plhs[0] = mxCreateDoubleScalar(0); //return status
HANDLE hToken =
reinterpret_cast(*(mwSize *)mxGetData(prhs[0]));
if(nrhs != 1)
{
mexErrMsgTxt("Incorrect number of input argument(s).
Expecting 1.");
}
int hr;
if(!(hr = ImpersonateLoggedOnUser(hToken)))
{
mexErrMsgTxt("Error impersonating.\n");
}
*(mxGetPr(plhs[0])) = hr;
}
Turning Off Impersonation in a MATLAB MEX-file
#include mex.h
#include windows.h
/*
*This mex function reverts to the old identity on the
interpreter thread **/
void mexFunction( int nlhs,
mxArray * plhs[],
int nrhs,
const mxArray * prhs[] )
{
if(!RevertToSelf())
{
mexErrMsgTxt("Failed to revert to the old
identity.");
}
}
Code Added to Support Impersonation in ASP.NET Application
Monitor.Enter(someObj);
DeployedComponent.DeployedComponentClass myComp;
try
{
System.Security.Principal.WindowsIdentity myIdentity =
System.Security.Principal.WindowsIdentity.GetCurrent();
//short circuit if user app is not impersonated
if(myIdentity.isImpersonated())
{
myComp = new DeployedComponent.
DeployedComponentClass ();
//Run Users code
MWArray[] output = myComp.impersonateUser(1,
getToken());
}
else
{
//Run Users code
}
}
Catch(Exception e)
{
}
finally
{
if(myComp!=null)
myComp.stopImpersonation();
Monitor.Exit(someObj;)
}
//
//
//Utility method to read the token for the current user
//and wraps it in a MWArray private MWNumericArray getToken()
{
System.Security.Principal.WindowsIdentity myIdentity =
System.Security.Principal.WindowsIdentity.GetCurrent();
MWNumericArray a = null;
if (IntPtr.Size == 4)
{
int intToken = myIdentity.Token.ToInt32();
a = new MWNumericArray(intToken, false);
}
else
{
Int64 intToken = myIdentity.Token.ToInt64();
a = new MWNumericArray(intToken, false);
}
return a;