Azure Managed Identity Token couldn't produce from local - azure

This is a continuation of the ticket Restrict Access with Azure Managed Identity in .NET Core Web API where I configured a .NET Core Web API to secured with user-assigned Azurre Managed Identity. This Web API has been deployed as https://epd-api.azurewebsites.net.
Now I have a locally running/debugging .NET Core WebApp trying to access the managed identity token for above azue deployed Web API as below.
string userAssignedClientId = "<<managed-identity clientid>>";
var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions { ManagedIdentityClientId=userAssignedClientId });
var accessToken = await credential.GetTokenAsync(new TokenRequestContext(new[] { "https://epd-api.azurewebsites.net/.default" }));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.Token);
It's breaking at line 'credential.GetTokenAsync()' with below exceptionn message.
AuthenticationFailedException: Azure CLI authentication failed due to
an unknown error. See the troubleshooting guide for more information.
https://aka.ms/azsdk/net/identity/azclicredential/troubleshoot ERROR:
The command failed with an unexpected error. Here is the traceback:
ERROR: Get Token request returned http error: 400 and server response:
{"error":"invalid_resource","error_description":"AADSTS500011: The
resource principal named https://epd-api.azurewebsites.net was not
found in the tenant named DXC Production. This can happen if the
application has not been installed by the administrator of the tenant
or consented to by any user in the tenant. You might have sent your
authentication request to the wrong tenant.\r\nTrace ID:
b537e8c2-c1a8-44ff-a363-d162cd15e101\r\nCorrelation ID:
507df083-138c-4848-b446-40631732a181\r\nTimestamp: 2022-09-13
06:52:22Z","error_codes":[500011],"timestamp":"2022-09-13
06:52:22Z","trace_id":"b537e8c2-c1a8-44ff-a363-d162cd15e101","correlation_id":"507df083-138c-4848-b446-40631732a181","error_uri":"https://login.microsoftonline.com/error?code=500011"}
Traceback (most recent call last):
Once I deployed my Web APP in Azure, the error message is different as below.
Connection ID "15636497907840976997", Request ID
"80000866-0000-d900-b63f-84710c7967bb": An unhandled exception was
thrown by the application.
Exception: Azure.Identity.AuthenticationFailedException:
ManagedIdentityCredential authentication failed: Service request
failed. Status: 500 (Internal Server Error)
Content:
Headers: Date: Tue, 13 Sep 2022 07:39:11 GMT Server: Kestrel
Transfer-Encoding: chunked X-CORRELATION-ID: REDACTED Content-Type:
application/json; charset=utf-8
See the troubleshooting guide for more information.
https://aka.ms/azsdk/net/identity/managedidentitycredential/troubleshoot
---> Azure.RequestFailedException: Service request failed. Status: 500 (Internal Server Error)
Content:
Headers: Date: Tue, 13 Sep 2022 07:39:11 GMT Server: Kestrel
Transfer-Encoding: chunked X-CORRELATION-ID: REDACTED Content-Type:
application/json; charset=utf-8
at Azure.Identity.ManagedIdentitySource.HandleResponseAsync(Boolean
async, TokenRequestContext context, Response response,
CancellationToken cancellationToken) at
Azure.Identity.ManagedIdentitySource.AuthenticateAsync(Boolean async,
TokenRequestContext context, CancellationToken cancellationToken)
at Azure.Identity.ManagedIdentityClient.AuthenticateAsync(Boolean
async, TokenRequestContext context, CancellationToken
cancellationToken) at
Azure.Identity.ManagedIdentityCredential.GetTokenImplAsync(Boolean
async, TokenRequestContext requestContext, CancellationToken
cancellationToken) --- End of inner exception stack trace --- at
Azure.Identity.CredentialDiagnosticScope.FailWrapAndThrow(Exception
ex, String additionalMessage) at
Azure.Identity.ManagedIdentityCredential.GetTokenImplAsync(Boolean
async, TokenRequestContext requestContext, CancellationToken
cancellationToken) at
Azure.Identity.ManagedIdentityCredential.GetTokenAsync(TokenRequestContext
requestContext, CancellationToken cancellationToken) at
Azure.Identity.DefaultAzureCredential.GetTokenFromSourcesAsync(TokenCredential[]
sources, TokenRequestContext requestContext, Boolean async,
CancellationToken cancellationToken) at
Azure.Identity.DefaultAzureCredential.GetTokenImplAsync(Boolean async,
TokenRequestContext requestContext, CancellationToken
cancellationToken) at
Azure.Identity.CredentialDiagnosticScope.FailWrapAndThrow(Exception
ex, String additionalMessage) at
Azure.Identity.DefaultAzureCredential.GetTokenImplAsync(Boolean async,
TokenRequestContext requestContext, CancellationToken
cancellationToken) at
Azure.Identity.DefaultAzureCredential.GetTokenAsync(TokenRequestContext
requestContext, CancellationToken cancellationToken) at
ManagedIdentityWeb.Pages.IndexModel.OnGetAsync() in
C:\Users\jmathews4\Source\Repos\ManagedIdentityAPI\ManagedIdentityWeb\Pages\Index.cshtml.cs:line
36 at
Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.ExecutorFactory.NonGenericTaskHandlerMethod.Execute(Object
receiver, Object[] arguments) at
Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeHandlerMethodAsync()
at
Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeNextPageFilterAsync()
at
Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.Rethrow(PageHandlerExecutedContext
context) at
Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.Next(State&
next, Scope& scope, Object& state, Boolean& isCompleted)
at
Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeInnerFilterAsync()
at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker
invoker, Task lastTask, State next, Scope scope, Object state, Boolean
isCompleted) at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed
context) at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State&
next, Scope& scope, Object& state, Boolean& isCompleted)
at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker
invoker, Task lastTask, State next, Scope scope, Object state, Boolean
isCompleted) at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker
invoker, Task task, IDisposable scope) at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker
invoker, Task task, IDisposable scope) at
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint
endpoint, Task requestTask, ILogger logger) at
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext
context) at
Microsoft.AspNetCore.Server.IIS.Core.IISHttpContextOfT`1.ProcessRequestAsync()
Any clue here for troubleshoot?

It's trying to use the AZ CLI there and its refresh token has expired. Run az login again in the command line and try again.

Related

Acumatica and System Crash related to Push Notification Dispatch Errors

Does anyone understand this error or how to further troubleshoot? I see it on the system monitor screen, and the site crashes seconds after this error.
Level: Error
Source: PushNotifications
Event: Push notification queue dispatcher failed
Link to Screen: ~/Main?ScreenId=SM302010
Message: Push notification queue dispatcher failed TenantID:null, TransactionID:null
TenantID =
ContextScreenId = SM302010
SourceContext = PushNotifications
EventID = PushNotifications_DispatcherFailedEventId
Exception = System.Messaging.MessageQueueException (0x80004005): Operation was cancelled before it could be completed.
at System.Messaging.MessageEnumerator.MoveNext(TimeSpan timeout)
at PX.Data.PushNotifications.MsmqExtensions.MoveNextWithCancellation(MessageEnumerator queueObserver, CancellationToken cancellationToken, Nullable`1 timeout, Action`1 heartBeatDelegate)
at PX.PushNotifications.PrimaryQueue.MsmqPrimaryNotificationQueue.TryDropUnmatchedCommitFromBeginOfQueue(MessageEnumerator queueObserver, CancellationToken cancellationToken)
at PX.PushNotifications.PrimaryQueue.MsmqPrimaryNotificationQueue.TryGetNextTransactionId(CancellationToken cancellationToken, Message& message)
at PX.PushNotifications.PrimaryQueue.MsmqPrimaryNotificationQueue.ReadNextMessageTransaction(CancellationToken cancellationToken, EventsTransaction& messages)
at PX.PushNotifications.NotificationQueueDispatcher.ReadNextTransaction(CancellationToken cancellationToken, EventsTransaction& transaction)
at PX.PushNotifications.NotificationQueueDispatcher.Dispatch(CancellationToken cancellationToken)
This can error arise when site is restarted by IIS. I suppose your site crashes and this error was logged as the result of crash.

Request body too large

When I try to upload a 80mb file from postman to my local endpoint running in Visual Studio 2019 on IISExpress I get the following error:
The request filtering module is configured to deny a request that exceeds the request content length.
So I added this to applicationhost.config for the project:
<system.web>
<httpRuntime maxRequestLength="1050000" />
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824"/>
</requestFiltering>
</security>
This stop the error coming when I make the API request but now I just get a ServiceStack generated "snapshot" page telling me how long request took and the date but my actual endpoint is never hit.
Inside my logs I can see ServiceStack throwing this exception:
2020-07-20 01:57:56.0497||ERROR|ServiceStackHost|Request body too
large. Microsoft.AspNetCore.Server.IIS.BadHttpRequestException:
Request body too large. at
Microsoft.AspNetCore.Server.IIS.BadHttpRequestException.Throw(RequestRejectionReason
reason) at
Microsoft.AspNetCore.Server.IIS.Core.IISHttpContext.InitializeRequestIO()
at
Microsoft.AspNetCore.Server.IIS.Core.IISHttpContext.ReadAsync(Memory1 memory, CancellationToken cancellationToken) at Microsoft.AspNetCore.Server.IIS.Core.HttpRequestStream.ReadAsyncInternal(Memory1
buffer, CancellationToken cancellationToken) at
Microsoft.AspNetCore.WebUtilities.BufferedReadStream.EnsureBufferedAsync(Int32
minCount, CancellationToken cancellationToken) at
Microsoft.AspNetCore.WebUtilities.MultipartReaderStream.ReadAsync(Byte[]
buffer, Int32 offset, Int32 count, CancellationToken
cancellationToken) at
Microsoft.AspNetCore.WebUtilities.StreamHelperExtensions.DrainAsync(Stream
stream, ArrayPool1 bytePool, Nullable1 limit, CancellationToken
cancellationToken) at
Microsoft.AspNetCore.WebUtilities.MultipartReader.ReadNextSectionAsync(CancellationToken
cancellationToken) at
Microsoft.AspNetCore.Http.Features.FormFeature.InnerReadFormAsync(CancellationToken
cancellationToken) at
Microsoft.AspNetCore.Http.Features.FormFeature.ReadForm() at
Microsoft.AspNetCore.Http.DefaultHttpRequest.get_Form() at
ServiceStack.Host.NetCore.NetCoreRequest.get_FormData() in
C:\BuildAgent\work\3481147c480f4a2f\src\ServiceStack\Host\NetCore\NetCoreRequest.cs:line
167 at
ServiceStack.HttpRequestExtensions.GetFlattenedRequestParams(IRequest
request) in
C:\BuildAgent\work\3481147c480f4a2f\src\ServiceStack\HttpRequestExtensions.cs:line
555 at ServiceStack.Host.RestHandler.CreateRequestAsync(IRequest
httpReq, IRestPath restPath) in
C:\BuildAgent\work\3481147c480f4a2f\src\ServiceStack\Host\RestHandler.cs:line
132 at ServiceStack.Host.RestHandler.ProcessRequestAsync(IRequest
req, IResponse httpRes, String operationName) in
C:\BuildAgent\work\3481147c480f4a2f\src\ServiceStack\Host\RestHandler.cs:line
89|url: |action:
So the Body length still needs to be set somewhere but everywhere I look points back to the config I have already used.
Is there additional setting required or is this a ServiceStack issue?
I was missing this option in startup:
services.Configure<IISServerOptions>(options =>
{
options.MaxRequestBodySize = int.MaxValue;
});
services.Configure<KestrelServerOptions>(options =>
{
options.Limits.MaxRequestBodySize = int.MaxValue; // if don't set default value is: 30 MB
});

Visual Studio Team Services Build - Error 500 (was Visual Studio Online - VSO)

I don't know how to change or track the agent, or identify the reason of this error.
C:\a\1\s\RadMVCLab\Scripts\jquery.datatables\examples\examples_support\themes\smoothness\images\ui-bg_glass_95_fef1ec_1x400.png: Please contact your administrator. There was an error contacting the server.
Technical information (for administrator):
HTTP code 500: Internal Server Error
System.Exception: One or more errors occurred while performing a get operation for workspace ws_1_1;1c6d9554-2472-4494-8d67-d17901ca66b2
at Microsoft.TeamFoundation.DistributedTask.Task.Internal.Core.TfvcGetOperation.Execute(String sourceVersion)
at Microsoft.TeamFoundation.DistributedTask.Task.Internal.Core.TfvcHelper.SyncRepository(VersionControlServer server, Uri repositoryUrl, String workspaceName, String rootPath, WorkingFolder[] workingFolders, String sourceVersion, Boolean cleanRepository, String shelveset, String reshelveName, Boolean gatedRunCI, CancellationToken cancellationToken)
at Microsoft.TeamFoundation.DistributedTask.Task.Internal.Core.TfvcHelper.Sync(ITaskEndpoint endpoint, String localPath, Dictionary2 serverPathMapping, String sourceVersion, Boolean cleanRepository, String workspaceName, String shelveset, String reshelveName, Boolean runCI, CancellationToken cancellationToken)
at Microsoft.TeamFoundation.DistributedTask.Plugin.Build.TfvcSourceProvider.<>c__DisplayClass3_0.<PrepareRepositoryAsync>b__0()
Microsoft.TeamFoundation.DistributedTask.Agent.Common.AgentExecutionTerminationException: Prepare repository failed with exception. ---> System.Exception: One or more errors occurred while performing a get operation for workspace ws_1_1;1c6d9554-2472-4494-8d67-d17901ca66b2
at Microsoft.TeamFoundation.DistributedTask.Task.Internal.Core.TfvcGetOperation.Execute(String sourceVersion)
at Microsoft.TeamFoundation.DistributedTask.Task.Internal.Core.TfvcHelper.SyncRepository(VersionControlServer server, Uri repositoryUrl, String workspaceName, String rootPath, WorkingFolder[] workingFolders, String sourceVersion, Boolean cleanRepository, String shelveset, String reshelveName, Boolean gatedRunCI, CancellationToken cancellationToken)
at Microsoft.TeamFoundation.DistributedTask.Task.Internal.Core.TfvcHelper.Sync(ITaskEndpoint endpoint, String localPath, Dictionary2 serverPathMapping, String sourceVersion, Boolean cleanRepository, String workspaceName, String shelveset, String reshelveName, Boolean runCI, CancellationToken cancellationToken)
at Microsoft.TeamFoundation.DistributedTask.Plugin.Build.TfvcSourceProvider.<>c__DisplayClass3_0.b__0()
--- End of inner exception stack trace ---
at Microsoft.TeamFoundation.DistributedTask.Plugin.Build.TfvcSourceProvider.<>c__DisplayClass3_0.b__0()
at System.Threading.Tasks.Task.Execute()
Finishing Build

azure media services from blob storage

I find some relevant answers but none that explains if I really need all the code from the Azure Media Services teams example at https://azure.microsoft.com/en-us/documentation/articles/media-services-copying-existing-blob/
I just want to upload a file from blob to Azure Media Services. Like this:
var uploadFilePath = blobUrl;
var uploadAsset = _context.Assets.Create(Path.GetFileNameWithoutExtension(uploadFilePath), AssetCreationOptions.None);
var assetFile = uploadAsset.AssetFiles.Create(Path.GetFileName(uploadFilePath));
assetFile.Upload(uploadFilePath);
But I'm getting
AggregateException was unhandled by user code, "An exception of type
'System.AggregateException' occurred in mscorlib.dll but was not
handled in user code"
Stack trace
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean
includeTaskCanceledExceptions) at
System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout,
CancellationToken cancellationToken) at
Microsoft.WindowsAzure.MediaServices.Client.AssetFileData.Upload(String
path) at
UploadMediaServicesExample.Services.MediaHandler.AddFileToMediaServices(String
blobUrl) in
C:\Source\UploadMediaServicesExample\UploadMediaServicesExample\Services\MediaHandler.cs:line
51 at
UploadMediaServicesExample.Controllers.HomeController.UploadVideo(IEnumerable1
file) in
C:\Source\UploadMediaServicesExample\UploadMediaServicesExample\Controllers\HomeController.cs:line
24 at lambda_method(Closure , ControllerBase , Object[] ) at
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase
controller, Object[] parameters) at
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext
controllerContext, IDictionary2 parameters) at
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext
controllerContext, ActionDescriptor actionDescriptor, IDictionary2
parameters) at
System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult
asyncResult, ActionInvocation innerInvokeState) at
System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult2.CallEndDelegate(IAsyncResult
asyncResult) at
System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult
asyncResult) at
System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3d()
at
System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.b__3f()
Additional information: One or more errors occurred.
Here is the blob Uri which is public.. "https://mulimo.blob.core.windows.net/temporary-files/clip.mp4"
Asset file upload method not supporting upload from blobs. It is only working with local files. Regarding exception you should see message in inner exception message property. You can use azure media services extensions (or see how it is done there) https://github.com/Azure/azure-sdk-for-media-services-extensions to create asset from existing blob.

Getting the Azure service properties errors on dev environment

I would like to set the DefaultServiceVersion for my azure storage instance, so I wrote the following code:
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("CloudStorageConnectionString"));
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
var serviceProperties = blobClient.GetServiceProperties();
if (serviceProperties.DefaultServiceVersion != "2011-08-18")
{
serviceProperties.DefaultServiceVersion = "2011-08-18";
blobClient.SetServiceProperties(serviceProperties);
}
I then tried to run it with the development storage server, and got an exception (erroring in the dev server by the looks) from blobClient.GetServiceProperties()
Microsoft.WindowsAzure.StorageClient.StorageServerException was unhandled by user code
HResult=-2146233088
Message=Server encountered an internal error. Please try again after some time.
Source=Microsoft.WindowsAzure.StorageClient
StackTrace:
at Microsoft.WindowsAzure.StorageClient.Tasks.Task`1.get_Result()
at Microsoft.WindowsAzure.StorageClient.Tasks.Task`1.ExecuteAndWait()
at Microsoft.WindowsAzure.StorageClient.TaskImplHelper.ExecuteImplWithRetry[T](Func`2 impl, RetryPolicy policy)
at Microsoft.WindowsAzure.StorageClient.CloudBlobClient.GetServiceProperties()
at ConsoleApp.GetContainer() in c:\app\Program.cs:line 90
at ConsoleApp.Main() in c:\app\Program.cs:line 47
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
InnerException: System.Net.WebException
HResult=-2146233079
Message=The remote server returned an error: (500) Internal Server Error.
Source=System
StackTrace:
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at Microsoft.WindowsAzure.StorageClient.EventHelper.ProcessWebResponse(WebRequest req, IAsyncResult asyncResult, EventHandler`1 handler, Object sender)
InnerException:
Is it possible to set the DefualtServiceVersion with a dev server? I haven't tried with the real thing as I really only want to test if this solves another issue I'm having.
Based on the documentation here: http://msdn.microsoft.com/en-us/library/windowsazure/microsoft.windowsazure.storage.blob.cloudblobclient.getserviceproperties.aspx (scroll down to "Remarks" section), this operation is not currently supported on local storage. Also SetServiceProperties operation which enables/disables storage analytics is also not supported.

Resources