Unauthorized exception message when trying to contact cognitive service in Azure - azure

I am trying to make a simple image analysis project using AI-tools for Visual Studio. I have created an Azure Cognitive Service as a ComputerVision service. It has been more than 10 minutes since I created it so the api keys should be valid. Then I created a new project by right clicking on it. But when I run it then I get this exception:
Please input image url or locate a local image file. If input is empty, example image will be used.
No url or file specified, use the example https://oxfordportal.blob.core.windows.net/vision/Analysis/1-1.jpg
One or more errors occurred.
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task`1.get_Result()
at GetImageDetailsService.Program.Main(String[] args) in C:\Users\X\Documents\Visual Studio 2017\Projects\CognitiveServiceTest\GetImageDetailsService\Program.cs:line 27
Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models.ComputerVisionErrorException: Operation returned an invalid status code 'Unauthorized'
at Microsoft.Azure.CognitiveServices.Vision.ComputerVision.ComputerVisionAPI.<DescribeImageWithHttpMessagesAsync>d__30.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Azure.CognitiveServices.Vision.ComputerVision.ComputerVisionAPIExtensions.<DescribeImageAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at Microsoft.CognitiveServices.Samples.ComputerVisionApiExtensions.<DescribeImage>d__2.MoveNext() in C:\Users\X\Documents\Visual Studio 2017\Projects\CognitiveServiceTest\GetImageDetailsService\ComputerVisionApiExtensions.cs:line 34
Apparently I am not authorized. What can be causing this?
I am logged into my Azure subscription and I have funds (I am using F0 tier). I have also checked that the region is correct and that the api key matches.
Edit: When I change the api key to something different in the application call then I still get an unauthorized exception.
Edit2: Added code that calls the api.
var client = new ComputerVisionApiExtensions(ComputerVisionSubscriptionKey, ComputerVisionRegion, null);
var result = client.DescribeImage(imagePath).Result;

I was getting the same thing and thought it would be worthwhile to submit an issue. I got a response for a fix, tested it, and it all worked!
To solve the issue, just put this.AzureRegion = GetRegion(region); inside the constructor in the ComputerVisionApiExtensions.cs file.

For the Computer Vision API type of Azure Cognitive Services, the request for analyzing an image would look like as follows:
POST https://{location-of-your-Computer-Vision-API}.api.cognitive.microsoft.com/vision/v1.0/analyze?visualFeatures=Categories&language=en
Host: {location-of-your-Computer-Vision-API}.api.cognitive.microsoft.com
Content-Type: application/json
Ocp-Apim-Subscription-Key: {subscription-key-under-the-same-region-of-your-Computer-Vision-API}
{"url":"https://oxfordportal.blob.core.windows.net/vision/Analysis/1-1.jpg"}
Note: You must use the same region in your REST call as you used to
get your subscription keys. For example, if you got your
subscription keys from westus, replace "westcentralus" in the URL
below with "westus".
If your Azure Cognitive Services is under East Asia, while you use the subscription key to request westcentralus.api.cognitive.microsoft.com instead of eastasia.api.cognitive.microsoft.com, then you could get 401 Access Denied and the following response:
{
"statusCode": 401,
"message": "Access denied due to invalid subscription key. Make sure to provide a valid key for an active subscription."
}
You could use fiddler to capture the network traces when running your application to narrow this issue. Also, you could follow the detailed tutorials under "RESOURCE MANAGEMENT > Quick start" of your Cognitive Services via Azure Portal.

Related

Office365 management API - Unable to subscribe

I want to capture the file operation events in OneDrive. So I created a tenant in azure and attached an App with it. I provided the necessary permissions to the app.
I am able to get the access token using the client key, secret created in portal.azure.com. This means that tenant, app and client secret is correct.
Now I am using Office365 management API to subscribe to the content type Audit.SharePoint but in response I get this message,
{'error': {'code': 'AF10001', 'message':
'The permission set () sent in the request does not include the expected permission.'}}
Can anybody help ?
Note: I am using free account. I am wondering if this error is coming because its a free account.
==============================================================
After updating the Azure AD license to P2. It could further but subscription still failed with following error.
{'error': {'code': 'StartSubscription [CorrId=a2c6111b-7908-486b-ab69-9f6ccac7679e][TenantId=9cef4c36-5f08-49c4-9f61-7d4a7860444c,ContentType=Audit.SharePoint,ApplicationId=13d763cd-abbc-456d-96e3-57af430f025f,PublisherId=46b472a7-c68e-4adf-8ade-3db49497518e]
[AppId', 'message': '3d763cd-abbc-456d-96e3-57af430f025f] failed. Exception:
Microsoft.Office.Compliance.Audit.DataServiceException: Tenant 9cef4c36-5f08-49c4-9f61-7d4a7860444c does not exist.\r\n
at Microsoft.Office.Compliance.Audit.API.AzureManager.
<GetSubscriptionTableClientForTenantAsync>d__52.MoveNext() in
d:\\dbs\\sh\\nibr\\0705_172037\\cmd\\2\\sources\\dev\\auditing\\src\\auditapiservice\\common\\AzureManager.cs:line 2116\r\n--- End of stack trace from previous location where exception was thrown
---\r\n
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.Office.Compliance.Audit.API.AzureManager.<GetAPISubscriptionAsync>d__22.MoveNext() in
d:\\dbs\\sh\\nibr\\0705_172037\\cmd\\2\\sources\\dev\\auditing\\src\\auditapiservice\\common\\AzureManager.cs:line 550\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at Microsoft.Office.Compliance.Audit.API.StartController.<StartSubscription>d__0.MoveNext() in d:\\dbs\\sh\\nibr\\0705_172037\\cmd\\1\\sources\\dev\\auditing\\src\\auditapiservice\\apifrontendservicerole\\Controllers\\StartController.cs:line 76'}}
====================================================
MS Support told to have atleast one license of exchange online. So I started basic trial version of Office 365 for two users in AD.
With this, I was able to start auditing for users/admins from compliance.microsoft.com
But on hitting the subscription API, I get following error.
"error":{"code":"StartSubscription [CorrId=0a7a9c46-012c-4510-aff6-888a840a74f6][TenantId=9cef4c36-5f08-49c4-9f61-7d4a7860444c,ContentType=Audit.SharePoint,ApplicationId=13d763cd-abbc-456d-96e3-57af430f025f,PublisherId=46b472a7-c68e-4adf-8ade-3db49497518e][AppId","message":"3d763cd-abbc-456d-96e3-57af430f025f] failed. Exception: Microsoft.Office.Compliance.Audit.DataServiceException: Tenant 9cef4c36-5f08-49c4-9f61-7d4a7860444c does not exist.\r\n at Microsoft.Office.Compliance.Audit.API.AzureManager.d__52.MoveNext() in d:\\dbs\\sh\\nibr\\0712_070108\\cmd\\y\\sources\\dev\\auditing\\src\\auditapiservice\\common\\AzureManager.cs:line 2116\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.Office.Compliance.Audit.API.AzureManager.d__22.MoveNext() in d:\\dbs\\sh\\nibr\\0712_070108\\cmd\\y\\sources\\dev\\auditing\\src\\auditapiservice\\common\\AzureManager.cs:line 550\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.Office.Compliance.Audit.API.StartController.d__0.MoveNext() in d:\\dbs\\sh\\nibr\\0712_070108\\cmd\\6\\sources\\dev\\auditing\\src\\auditapiservice\\apifrontendservicerole\\Controllers\\StartController.cs:line 76"}}
Note: I am using free account. I am wondering if this error is coming because its a free account.
According to ehowardl3:
Check Azure Active Directory licensing level, Azure Active Directory licensing requires either a Premium P1 or Premium P2 license to be able to pull event information through the Office 365 Management API. Microsoft does not grant permission to use the API to enable subscriptions for Free or Basic licensing options.
{'error': {'code': 'AF10001', 'message':
'The permission set () sent in the request does not include the expected permission.'}}
Once you get the required license, to resolve above error, according to documentation:
AF10001: The permission set ({0}) sent in the request did not include the expected permission ActivityFeed.Read.
So, make sure to grant ActivityFeed.Read permission in Azure Active Directory
Updated answer:
Microsoft.Office.Compliance.Audit.DataServiceException: Tenant *** does not exist
To resolve above mentioned exception, according to markjjo:
Make sure that unified auditing is enabled for your Office 365 organization, as per documentation, try the following PowerShell command:
Set-AdminAuditLogConfig -UnifiedAuditLogIngestionEnabled $true
References: Office 365 Management API - Postman sample and Can not connect with office 365

Get list of actual Azure Function endpoints from Powershell

I'm trying to get a full list of function endpoints in my Azure function app from a Powershell script. I can get the list of functions from the management.azure.com API, but it just has the function name, like...
/subscriptions/ea4a3766-c3a8-4b9c-xxxx-xxxxxxxxxxxx/resourceGroups/MyResourceGroup/providers/Microsoft.Web/sites/MyFunctionAppName/functions/FunctionName
But the function actually has an endpoint of (for instance) http://myfunctionapp.azurewebsites.net/api/allsources/{sourceName}
How can I get that endpoint name from the Azure management API from Powershell? It's displayed in the "Get Function URL" button on the portal, so I would imagine it has to be there somewhere.
EDIT: The suggested duplicate still doesn't provide the actual function endpoint. For instance, I have a function called CheckLock. Its endpoint per the "Get Function URL" button on the portal (and the one that I want) is: https://myfunctionapp.azurewebsites.net/api/account/lock/{id}?code=myfunctioncode
What I'm getting from the suggested duplicate is:
#{
name=CheckLock;
function_app_id=/subscriptions/ea4a3766-c3a8-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myresourcegroup/providers/Microsoft.Web/sites/myfunctionappname;
script_root_path_href=https://myfunctionappname.scm.azurewebsites.net/api/vfs/site/wwwroot/CheckLock/;
script_href=https://myfunctionappname.scm.azurewebsites.net/api/vfs/site/wwwroot/bin/Funcs.dll;
config_href=https://myfunctionappname.scm.azurewebsites.net/api/vfs/site/wwwroot/CheckLock/function.json;
secrets_file_href=https://myfunctionappname.scm.azurewebsites.net/api/vfs/data/functions/secrets/CheckLock.json;
href=https://myfunctionappname.scm.azurewebsites.net/api/functions/CheckLock;
config=;
files=;
test_data=
}
I got it. In the data for the function itself, the route is part of the properties.config object.
Request should look like this: https://management.azure.com/subscriptions/{subscriptionid}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{functionAppName}/functions/{functionName}?api-version=2016-08-01
In the return value is a properties object, and within that is config object. Underneath that is the route property which contains the trigger endpoint.
In Powershell, it's this:
$functionData = Invoke-RestMethod -Method Get -Uri $functionName -Headers $accessTokenHeader
$triggerUrl = "https://$functionAppName.azurewebsites.net/api/" + $functionData.properties.config.route
You can test it here: https://learn.microsoft.com/en-us/rest/api/appservice/webapps/getfunction
Hope this helps someone else! Thanks to those who contributed.
AZ PowerShell has introduced the Invoke-AzResourceAction cmdlet. This does exactly what it says on the tin - it allows you to invoke an action against an Azure Resource.
It's possible to get a Function Key and URL through the listkeys action as follows -
$functionApp = Get-AzWebAppSlot -Name $FunctionAppName -ResourceGroup $ResourceGroupName -Slot $Slot
$functionSecrets = Invoke-AzResourceAction -ResourceId ("{0}/functions/{1}" -f $functionApp.Id, $FunctionName) -Action "listkeys" -ApiVersion "2019-08-01" -Force
The variable $functionSecrets now contains two properties -
key: The default function-level key (will only work for $FunctionName).
trigger_url: The URL to trigger $FunctionName. Note that this property does not honour custom routes.
The url you can get via Get Function URL named trigger_url, seems you could not be able to get all of them in a function app, but you can get it for one specific function, See : Web Apps - List Function Secrets, the trigger_url in the response body is what you want.
POST https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/functions/{functionName}/listsecrets?api-version=2016-08-01
Response body:
{
"key": "xxxxxxxxxxxxxxxxxxx",
"trigger_url": "https://xxxxx.azurewebsites.net/api/HttpTrigger1?code=xxxxxxxxxxxxxxx"
}
Note: If you get an error like below, you need to add an application setting AzureWebJobsSecretStorageType : Files for your function app.
{
"error": {
"code": "Conflict",
"message": "System.InvalidOperationException: Runtime keys are stored on blob storage. This API doesn't support this configuration. Please change Environment variable AzureWebJobsSecretStorageType value to 'Files'. For more info, visit https://aka.ms/funcsecrets\r\n at Kudu.Core.Functions.FunctionManager.<GetKeyObjectFromFile>d__9`1.MoveNext() in C:\\Kudu Files\\Private\\src\\master\\Kudu.Core\\Functions\\FunctionManager.cs:line 141\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Kudu.Core.Functions.FunctionManager.<GetFunctionSecretsAsync>d__12.MoveNext() in C:\\Kudu Files\\Private\\src\\master\\Kudu.Core\\Functions\\FunctionManager.cs:line 220\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Kudu.Services.Functions.FunctionController.<GetSecrets>d__12.MoveNext() in C:\\Kudu Files\\Private\\src\\master\\Kudu.Services\\Functions\\FunctionController.cs:line 141"
}
}
Quick tip : if you can get azure context with Get-AzContext, you can get the access token to the header like this : (Get-AzContext).TokenCache[0].ReadItems().AccessToken

Error: The bot's MSA appId or password is incorrect

Hi I am working in Bot framework in that I am facing the issue when I am testing the bot in local bot emulator after publishing the bot in to azure, and in the bot emulator I am providing the published url and Microsoft appid and Microsoft secret in bot emulator. When I am connect to azure, it’s show the issue like below.
Command failed: 4294967295 System.AggregateException: One or more errors occurred. ---> System.Exception: Couldn't acquire lock, is another instance running at Squirrel.SingleGlobalInstance..ctor(String key, TimeSpan timeOut) at Squirrel.UpdateManager.<acquireUpdateLock>b__32_0() at System.Threading.Tasks.Task`1.InnerInvoke() at System.Threading.Tasks.Task.Execute() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Squirrel.UpdateManager.<CheckForUpdate>d__7.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Squirrel.Update.Program.<CheckForUpdate>d__8.MoveNext() --- End of inner exception stack trace --- at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions) at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification) at System.Threading.Tasks.Task`1.get_Result() at Squirrel.Update.Program.executeCommandLine(String[] args) at Squirrel.Update.Program.main(String[] args) at Squirrel.Update.Program.Main(String[] args) ---> (Inner Exception #0) System.Exception: Couldn't acquire lock, is another instance running at Squirrel.SingleGlobalInstance..ctor(String key, TimeSpan timeOut) at Squirrel.UpdateManager.<acquireUpdateLock>b__32_0() at System.Threading.Tasks.Task`1.InnerInvoke() at System.Threading.Tasks.Task.Execute() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Squirrel.UpdateManager.<CheckForUpdate>d__7.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Squirrel.Update.Program.<CheckForUpdate>d__8.MoveNext()<--- {}
POST 401 [conversationUpdate]
POST 401 [conversationUpdate]
Error: The bot's MSA appId or password is incorrect.
Edit your bot's MSA info
POST 401 [conversationUpdate]
Error: The bot's MSA appId or password is incorrect.
Edit your bot's MSA info
I removed the App Id and password and tried to run it locally then it’s working properly.
I researched around the internet and could not find any solutions that solves my problem. Please help.
Thanks in Advance
you can try using http://localhost:3979/api/Messages in your bot emulator but do not enter any kind of id and password and also remove it from your web.config
like this shown in below picture:
And hit ctrl+f5 and then try. It will start working on your local environment.
For remote debugging you need to use the ngork.
do let me know in case you need more clarification.
I solved the same issue with following way:
When the supported account types is set to single tenant, if you use a personal subscription instead of a Microsoft account, the Emulator would issue the error: The bot's Microsoft App ID or Microsoft App Password is incorrect..
Go AD Application registration : Select Authentication -> Supported Account Type -> Accounts in any organizational directory ( Any Azure AD Directory - Multitenant )
Check AD registration to see if the supported account types is set to Accounts in any organizational directory (Any Azure AD directory - Multitenant) and personal Microsoft accounts.
Apparently, the emulator allows to test local bots only and won't work with published/hosted bots. For published, i am testing on Azure on directly through the "Test in Web Chat" feature

Azure ACS : ACS50000 error on getting ACS token

I am using my custom STS as IDP with Azure ACS with a WCF service as RP.
I am getting the following error while getting the ACS token-
ACS10002: An error occurred while processing the SOAP body. ACS50000: There was an error issuing a token.
Trace ID: 810078c0-d799-4652-9152-cff0b730d4bd
Timestamp: 2013-10-19 14:18:29Z
The error is not giving me a clue as to what is happening actually. Is there a way to ask the MS support to use the trace id to get the error details.
Yes. If you have a support plan you can provide the trace ID you see along with your subscription and ACS namespace and they should be able to look up the issue.
Before you try support however, make sure you explore the exception for more than just the Message property. Usually there is a lot more information buried within the exception in the details or inner exception.
Here is a link to the ACS Error Codes on MSDN.

Sharepoint Application not running

I have this sharepoint application which was running absolutely fine. The Application Pool Identity was set to configurable for this sharepoint application.
But from yesterday i have been getting the following error while trying to access the application:
Cannot connect to the configuration database.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: Microsoft.SharePoint.WebPartPages.WebPartPageUserException: Cannot connect to the configuration database.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[WebPartPageUserException: Cannot connect to the configuration database.]
Microsoft.SharePoint.ApplicationRuntime.SPRequestModule.EnsureInitialize(HttpRequest request) +544
Microsoft.SharePoint.ApplicationRuntime.SPRequestModule.BeginRequestHandler(Object oSender, EventArgs ea) +2347
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +68
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
The application had the credentials of a user who has now left our organization. So i decided to key in my credentials for the same.
But i am still facing the same error !!
I have given all the rights to my user that the other user had under the user management (administrative tools).
Can someone please help !!
Whats going wrong ??
Please verify that your application pool account has "Connect" permission on the SharePoint_Config database.

Resources