Receiving 403 error when accessing Azure function app locked down by Azure AD B2C - c#

We are using AD B2C for authentication on our web app. Last week we started receiving a 403.76 when calling our APIs that are hosted in Azure and locked down by Active Directory using our AD B2C tenant.
We haven't changed any config settings in AD when the change occurred. We rolled back all of our code which didn't help. We verified that our token is valid in jwt.io. We confirmed that our audience is correct and permissions was set properly in app registrations. We can see the easy auth error 403.76 when going in to "Diagnose and solve problems" section of the function app and drilling into 4xx errors.
The function app just does a GetAsync against Cosmos to get your user profile on sign in. However we aren't getting that far, as we are receiving a 403.76 when verifying our token with AD.
We should be able to do a GET against our API and receive data as we were before. Instead we get HTTP status 403 with a sub status of 76.
The error in "Diagnose and solve problems" section:
EasyAuth:AuthorizationCheckFailed. For more details, refer to HTTP Status Codes by EasyAuth Module

We banged our heads against a wall for five days, so I wanted to make sure this was posted on stack overflow for anyone else facing this issue. Especially since it affected customers.
After working with Microsoft 24/7 for the last three days, we finally received word that this was due to an issue on their end with EasyAuth. The workaround was to add this in our Configuration of the function app:
WEBSITE_AUTH_AAD_BYPASS_SINGLE_TENANCY_CHECK = true

Related

Azure - System Assigned Managed Identities for Function App

I have a function app and need to give it permission to write to blob/table storage. I turned on "System Assigned Managed Identity", and I set the following permissions for it with the scope being the Storage Account I need to access.
Storage Account Contributor
Storage Blob Data Owner
Storage Table Data Contributor
Storage Queue Data Contributor
UPDATE
I remove AZURE_CLIENT_ID, AZURE_CLIENT_SECRET and AZURE_TENANT_ID and then I receive an environment configuration error. I am not running this locally or debugging, I'm triggering it through API Management.
Executed 'Create' (Failed, Duration=1406ms)EnvironmentCredential authentication unavailable. Environment variables are not fully configured. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/environmentcredential/troubleshoot
^ The above link tells me I should add those environment variables back, but it seems like I shouldn't need them according to Peter Bon's answer below
One piece that I find very confusing (because I can't find good documentation on this anywhere) is that I am required by Azure to include three variables
AZURE_CLIENT_ID
AZURE_CLIENT_SECRET
AZURE_TENANT_ID
I am inferring that they are needed to actually allow my function app to access the storage account, which confused me at first because if I just gave it permission explicitly with assigned roles, why do I also need to create something completely outside of my function app to give it permission to do the thing I already gave it permission to do?
My question about this though is "HOW DO I MAKE THIS?" If I need to make an App Registration, what should the callback URL be? What should the API Permissions be? I gave it my best guess and did not get a satisfactory result.
App Registration:
API permissions -> Microsoft.Graph User.Read
Authentication -> https://<mydomain>.onmicrosoft.com/.auth/login/aad/callback
-> ID Tokens
-> Accounts in this organization
Secrets -> Generated new secret to use for AZURE_CLIENT_SECRET
Roles & Admissions -> Cloud application administrator
I then set AZURE_CLIENT_ID to be the app id of this App Registration, AZURE_CLIENT_SECRET to the app registration's secret and AZURE_TENANT_ID to my tenant ID.
Then in my code, I attempt to do the following
var tableUri = new Uri(string.Format("https://{0}.table.core.windows.net/", storageAccountName));
var credential = new DefaultAzureCredential(options);
services.AddScoped(x => new TableServiceClient(tableUri, credential));
And it fails when accessing my table storage with the following error:
Executed 'Create' (Failed, Id=<id>, Duration=2108ms)Server failed to authenticate the request. Please refer to the information in the www-authenticate header.RequestId:<id>Time:2022-10-21T12:15:21.6998519ZStatus: 401 (Server failed to authenticate the request. Please refer to the information in the www-authenticate header.)ErrorCode: InvalidAuthenticationInfoContent:{"odata.error":{"code":"InvalidAuthenticationInfo","message":{"lang":"en-US","value":"Server failed to authenticate the request. Please refer to the information in the www-authenticate header.\nRequestId:<id>\nTime:2022-10-21T12:15:21.6998519Z"}}}Headers:Server: Microsoft-HTTPAPI/2.0x-ms-request-id: <id>x-ms-error-code: REDACTEDWWW-Authenticate: Bearer authorization_uri=https://login.microsoftonline.com/<tenant_id>/oauth2/authorize resource_id=https://storage.azure.comDate: Fri, 21 Oct 2022 12:15:21 GMTContent-Length: 279Content-Type: application/json
and if I update the Authentication redirect to
https://storage.azure.com
then I get the following error:
Executed 'Create' (Failed, Id=<id>, Duration=2349ms)This request is not authorized to perform this operation using this permission.RequestId:<request>Time:2022-10-21T13:14:29.0955823ZStatus: 403 (Forbidden)ErrorCode: AuthorizationPermissionMismatchContent:{"odata.error":{"code":"AuthorizationPermissionMismatch","message":{"lang":"en-US","value":"This request is not authorized to perform this operation using this permission.\nRequestId:<id>\nTime:2022-10-21T13:14:29.0955823Z"}}}Headers:Cache-Control: no-cacheTransfer-Encoding: chunkedServer: Windows-Azure-Table/1.0,Microsoft-HTTPAPI/2.0x-ms-request-id: <id>x-ms-client-request-id: <id>x-ms-version: REDACTEDX-Content-Type-Options: REDACTEDDate: Fri, 21 Oct 2022 13:14:28 GMTContent-Type: application/json; odata=minimalmetadata; streaming=true; charset=utf-8
I am honestly pretty confused at this point, can someone please help me understand how to successfully set up system assigned managed identities?
UPDATE WITH ANSWER
figured it out w/ suggestion from Peter.. so, I'm not a C# developer, but have a programming background & am doing devops for this project, another group is coding the application. I didn't realize that they had specifically used new EnvironmentCredential(); in their code, since they emphasized always needing to use DefaultAzureCredential but the EnvironmentCredential forces the setting of AZURE_CLIENT_ID. This also explains our issue w/ using DefaultAzureCredential because it goes through the list like you linked in the answer, so it sees AZURE_CLIENT_ID is set, and doesn't bother going for MI even though MI has the right permissions.
When using a managed identity you should not provide these env variables. It would also defeat the purpose of not having to store a secret. They are not required in that scenario. It is just one of the many ways DefaultAzureCredential tries to get valid credentials. See this section. If you do not provide them, it will fall back trying to use a managed identity.

ASP.NET hosted on Centos7 with Windows authentication - GSSAPI: Feature not available

We have ASP.NET backend server running on .NET 5, its hosted on Centos7 and we have some issues with Windows AD authentication.
We have followed this tutorial https://learn.microsoft.com/en-us/aspnet/core/security/authentication/windowsauth?view=aspnetcore-5.0&tabs=visual-studio#kestrel, meaning that we have added AddAuthentication + AddNegotiate and UseAuthentication to our Startup.cs, host machine - Centos7 is in domain, we have also set the KRB5_KTNAME, it points to the existing keytab file, which we have generated on the domain controller.
When i use command kinit username#DOMAIN.COMPANY.COM and then fill out my password, everything seems to be ok, i also see some ticket, when i invoke klist command.
But for some reason, our ASP.NET server is unable to authenticate me, when i open its url in a browser, fill out my credentials, i get the following error:
2021-06-21 07:51:55.4321|ERROR|Microsoft.AspNetCore.Authentication.Negotiate.NegotiateHandler|An exception occurred while processing the authentication request. Interop+NetSecurityNative+GssApiException: GSSAPI operation failed with error - Unspecified GSS failure. Minor code may provide more information (Feature not available).
I have completely no idea what this error means and i am unable to google any meaningful results, do you have any ideas?
Thank you!

DocuSign C# API - USER_LACKS_MEMBERSHIP error for every token-authenticated request

We had a working application, we went through the go-live process, and everything was running live for several days. Then we started getting SSL errors, and we saw that the nuget package for the DocuSign package had an update (I believe this was all for the 11/13/2019 2019 certificates auto-update), so we updated our code, but now every request returns the USER_LACKS_MEMBERSHIP error for every token-authenticated request.
Things I can confirm are not the issue:
We have authenticated the app via account.docusign.com and the oauth signature impersonation scope, and the testing and live paths are in the API approved Redirect URIs.
We have the correct base path in the configuration (https://na3.docusign.net, as shown on our Apps and Keys page)
The base path did not change after we get the token back (The BaseUri on the Account object matches what we started with)
We are using the correct user for the configuration (The value labeled "API Username" in the Apps and Keys page is entered as "IMPERSONATED_USER_GUID" in appsettings.json and successfully used in creating the token as parameter UserID, which also matches our user account's ID shown in the backend, so we are not confusing it with TARGET_ACCOUNT_ID or CLIENT_ID, and shuffling those around causes errors much earlier at the token generation step).
We only have one user: the administrator of the DocuSign account. Their ID appears in the API configuration labeled as "API Username". The DocuSign administration backend doesn't display a membership tab anywhere for us to correct any possible issues with a user lacking membership. As far as I can tell, Membership is a higher tier account option than what we're paying for, so I'm confused how we could be having problems with a feature we haven't bought.
We get this error for checking envelope status. We get this error for trying to create new envelopes. We get this error for trying to get Account information. The only thing we can do is get an authentication token, but then that token can't be used to make any further authenticated requests.
Is there anything I'm missing that could be causing this other than some database error on DocuSign that I can't correct through the tools available to me? The package update changed the order of which class constructor accepts the ApiClient object, and there's a new AccessToken field on the Configuration class (which I filled out, but doesn't seem to have any effect, since we're still adding the Authorization/Bearer header manually). I'm out of ideas on what to try next.
Are you using the production environment or the demo environment?
I suspect that what's happening is that you are getting them mixed. As the baseUrl should not be demo.docusign.net etc. if you're using production (as indicated by your na3.docusign.net address) but you must ensure that the same account/user from production is also used.
So, the 4 things to check:
userId
accountId.
baseURI
authURI (account-d.docusign.com vs. account.docusign.com)
All of these should match and be for the same account in the same env.

Azure AD Graph call for User creation failing with some obscure error

I have been told to raise a question about Azure AD Graph Api here instead of raising it as an issue for the corresponding GitHub sample repository, I hope Azure Graph API team monitors SO and can help us with this github sample issue
Some extra context for the problem:
We are using Microsoft.Azure.ActiveDirectory.GraphClient nuget to create and manage users in our Azure AD test tenant. Following this sample application
we can create and update users in Azure AD via Graph API. That was fine until some moment which happened about 2-3 days ago (not sure about the exact moment, we discovered the problem on Tuesday morning AU time. Last successful run was on Friday last week). It was 100% working code and to confirm that it's not our code - I ran through sample application again - it's broken now too. I've tested it with the latest GraphClient v2.1.0 and original one from sample app which is - v2.0.6
To simplify testing of the problem I've made a LINQ based sample with some secrets redacted ( you need to follow console app sample guide to put in your values if you want to run it, instead of original sample app)
Also here is the Fiddle captures (redacted) of
Authentication request-response (client-request-id: 88b2bbbd-94cd-498d-a147-caad05e16eb7)
User Creation failing Attempt
Few things to note in the fiddler captures - Azure AD Graph API doesn't return refresh token along with access token:
{"expires_in":"3599","token_type":"Bearer","scope":"UserProfile.Read",
"expires_on":"1441183928","not_before":"1441180028","resource":"https://graph.windows.net",
"access_token":"TOKEN WAS HERE"}
I can see the issue with the scope string here, but we are not setting any explict scope in GraphClient when calling for token as per Sample app ( and this code was fine before, as I mentioned early)
User creation response is clear in terms of what happens and why it happens
{"odata.error":
{"code":"Authorization_RequestDenied","message":
{"lang":"en","value":"Insufficient privileges to complete the operation."}
}
}
But it's not clear how to ask for extra permission scopes through any of these AuthenticationContext.AcquireToken Method overloads
Also it's strange that the very same code was fully functional before and is broken now, after some mysterious change?
So I have few questions:
How to add extra scope permissions in GraphClient library to get Graph API token with User Modification enabled. This is probably a band aid fix of the problem.
It looks like Azure AD tries to manage permissions for client apps in the portal. But there is no extra permissions for Native Client type of application. How can I explicitly update app permissions so the existing code can work again. Is it possible at all ?
Can anyone recommend other libraries to interact with GraphAPI, which allow the consumer to explicitly specify scope for the requested token ?
================Update================
Yes, I saw that consent flow documentation. Chasing the issue I've created new Azure AD tenant, added brand new application and added all possible rights, including all available application and delegation ones:
now it looks like this. I also
I can get a token with long list of scopes, e.g.
Directory.AccessAsUser.All
Directory.Read
Directory.Write
User.Read
User.ReadWrite
User.Read.All
User.ReadBasic.All
User.ReadWrite.All
user_impersonation
UserProfile.Read
--cut unrelated scopes--
But it still gives me 403 :
{"odata.error":
{"code":"Authorization_RequestDenied","message":
{"lang":"en","value":"Insufficient privileges to complete the operation."}
}
}
One thing worth to note - in the scope list there is no Directory.ReadWrite.All
But here docs says :
Directory.ReadWrite.All : Read and write directory data
================Update================
PS: Some technical request info for Azure AD engineers:
Authentication request-response has client-request-id: 88b2bbbd-94cd-498d-a147-caad05e16eb7.
Failed Graph call has client-request-id: 882f3918-0ddd-40fe-a558-866997e32b46 in response only
The issue here is that you have not properly configured your application to request the correct permissions to the Graph API.
To do this, you must go into the Azure Management Portal and configure your 'permissions to other applications' to include the scopes your app needs to be able to read/write to the directory.
We have some documentation here which should help you:
https://msdn.microsoft.com/en-us/library/azure/dn132599.aspx (Describes the consent flow)
https://msdn.microsoft.com/Library/Azure/Ad/Graph/api/graph-api-permission-scopes (describes the specific permissions that the graph API exposes that your application will need to request)
I hope this helps!

Twitter API + OAuth: Can't send status updates, getting 401

I'm trying to use Twitter's API and OAuth to send status updates (new Tweets). I am using Shannon Whitley .NET code example http://www.voiceoftech.com/swhitley/?p=681 (as recommended on the Twitter API docs). I can read (GET) using OAuth just fine, however when I try to send a status update via http ://twitter.com/statuses/update.xml (using a POST), it returns a 401 with the following XML:
<?xml version="1.0" encoding="UTF-8"?>
<hash>
<request>/statuses/update.xml</request>
<error>Read-only application cannot POST</error>
</hash>
I swear I have set up my application to use read and write, the authorise page at Twitter (http ://twitter.com/oauth/authorize) even says "The application TweeVerbs.com (Development) by would like the ability to access and update your data on Twitter."
Yet it's still saying "Read-only application cannot POST". WTF!?
I have googled this error message until I was blue in the face. I found somewhere that said to add the querystring paremeter oauth_access_type=write to the redirect URL which goes to the Twitter authorise page which I have done, but it still gives me a 401.
If it helps, here is the data that is getting sent back and firth as per the OAuth workflow:
Request Authorise Token:
http ://twitter.com/oauth/request_token?oauth_consumer_key=tViV8vAt4cqSKbGdPGWT7Q&oauth_nonce=2790042&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1244567068&oauth_version=1.0&oauth_signature=KzxcXN%2bQ0AJoAJ%2flQfzs8SLjC%2fQ%3d
Generated Authorize Redirect URL:
http ://twitter.com/oauth/authorize?oauth_token=EpyBg3nJGOmtmBjRUAsqqaGHARb2F2F2VcccqHkwio&oauth_access_type=write
Authorise Screen Message: "The application TweeVerbs.com (Development) by would like the ability to access and update your data on Twitter. This application plans to use Twitter for logging you in in the future. Sign out if you want to connect to an account other than Sironfoot."
Get Access Token:
http ://twitter.com/oauth/access_token?oauth_consumer_key=tViV8vAt4cqSKbGdPGWT7Q&oauth_nonce=2016804&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1244567166&oauth_token=EpyBg3nJGOmtmBjRUAsqqaGHARb2F2F2VcccqHkwio&oauth_version=1.0&oauth_signature=%2bEVQUxUPLT%2b%2bkfaG0Vq1YJZXcAw%3d
Status Update API call:
URL - http ://twitter.com/statuses/update.xml
POST data - oauth_consumer_key=tViV8vAt4cqSKbGdPGWT7Q&oauth_nonce=5707692&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1244567268&oauth_token=19130957-nb89DjZhjCAzcbHUa96yRWHqlQFQIJ0AKyXpqnHt1&oauth_version=1.0&status=HelloWorld&oauth_signature=WqA%2bWY0IxveeSJ7G3Ewy3whh1sE%3d
I don't know what the problem was, but I deleted my Application registration on Twitter (You have to register apps in Twitter to get OAuth keys etc.), and then recreated it. Now it works fine. Weird, probably a problem with Twitter screwing up.
I'm also using Tweetsharp (http://tweetsharp.com/), highly recommend it, it's got a nice fluent API. Note: switching over to Tweetsharp wasn't the fix, I had already switched over and had the same problem until I delete and recreated app registration on Twitter.
If you authorized your application to access your Twitter account when the application was set in "read only access" mode and you get the "Read-only application cannot POST" error after changing the application settings to be "read and write access" then you have to revoke access to the application on https://twitter.com/settings/connections and then reauthorize it. The "read only" access_token tends to be sticky until you revoke it.
Go to http://www.twitter.com/oauth_clients
Select your App.
Edit Application Setting.
Set Default Access type to Read & Write.
Save & Run.
Hope this helps.
plus also see if your system's CLOCK is synched with internet; on windows you can do it by adjusting date time settings
because if you CLOCK is not synched you will get 401 unauthorized exception; best of luck
cheers
I've dont that several times now, without succes, I'm getting a 401 exception while requesting an acces token from twitter.
I'm using Tweetsharp as well as you.

Categories