0

So I'm trying to get some GraphAPI stuff working with my project here, as per this question:

How to get the JWT (using OpenIdConnect) from HttpContext, and pass to Azure AD Graph API

And following Microsoft code samples pretty closely, I'm getting an 'HttpContext.Current.get returned null' error.

I'm calling NaiveTokenCache (which is exactly as specified in Microsoft code samples here: "https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect/blob/master/TodoListWebApp/Utils/NaiveSessionCache.cs")

But when that class goes to load, I'm getting the above error.

I've implemented the IRequiresSessionState from the utility class that's attempting the API call, but I'm still getting the same error.

What am I doing wrong? I'm at a loss on this one.

Edit: So the Microsoft class runs fine if I call it from the controller. But as soon as flow of control moves to the utility class, I'm losing my session. How can I make sure that my utility class has the same session without passing it explicitly?

Edit #2: So my utility class runs the API call as an async method (it has to, the web token request calls are async). I'm assuming since it's async, a new thread is being split off. Now in this case, passing the HttpContext explicitly is my first instinct, but I can't serialize/deserialize the session, as the token cache requires. It's demanding a static reference! Sheesh.

Edit #3: So by design or bug, the HttpContext won't resolve after a call to await.

HttpContext.Current //this resolves
await foo()
HttpContext.Current //this doesn't
Scuba Steve
  • 1,541
  • 1
  • 19
  • 47
  • 1
    When calling async methods using await/async specify `.ConfigureAwait(true);` to ensure that the current context is re-captured when the thread resumes work. Example: `await doSomeTaskAsync().ConfigureAwait(true);`. Ideally though you should inject `HttpContextBase` into the classes that need to use it. – Igor Aug 01 '18 at 19:33
  • How would you recommend to go about the latter? – Scuba Steve Aug 01 '18 at 19:43
  • Depends on your DI/IoC framework... I prefer AutoFac which has a built in module you can register to do this. – Igor Aug 01 '18 at 19:44
  • Okay so the instructions from Igor didn't fix the issue. But I did find the culprit: https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect/issues/25 – Scuba Steve Aug 01 '18 at 20:07
  • Annd I have another case where I need the HttpContext (I need to call a challenge to authenticate from the Async method), and the HttpContext.Current is null, even with Igor's instructions. – Scuba Steve Aug 01 '18 at 21:59

0 Answers0