0

I'm implementing the following scenario: ASP.NET MVC 5 application access OData WebAPI with Azure Active Directory authentication (like in this article: http://msdn.microsoft.com/en-us/magazine/dn463788.aspx ).

However, when I call AuthenticationContext.AcquireToken I get System.Threading.ThreadStateException saying: ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2' cannot be instantiated because the current thread is not in a single-threaded apartment.

EDITED:

Steps to reproduce:

  1. Create New MVC project with Organizational Authentication. Use your Windows Azure Domain and MSDN Account

  2. Add Actice Directory Authentication Library via NuGet

  3. Add action with the following code:

    public async Task<ActionResult> Index(){        
    
    
            AuthenticationContext ac = new AuthenticationContext("https://login.windows.net/domain.onmicrosoft.com");
            AuthenticationResult ar = ac.AcquireToken("https://domain.onmicrosoft.com/WindowsAzureADWebAPITest",
                                                        "a4836f83-0f69-48ed-aa2b-88d0aed69652",
                                                        new Uri("https://domain.onmicrosoft.com/myWebAPItestclient")
                                                    );
            // Call Web API
            string authHeader = ar.CreateAuthorizationHeader();
            HttpClient client = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://server.com:44353/api/Values");
            request.Headers.TryAddWithoutValidation("Authorization", authHeader);
            HttpResponseMessage response = await client.SendAsync(request);
            string responseString = await response.Content.ReadAsStringAsync();
    
            return View();
        }
    
  4. Run the code and reproduce the issue (AcqureToken method call).

Please suggest a fix.

Thank you!

Yuriy Frolov
  • 301
  • 1
  • 3
  • 10

1 Answers1

0

That particular overload of AcquireToken() is only usable in a native client app because the way it handles user authentication is by opening a browser window to login.windows.net. This requires the app to host a browser ActiveX control and that's why it needs an STA thread.

Now, in your example the code runs inside IIS on the server machine where hosting ActiveX controls is just not possible.

What you really need is delegation which is described here: http://www.cloudidentity.com/blog/2013/10/29/using-adals-acquiretokenby-authorizationcode-to-call-a-web-api-from-a-web-app/

Same author, just the different article.