How to debug JWT and AuthorizeAttribute - asp.net-web-api
I am following this Microsoft Docs tutorial and everything appears to work upto the point where I call the web api with the access token using Postman.
To be specific:
I request a token, Azure AD redirects me to supply Username and Password
Credentials are accepted and a token is returned
I tell Postman to use the token and call the api
I get a 401
If I decode the token everything appears correct, i.e. the aud matches the Web API registration in AD B2C, User is correct, claims, etc.
Commenting out the [Authorize] attribute in my API works, data is returned so its something in the authorization of my API I think.
I'm not sure how I can debug the authentication process in ASP.NET Core Web API though. For example putting breakpoints in my controller doesn't work because my code doesn't even get that far.
UPDATE
In the Postman Console the Response Headers say: WWW-Authenticate:"Bearer error="invalid_token", error_description="The issuer is invalid"". The issuer is https://login.microsoftonline.com/<guid>/v2.0/.
UPDATE 2
Embarrassingly, as documented in the article, once I matched the AzureAdB2C.Instance setting in my appsettings.json with the Postman Auth Url the invalid_token error goes away but now I'm getting 500 errors: Unable to obtain configuration from..., Microsoft.IdentityModel.Protocols.ConfigurationManager<T>.GetConfigurationAsync(CancellationToken cancel).
BRICK WALL
The thread 0x5c30 has exited with code 0 (0x0).
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET https://localhost:44366/api/values
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.2.5\System.Net.Sockets.dll'.
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.2.5\Microsoft.Win32.Primitives.dll'.
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.2.5\System.Net.NameResolution.dll'.
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.2.5\System.Security.Cryptography.Encoding.dll'.
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.2.5\System.Collections.NonGeneric.dll'.
Exception thrown: 'System.Net.Http.HttpRequestException' in System.Net.Http.dll
Exception thrown: 'System.IO.IOException' in Microsoft.IdentityModel.Protocols.dll
Exception thrown: 'System.IO.IOException' in System.Private.CoreLib.dll
Exception thrown: 'System.IO.IOException' in System.Private.CoreLib.dll
Exception thrown: 'System.InvalidOperationException' in Microsoft.IdentityModel.Protocols.dll
Exception thrown: 'System.InvalidOperationException' in System.Private.CoreLib.dll
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.2.5\System.Diagnostics.StackTrace.dll'.
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.2.5\System.Reflection.Metadata.dll'.
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler:Error: Exception occurred while processing message.
System.InvalidOperationException: IDX20803: Unable to obtain configuration from: '[PII is hidden]'. ---> System.IO.IOException: IDX20804: Unable to retrieve document from: '[PII is hidden]'. ---> System.Net.Http.HttpRequestException: Response status code does not indicate success: 404 (Not Found).
at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)
--- End of inner exception stack trace ---
at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)
at Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.GetAsync(String address, IDocumentRetriever retriever, CancellationToken cancel)
at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
--- End of inner exception stack trace ---
at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.AuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme)
at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.AuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App\2.2.5\Microsoft.AspNetCore.Http.Extensions.dll'.
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 1438.8301ms 500 text/html; charset=utf-8
Prompted by #Sam's last comment and my earlier realization of matching authority domains, instead of matching the appsettings.json AzureAdB2C:Instance value to the Postman Auth Url value of https://login.microsoftonline.com/, I matched the Postman Auth Url value to the appsettings AzureAdB2C:Instance value of https://<mytenant>.b2clogin.com/.
Related
Error reading MIME multipart body part. ---> System.Web.HttpException: The client disconnected when file uploaded in web application
There is a strange behavior, user is unable to upload a file in web application getting below 'Error reading MIME multipart body part. System.IO.IOException: Error reading MIME multipart body part. ---> System.Web.HttpException: The client disconnected.' but the same file I am able to upload without any errors. We tried below options by going through the articles and similar error posts but no luck. I tried switching out the Task.Factory code: var task = Task.Factory .StartNew(() => parts = Request.Content.ReadAsMultipartAsync().Result.Contents, CancellationToken.None, TaskCreationOptions.LongRunning, // guarantees separate thread TaskScheduler.Default); with below var task = Task.Run(async () => await Request.Content.ReadAsMultipartAsync()); parts = task.Result.Contents; Increased max request limits in web.config like maxRequestLength="2147483647", maxAllowedContentLength="157286400". I see errors like below in logs Error reading MIME multipart body part. System.IO.IOException: Error reading MIME multipart body part. ---> System.Web.HttpException: The client disconnected. at System.Web.Hosting.IIS7WorkerRequest.EndRead(IAsyncResult asyncResult) at System.Web.HttpBufferlessInputStream.EndRead(IAsyncResult asyncResult) at System.Threading.Tasks.TaskFactory1.FromAsyncTrimPromise1.Complete(TInstance thisRef, Func`3 endMethod, IAsyncResult asyncResult, Boolean requiresSynchronization) I am unable to reproduce this error in any of my environments, not sure what is causing in user environment. Any suggestions?
Running into an error when TryMudBlazor is run on Chrome
Recently TryMudBlazor seems to run into problems on Chrome when trying out the examples from the MudBlazor site. This seems to be something that is happening more recently. Everything works fine on Microsoft Edge. Getting error: blazor.webassembly.js:1 System.AggregateException: One or more errors occurred. (Could not resolve type with token 0100006c from typeref (expected class 'Try.UserComponents.__Main' in assembly 'Try.UserComponents, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null')) ---> System.TypeLoadException: Could not resolve type with token 0100006c from typeref (expected class 'Try.UserComponents.__Main' in assembly 'Try.UserComponents, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null') at TryMudBlazor.Client.Program.Main(String[] args) --- End of inner exception stack trace ---
I got a suggestion to clear browser cookies and try it again on Chrome and that seemed to have worked.
Unable to load asset-classic ways already verified
I already try to run pub get, hot reload and my sentence is right. this is my error : Exception caught by image resource service The following assertion was thrown resolving an image codec: Unable to load asset: images/cover.jpg
Is there a AAD login web test that I can use for the Azure availability test as the one I am using is randomly generating context parameter errors?
We are running a web test that uses AAD to login to a web site. When run via Visual Studio the web test runs correctly. However, when run in Azure availability this generates missing context parameter errors. I have attached the error call stack. This is causing availability dips. The error is not specific to a Azure region. I need a web test that works. There is no try catch mechanism in web tests so I cannot filter out such errors. I can't upload or paste the web test but its a Azure AAD login web test. I expect the web test to work. However, I get the following errors: 2 primary requests, 0 dependant requests and 0 conditional rules failed Exception (subtype 'WebTestException') occured at (UTC) for Uri 'https://login.microsoftonline.com/kmsi', step #5 with the error 'Context parameter 'FormPostParam1.ctx' not found in test context', exception text 'Microsoft.VisualStudio.TestTools.WebTesting.WebTestException: Context parameter 'FormPostParam1.ctx' not found in test context at Microsoft.VisualStudio.TestTools.WebStress.HelperMethods.UpdateBindingSites(WebTestCaseContext testCaseContext, String preBoundString) at Microsoft.VisualStudio.TestTools.WebStress.WebTestInstrumentedTransaction.PerformRequestDataBinding() at Microsoft.VisualStudio.TestTools.WebStress.WebTestInstrumentedTransaction.Execute(WebTestCaseContext testCaseContext, AsyncCallback completionCallback, Object callerState)', stack trace ' at Microsoft.VisualStudio.TestTools.WebStress.HelperMethods.UpdateBindingSites(WebTestCaseContext testCaseContext, String preBoundString) at Microsoft.VisualStudio.TestTools.WebStress.WebTestInstrumentedTransaction.PerformRequestDataBinding() at Microsoft.VisualStudio.TestTools.WebStress.WebTestInstrumentedTransaction.Execute(WebTestCaseContext testCaseContext, AsyncCallback completionCallback, Object callerState)'. Exception (subtype 'WebTestException') occured at (UTC) for Uri '', step #6 with the error 'Context parameter '$HIDDEN1.code' not found in test context', exception text 'Microsoft.VisualStudio.TestTools.WebTesting.WebTestException: Context parameter '$HIDDEN1.code' not found in test context at Microsoft.VisualStudio.TestTools.WebStress.HelperMethods.UpdateBindingSites(WebTestCaseContext testCaseContext, String preBoundString) at Microsoft.VisualStudio.TestTools.WebStress.WebTestInstrumentedTransaction.PerformRequestDataBinding() at Microsoft.VisualStudio.TestTools.WebStress.WebTestInstrumentedTransaction.Execute(WebTestCaseContext testCaseContext, AsyncCallback completionCallback, Object callerState)', stack trace ' at Microsoft.VisualStudio.TestTools.WebStress.HelperMethods.UpdateBindingSites(WebTestCaseContext testCaseContext, String preBoundString) at Microsoft.VisualStudio.TestTools.WebStress.WebTestInstrumentedTransaction.PerformRequestDataBinding() at Microsoft.VisualStudio.TestTools.WebStress.WebTestInstrumentedTransaction.Execute(WebTestCaseContext testCaseContext, AsyncCallback completionCallback, Object callerState)'.
'DefaultAppPool' suffered a fatal communication error with the World Wide Web Publishing Service
I am getting Event Log entries every time I access the site: Event Type: Error Event Source: VsJITDebugger Event Category: None Event ID: 4096 User: NT AUTHORITY\NETWORK SERVICE Computer: COMPUTER-02 Description: An unhandled Microsoft .NET Framework exception occurred in w3wp.exe [2908]. Just-In-Time debugging this exception failed with the following error: Debugger could not be started because no user is logged on. Check the documentation index for 'Just-in-time debugging, errors' for more information. Data: 0000: 02 00 5c 80 ..\ System Logs Event Type: Error Event Source: W3SVC Event Category: None Event ID: 1002 Date: 28/03/2011 Time: 17:49:28 User: N/A Computer: COMPUTER-02 Description: Application pool 'DefaultAppPool' is being automatically disabled due to a series of failures in the process(es) serving that application pool. Application Log Event Type: Warning Event Source: W3SVC Event Category: None Event ID: 1011 Date: 28/03/2011 Time: 17:49:28 User: N/A Computer: COMPUTER-02 Description: A process serving application pool 'DefaultAppPool' suffered a fatal communication error with the World Wide Web Publishing Service. The process id was '3724'. The data field contains the error number. Data: 0000: 6d 00 07 80 m.. I have also followed the advice of Microsoft's Support site without luck. The Network Service account didn't have any problems accessing the registry. I need to run the site in IIS6 (instead of IIS Express 7.5) as the site runs ASP as well as ASP.NET I need the wildcard mapping for authentication in ASP. I have completely run out of ideas, as the site was fine in ASP.NET 3.5 (CLR v2...), but this upgrade has completely messed up by debugging. Any help will be much appreciated.
You will need WinDbg (Debugging Tools for Windows) and DebugDiag. Install DebugDiag and WinDbg Ensure you have copied the related framework's SOS.dll to the WinDbg directory. Add a rule to catch IIS/COM+ processes On first exceptions, create a full user dump. Limit of 10 Open the website and look at look at DebugDiag, you should find it starting to take full dumps. Once you have a few memory dumps, load WinDbg and click File->Open Crash Dump and load one of the memory dump. Type .load sos Type !clrstack You will get a stack trace of the error like: 0:016> .load sos 0:016> !clrstack PDB symbol for clr.dll not loaded OS Thread Id: 0xa60 (16) Child SP IP Call Site 01d2eb5c 7c81a251 [HelperMethodFrame: 01d2eb5c] System.Diagnostics.Debugger.LaunchInternal() 01d2ebac 7a0e0166 System.Diagnostics.Debugger.Launch()*** WARNING: Unable to verify checksum for mscorlib.ni.dll *** ERROR: Module load completed but symbols could not be loaded for mscorlib.ni.dll 01d2ebd8 04470176 ebiz.Global.Application_Start(System.Object, System.EventArgs) 01d2f1f8 791421bb [DebuggerU2MCatchHandlerFrame: 01d2f1f8] 01d2f1c4 791421bb [CustomGCFrame: 01d2f1c4] 01d2f198 791421bb [GCFrame: 01d2f198] 01d2f17c 791421bb [GCFrame: 01d2f17c] 01d2f3a0 791421bb [HelperMethodFrame_PROTECTOBJ: 01d2f3a0] System.RuntimeMethodHandle._InvokeMethodFast(System.IRuntimeMethodInfo, System.Object, System.Object[], System.SignatureStruct ByRef, System.Reflection.MethodAttributes, System.RuntimeType) 01d2f41c 79b3d689 System.RuntimeMethodHandle.InvokeMethodFast(System.IRuntimeMethodInfo, System.Object, System.Object[], System.Signature, System.Reflection.MethodAttributes, System.RuntimeType) 01d2f470 79b3d37c System.Reflection.RuntimeMethodInfo.Invoke(System.Object, System.Reflection.BindingFlags, System.Reflection.Binder, System.Object[], System.Globalization.CultureInfo, Boolean) 01d2f4ac 79b3bfed System.Reflection.RuntimeMethodInfo.Invoke(System.Object, System.Reflection.BindingFlags, System.Reflection.Binder, System.Object[], System.Globalization.CultureInfo) 01d2f4d0 79b43284 System.Reflection.MethodBase.Invoke(System.Object, System.Object[]) 01d2f4dc 67894f4d System.Web.HttpApplication.InvokeMethodWithAssert(System.Reflection.MethodInfo, Int32, System.Object, System.EventArgs)*** WARNING: Unable to verify checksum for System.Web.ni.dll *** ERROR: Module load completed but symbols could not be loaded for System.Web.ni.dll 01d2f500 678951cb System.Web.HttpApplication.ProcessSpecialRequest(System.Web.HttpContext, System.Reflection.MethodInfo, Int32, System.Object, System.EventArgs, System.Web.SessionState.HttpSessionState) 01d2f550 67b34175 System.Web.HttpApplicationFactory.FireApplicationOnStart(System.Web.HttpContext) 01d2f564 672bfe1c System.Web.HttpApplicationFactory.EnsureAppStartCalled(System.Web.HttpContext) 01d2f59c 672bfd3d System.Web.HttpApplicationFactory.GetApplicationInstance(System.Web.HttpContext) 01d2f5ac 672fbf28 System.Web.HttpRuntime.ProcessRequestInternal(System.Web.HttpWorkerRequest) 01d2f5e0 672fbccd System.Web.HttpRuntime.ProcessRequestNoDemand(System.Web.HttpWorkerRequest) 01d2f5f0 672fb2cd System.Web.Hosting.ISAPIRuntime.ProcessRequest(IntPtr, Int32) 01d2f5f4 6791c30c [InlinedCallFrame: 01d2f5f4] 01d2f668 6791c30c DomainNeutralILStubClass.IL_STUB_COMtoCLR(Int32, Int32, IntPtr) 01d2f7fc 791425a1 [GCFrame: 01d2f7fc] 01d2f86c 791425a1 [ContextTransitionFrame: 01d2f86c] 01d2f8a0 791425a1 [GCFrame: 01d2f8a0] 01d2f9f8 791425a1 [ComMethodFrame: 01d2f9f8] For me anyway, you can see that the Debugger.Launch() is right at the top, and low and behold, my code had it in. It seems that IIS doesn't like that at all if it is your first line of code!
If you are not familiar with WinDbg, you can still extract a lot of information from the dumps. You already have dumps created by DebugDiag. Launch VS, File -> Open -> File (Ctrl + O), select the .dmp file. VS2010 will than display couple of options to debug -- Mixed mode or Native Only. Choose Mixed mode, open threads window, identify thread that threw exception, look at the call stack. Sometimes you get to local variables for the thread, but don't count on that too much, as data might not be correct.