Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / .NET Framework / Interop / February 2004

Tip: Looking for answers? Try searching our database.

InvalidCastException Using AzMan from ASP.NET

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Chris Bilson - 04 Feb 2004 19:33 GMT
Hi All,

I am having a problem using the AzMan PIA in an ASP.NET application.
Here are the basic steps my application is performing:

1. During startup, an AzAuthorizationStore is initialized from an XML
File. OpenApplication is called. The resulting IAzApplication is
stored in a static variable.

2. During the ASP.NET application's AuthenticateRequest event, after
the user is authenticated (using Windows authentication), I call
InitializeClientContextFromToken, using the logged in user's token. I
then store the IAzClientContext in call context.

3. The object that makes these AzMan calls (and that has a static ref
to IAzApplication) has an AccessCheck method, which first calls
AccessCheck on the IAzClientContext, and then performs some other
access check logic if the AzMan access check succeeded.

The problem is that in step 2, sometimes I get an InvalidCastException
calling any method on the IAzApplication.
(System.InvalidCastException: QueryInterface for interface
Microsoft.Interop.Security.AzRoles.IAzApplication failed).

This is my first extensive use of COM Interop, so I thought maybe
there was a threading problem. I reworked my class to be thread bound,
creating a new object (with a new IAzApplication) on each thread. I
store the CurrentThread's hash code, and compare it against
CurrentThread.GetHashCode() before I make any calls to IAzApplication,
and verify that the thread hash codes are the same.

After all this, I was still getting the same exception.

I also tried a few other variations, such as storing the
IAzApplication reference in other places (Application state, TLS slot,
etc.)

Does anybody have any advice for me? BTW, this is not the 9-minute
timeout problem - or at least this problem manifests itself in much
less than 9 minutes (4 or 5 page views and I get it, perhaps 30
seconds).

Or is there a better way for me to use the AzMan objects? Thanks in
advance for any advice/info.

Chris Bilson
"Ying-Shen Yu[MSFT]" - 05 Feb 2004 08:41 GMT
Hi Chris,

Thanks for posting in the community!

From my understanding, you initialized the IAzApplicationStore at startup,
then call the method on IAzApplication later when the AuthenticateRequest
event fired.

You may read the follow article first and try if the ASP.NET sample code
works properly on your system. If the sample works fine, I suspect the
problem might still caused by thread mismatch, you may try taking a look at
the IIS log or dig deep into the InvalidCastException, to get the error
code(I mean HRESULT returned by Com runtime).
In addition, I'm not clear what your "static variable" mean, you may try
storing the IAzApplication in Session property instead.

Thanks!

Best regards,

Ying-Shen Yu [MSFT]
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security

This posting is provided "AS IS" with no warranties and confers no rights.
This mail should not be replied directly, "online" should be removed before
sending.
Chris Bilson - 05 Feb 2004 19:08 GMT
Hi Ying-Shen,

  Thanks for your reply.

> From my understanding, you initialized the IAzApplicationStore at startup,
> then call the method on IAzApplication later when the AuthenticateRequest
> event fired.

Correct.

> You may read the follow article first and try if the ASP.NET sample code
> works properly on your system.

Which article is that?

> If the sample works fine, I suspect the
> problem might still caused by thread mismatch, you may try taking a look at
> the IIS log or dig deep into the InvalidCastException, to get the error
> code(I mean HRESULT returned by Com runtime).

0x80004002. There is no inner or base exception.

In addition to the System.Threading.Thread.GetHashCode() checking I
mentioned, I added calls to Kernel32's GetCurrentThreadId(), for
diagnostics, and verified that when the error occurs, I am on the same
Windows thread, as well as the same .NET thread.

> In addition, I'm not clear what your "static variable" mean, you may try
> storing the IAzApplication in Session property instead.

I tried that, but had the same problem. What I meant by static
variable was something like:

public class SecurityMgr
{
  ...
 
  // NOTE: Putting this in App State or Session State did not help
  private static IAzApplication azApp_ = null;

  // Called from my Global.asax's Application_Start
  public void Init(HttpContext)
  {
     ...
     AzAuthorizationStore store = new AzAuthorizationStoreClass();
     store.Initialize(0, @"msxml://" + storeFilename, null);
     azApp_ = store.OpenApplication(appName, null);
     ...

  }

  // Called from my Global.asax's Application_AuthenticateRequest
  public void InitContext(HttpContext ctxt)
  {
    ...
    IPrincipal p = HttpContext.Current.User;
    WindowsIdentity winID = p.Identity as WindowsIdentity;

    // NOTE: This is where the error occurs
    IAzClientContext azCtxt =
azApp_.InitializeClientContextFromToken((uint) winID.Token, null);

    CallContext.SetData("SecuityMgr:ClientContext", azCtxt);
  }

  // Called from anywhere
  public bool AccessCheck(string operationName)
  {
     bool rv = false;

     int opID = GetOperationIDSomehow(operationName);
     IAzClientContext ctxt =
CallContext.GetData("SecurityMgr:ClientContext")
       as IAzClientContext;
     object[] res = ctxt.AccessCheck("something contextual", null,
        new object[]{operationID}, null, null, null, null, null);
     if (res.Length > 0)
        rv = 0 == (int) res[0];

     if (rv) {
       // Do some extra checking based on some application business
rules
     }
     
     return rv;
  }
}
"Ying-Shen Yu[MSFT]" - 06 Feb 2004 02:01 GMT
Hi Chris,

Sorry, the link to that article is:

http://www.microsoft.com/technet/treeview/default.asp?url=/technet/prodtechn
ol/windowsserver2003/maintain/security/athmanwp.asp

Best regards,

Ying-Shen Yu [MSFT]
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security

This posting is provided "AS IS" with no warranties and confers no rights.
This mail should not be replied directly, "online" should be removed before
sending.
"Ying-Shen Yu[MSFT]" - 06 Feb 2004 11:50 GMT
Hi Chris,

Thanks for the detail information.

80004002(E_NOINTERFACE) might be caused by many issues, however mostly the
error was caused by
threading model mismatch or permmision denied.

First I'd like you check the sample in this article,

<Role-Based Access Control for Multi-tier Applications Using Authorization
Manager>
http://www.microsoft.com/technet/treeview/default.asp?url=/technet/prodtechn
ol/windowsserver2003/maintain/security/athmanwp.asp

especially make sure you are running the application server in a service
account.  To configure your ASP.NET application server to run in a service
account, you create a separate IIS 6.0 worker process which runs in the
security context of the service account created for the application server.
You can then configure your ASP.NET application to use this dedicated IIS
worker process. For more information on IIS 6.0 worker processes, see the
Microsoft Internet Information Services page on the Microsoft Web site at

http://www.microsoft.com/technet/prodtechnol/iis/default.asp.

Alternatively, you can use ASP.NET to configure the context in which an
application runs using the Web.config file for your ASP.NET application. In
that case, you should configure the ASP.NET application to run as the
dedicated service account.

In Addition, I'd like you try turning on the ASP Compatibility mode, add
the aspcompat=true attribute to the Page Directive.  Adding this attribute
accomplishes two things:
1) ASP.NET uses Single-Threaded Apartment (STA) threads when accessing the
COM component. The default is to use Multi-Threaded Apartment, or MTA,
threading.

2) ASP.NET provides access to the ASP-intrinsic objects in a
backward-compatible fashion.

Also, just to confirm does this problem also occur if deployed your program
on some other windows 2003 servers?
Thanks!

Best regards,

Ying-Shen Yu [MSFT]
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security

This posting is provided "AS IS" with no warranties and confers no rights.
This mail should not be replied directly, "online" should be removed before
sending.
Chris Bilson - 06 Feb 2004 22:51 GMT
Thanks Ying-Shen!

> First I'd like you check the sample in this article,
>
> <Role-Based Access Control for Multi-tier Applications Using Authorization
> Manager>
> http://www.microsoft.com/technet/treeview/default.asp?url=/technet/prodtechn
> ol/windowsserver2003/maintain/security/athmanwp.asp

Have it right here on my desk. It's the article that convinced me that
AuthMan was what I had been looking for for authorization.

That sample works fine on my machine no matter how many requests I
make, even if I include the ASP.NET page in the article in my
application's vdir.

The only problem is that that sample initializes the AzManStore and
Opens the application on every request. That just seems very
inefficient for my application, since everything in the application
will be using the same IAzApplication.

> especially make sure you are running the application server in a service
> account.  

OK. My application is running in it's own app pool, as NETWORK
SERVICE. I assume that is what you mean by a service account (it has
the login as service right). Since you mentioned this, I tried
changing the identity for the app pool to local service and then local
system. No help.

I also tried running the application on a test server that has an app
pool that runs as a domain account (which has login as service on that
machine). Same problem.

BTW, the NETWORK SERVICE account on my machine has read access to my
auth man file.

> In Addition, I'd like you try turning on the ASP Compatibility mode, add
> the aspcompat=true attribute to the Page Directive.  

I tried this for the page I have been getting the fault on, it didn't
help, so I went back and turned on aspcompat for all the pages I view
before I get to that page. That didn't help either.

> Also, just to confirm does this problem also occur if deployed your program
> on some other windows 2003 servers?

Yes. We only have Windows Server 2003 servers, so I can't confirm if
this is a problem on older machines.

For now, I think I will just change my SecurityMgr class to initialize
the IAzApplication for each request, until I can find a better work
around. Really wish I knew what caused this.
"Ying-Shen Yu[MSFT]" - 10 Feb 2004 02:53 GMT
Hi Chris,

I had sent a mail to the product group to ask them take a look at this
issue,
I'll upate this issue if I get the reply from them and update this thread
as soon as possible.

for your second issue (the VS.NET IDE hang when debugging ASP.NET apps).
I suggest you drop a post to aspnet related groups, maybe you will get more
information there, since it's probably not an interop issue.

Thanks!

Best regards,

Ying-Shen Yu [MSFT]
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security

This posting is provided "AS IS" with no warranties and confers no rights.
This mail should not be replied directly, "online" should be removed before
sending.
"Mike Moore [MSFT]" - 13 Feb 2004 00:15 GMT
Hi Chris,

I'm sorry about the delay in replying. We are still researching your issue
and will post more information as soon as we can.

Thank you, Mike
Microsoft, ASP.NET Support Professional

Microsoft  highly recommends to all of our customers that they visit the
http://www.microsoft.com/protect site and perform the three straightforward
steps listed to improve your computer?s security.

This posting is provided "AS IS", with no warranties, and confers no rights.

--------------------
> X-Tomcat-ID: 146297889
> References: <ed0cda0.0402041133.649beeb7@posting.google.com>
<5TsWVQ86DHA.2164@cpmsftngxa07.phx.gbl>
<ed0cda0.0402051108.4f4361b4@posting.google.com>
<zBkIsdK7DHA.808@cpmsftngxa07.phx.gbl>
<ed0cda0.0402061451.358f47d9@posting.google.com>
> MIME-Version: 1.0
> Content-Type: text/plain
[quoted text clipped - 33 lines]
> This mail should not be replied directly, "online" should be removed before
> sending.
Chris Bilson - 14 Feb 2004 01:10 GMT
> Hi Chris,
>
> I'm sorry about the delay in replying. We are still researching your issue
> and will post more information as soon as we can.

Excellent. Thank you very much!
Chris Bilson - 06 Feb 2004 23:06 GMT
One other thing I forgot to mention...when I set a breakpoint in the
exception handler for the InvalidCastException, if I step around a
litte and try to examine the exception or execute anything in the
immediate window, and then resume, devenv hangs really bad. It is
totally unresponsive, and I end up having to kill it and iisreset as
well. Not fun.
David Qiu - 17 Feb 2004 22:45 GMT
Hi Chris,
I apologize for the delay. It took us sometime to find the resource on your
issue.
Does this error occur intermittently? If so it is hard unless we debug it
if we can repro.

I would suggest to get a regmon and a filemon log first when the error
occurs. You can
download regmon.exe and filemon.exe from

http://www.sysinternals.com

The meaning of the error is:
0x80004002   ( -2147467262 )
E_NOINTERFACE
No such interface supported

Thanks,
David
Microsoft Developer Support
Chris Bilson - 19 Feb 2004 23:01 GMT
> Hi Chris,
> I apologize for the delay. It took us sometime to find the resource on your
> issue.

No problem.

> Does this error occur intermittently? If so it is hard unless we debug it
> if we can repro.

As I mentioned earlier, it occurrs after several requests have been
made to our ASP.NET application (say after 5 requests). Then it
happens fairly regularly, like every other request.

I tried to make a simple ASP.NET app to repdocuce this behavior, but
the simple app behaved fine.

I will e-mail you a link to RegMon and FileMon logs seperately. If you
are interested you can take a look, but I looked and didn't see
anything interestings.

I have been ignoring this problem for about a week, and was just doing
some work in the same area, and thought I saw something that looks
suspicious. A call on one thread to
IAzApplication::InitializeClientContextFromToken was in progress (we
have a large XML file for AuthMan to digest) when another thread was
starting to call the same method on the same instance of
AzApplication. We have two frames in our browser app that are both
ASPX pages accessing AuthMan. I will ivestigate further, and if I come
to any conclusions, I will be sure to post them here.

Thanks again for the help.

> I would suggest to get a regmon and a filemon log first when the error
> occurs. You can
[quoted text clipped - 10 lines]
> David
> Microsoft Developer Support
Nasseam Elkarra - 23 Feb 2004 08:31 GMT
    // NOTE: This is where the error occur
   IAzClientContext azCtxt
azApp_.InitializeClientContextFromToken((uint) winID.Token, null)

You should be casting to ulong (or UInt64) instead of uint. The method signature is below

public abstract new Microsoft.Interop.Security.AzRoles.IAzClientContext InitializeClientContextFromToken ( System.UInt64 ullTokenHandle , System.Object varReserved
   Member of Microsoft.Interop.Security.AzRoles.IAzApplicatio

Nasseam Elkarr
http://www.myspotter.com

Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.