Integration testing with Azure ADB2C - asp.net-core

We have a Web application that is protected by Azure ADB2C. Users must be logged in to access the application. When the user logs into the application we use the API connectors feature to go and fetch more user details using the email the user logged in with. These extra details are added to the token as custom attributes and are consumed by the web app inside the OnTokenValidated event.
When our code is deployed to either the Test/Staging or Production endpoints our integration tests are run against that endpoint. I can't spoof the authentication as the tests are talking to live endpoints. I need to authenticate the tests as if they are a real user.
I have looked around and have tried the ROPC flow that is suggested on similar posts. The trouble is with this solution is that it does not call the API connectors to get the extra user details that the 'normal' login flow would.
ROPC Solution:
Integration Test with Azure AD login
How can I make my integration tests authenticate with Azure ADB2C the same way a real user would so that the API connectors are called?
Any help/advice is greatly appreciated.
Thanks.

Thanks you Nasheen Kalam for the blog.
Based on the GIT reference for Integration Test for the Sign up and Sign in Pages
https://git.uwaterloo.ca/jmshahen/ece651-project/-/merge_requests/22
Below are the process:
Run authentication test with pre-defined user
Test Step:
1.Go to application URL: 127.0.0.1:3000
2. Redirect to Sign In page
3. Use registered email and password
4. Sign In
5. Verify Result
Expected Result:
Pass: when email, password is matched
Fail: Error message thrown in case of wrong combination
Run sign up process for new user
Test Steps:
Manually Remove user if already exists in DB
1.Go to application URL: 127.0.0.1:3000/signup
2. Use full name, email address and password
4. Sign Up
5. Verify Result
Test Data
User name: Test User01
User email: testuser#gmail.com
User Password:
usertest01
Verification text:
Test User01
Expected Result:
Pass: when new user is created
Fail: Error message thrown in case of user already exists

Related

Authentication with AzureAD via TestCafe Tests

I'm unable to authenticate / sign-in via AzureAD when running testCafe.
const testrole = Role(
'https://login.microsoftonline.com/',
async t => {
await t
.typeText(Selector('input').withAttribute('type', 'email'), *******)
.click(Selector('#idSIButton9'))
.typeText(Selector('input').withAttribute('type', 'password'), ********)
.click(Selector('#idSIButton9'));
},
{ preserveUrl: true }
);
The above steps work fine, however after entering the password I get a message saying:
"Unable to sign in to Outlook account, Error: AADSTS900561: The endpoint only accepts POST requests. Received a GET request."
From my initial search, it seems like something to do with 3rd party cookies on the browser. However, I'm unable to find a solution at this time.
Any idea how I get around this issue?
The Azure AD product team has always reminded me that it is a bad idea to try to automate sign in like that.
They will probably detect that you are a bot and start blocking your requests, even if you succeed.
Instead, to acquire access tokens you need to use either the client credentials flow (for app-only tokens) or the resource owner password credentials flow (for delegated user tokens).
Client credentials flow: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow
ROPC flow: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth-ropc
You have to take good care to secure the credentials used for testing.
And use a test tenant if possible.

Authentication using Azure AD, failing at last step accessing Skype for Business

I am following this guide (https://learn.microsoft.com/en-us/skype-sdk/ucwa/authenticationusingazuread) in order to access Skype for Business. Everything goes fine till the last part but let's do step by step. I am building my .net console application to do this but in order to explain you properly the problem I am having I will show you directly the http calls through Insomnia (software used to make http calls).
Step 1:
GET request towards https://webdir.online.lync.com/autodiscover/autodiscoverservice.svc/root
I hit 200 and as answer I receive this:
Step 2:
I use the user link.
So I send an http request to https://webdir1e.online.lync.com/Autodiscover/AutodiscoverService.svc/root/oauth/user and I get a 401 Unauthorized (everything still correct).
In the header of the answer it points me to the Identity Provider to ask for authorization (authorization_uri)
Step 3: I use that link to authorize my app, which has its own client_Id (that I hide in the following screenshot).
This is how I compose the call:
If I send this http request I get redirected to the page where it asks my personal login and by inserting my credentials I succesfully login and hit 404, where in the answer I receive back my access token.
Step 5: I use the access token towards the same AutodiscoverService link of step 1. This is to register my application. I hit 200 and I receive back the link to access Skype for Business.
Finally (and this is where things go wrong) I send a POST request towards the applications link with the Bearer token, and I receive a 403 Forbidden. I think I am following correctly the guide but I can't figure out why I can access the resource at the last step.
EDIT:
The permissions are granted. I hide the name since it contains the name of my company. But it is the same of the domain of my login.
So the token you generated authorizes you to access resources at https://webdir1e.online.lync.com which you've done to fetch a new set of resources including the "application" resouce which is on a DIFFERENT host: https://webpooldb41e14.infra.lync.com.
You actually have to get another OAuth token now which authorizes you for the application resource and then you can POST to that to generate your session in UCWA.
As a side note... If you've defined your own single-tenant application in Azure that has been granted rights to SkypeForBusinessOnline then I think you should be targeting authorization and authentication endpoints of the form:
https://login.microsoftonline.com/{tenantID}/oauth2/v2.0/authorize
https://login.microsoftonline.com/{tenantID}/oauth2/v2.0/token
Also I should add, if you're trying to write a trusted secure client that users in your company will use I would suggest looking up the Resource Owner Password Credentials auth flow. It allows you to directly hit the token endpoint I mentioned above and exchange username/password credentials for an access token. Then you can manage auto-discovery and application creation easily under the hood without getting re-directed back and forth to Azure.
https://learn.microsoft.com/mt-mt/azure/active-directory/develop/v2-oauth-ropc

Issue with "Resource owner password credentials grant" in Azure AD OAuth

Unable to get the access token by directly passing the username and password
Endpoint : https://login.microsoftonline.com/{tenant_id}/oauth2/token
grant_type: password
client_id: APPLICATION_ID
resource: https://graph.microsoft.com/.default
username: <username#microsoft.com>
password: <password>
Scope : openid
App is created in https://apps.dev.microsoft.com/
Getting Invalid grant error:
{
"error": "invalid_grant",
"error_description": "AADSTS70002: Error validating credentials. AADSTS50126: Invalid username or password\r\nTrace ID: 1ff96bc3-29c8-48f1-b7cc-f77c01525500\r\nCorrelation ID: 9821fdf5-25dc-4b07-84b3-f084194ea123\r\nTimestamp: 2018-09-14 20:04:01Z",
"error_codes": [
70002,
50126
],
"timestamp": "2018-09-14 20:04:01Z",
"trace_id": "1ff96bc3-29c8-48f1-b7cc-f77c01525500",
"correlation_id": "9821fdf5-25dc-4b07-84b3-f084194ea123"
}
UPDATE
Looks like there are more than one issues in play here.
You were using Azure AD token endpoint but had registered your application with Azure AD B2C by mistake (so case 2 as per my original answer).
Now after correcting that one, you should be using clientid and client secret for this new application that is registered with Azure AD.
Make sure you have added Microsoft Graph permissions for your application in Azure AD under "required permissions" and at the end of selecting appropriate permissions, make sure you press on the "Grant Permissions" button to give consent.
Looking at the error message and code you are getting (invalid_grant and "AADSTS70002: Error validating credentials. AADSTS50126"), I tried out ROPC exactly like you from Postman with a test application of my own and I tried multiple different combinations of passing wrong inputs, but the exact error codes you see come only in scenario where either my password or the username is incorrect (as the message says :)). In all other cases, error code will be different.
So, for username - make sure you give fully qualified name e.g. rohitsaigal#mydomain.onmicrosoft.com
for password - pretty obvious.
Give it another try based on instructions above and lets see how it goes.
ORIGINAL ANSWER
App is created in https://apps.dev.microsoft.com/
This means that your application is registered with Azure AD B2C.
Where you have registered your application isn't matching with the token endpoint you are using.
Case 1 - You are looking to use Azure AD B2C
Resource Owner Password Credentials Grant is still in public preview and you will need to follow the instructions provided by Microsoft here -
Configure the resource owner password credentials flow in Azure AD B2C
The endpoint you will hit to get the token will also be different that the one you have mentioned.
https://yourtenant.b2clogin.com/<yourtenant.onmicrosoft.com>/oauth2/v2.0/token?p=B2C_1_ROPC_Auth
Case 2 - You are looking to use Azure AD B2B
In this case you are using the correct end point to get the token, but you have wrongly registered your application with Azure AD B2C, you will need to change that and register your application from Azure Portal.
Instructions and details here - Integrating applications with Azure Active Directory
Just in case you need to read up on differences between Azure AD B2B v/s B2C - look at this SO Post
Here is another useful SO Post that gives information about registering your application through Azure Portal v/s https://apps.dev.microsoft.com (New application registration portal)
It seems like you didn't Grant Permissions to your app. Make sure all of the users are added to the app and ensure that you have the correct web.config parameters.
Also, ensure that the username and password are correct for the managed domain to connect. I've gotten this error before using the incorrect user. A regular azure global admin user may not be able to authenticate. You need to make sure you are using a CSP admin user.
This works https://learn.microsoft.com/en-us/azure/active-directory-b2c/add-ropc-policy?tabs=app-reg-ga&pivots=b2c-user-flow
But keep in mind that there are limitations like:
You cannot use when a password is expired or needs to be changed.
MFA is not supported
Social logins are not supported

Using Anypoint Access Management - Mulesoft APIs

Good morning I am using internal mulesoft Access Management APIs API Reference. I have successfully setup my postman to get the security token after login, and even executed successfully the /api/users/me. However, regardless of the access provided to the connection/login user, i can't get the full list of users (/api/users), receiving a Not authorized error. Let me explain the context. We are running on a federated platform, so we can't manage the users registration from the console, but need to wait until they login through SSO the first time to grant access to the correspondent business group and role. There is a complain as the users need to send the admin a note letting know of their successful first login, and afterwards wait to receive the access to the business group. After they login for the first time, their profiles are created in the root org. You can see them only when you are in the master organization. However, you can't get their new user id when you request a list of users of this master organization (/api/organizations/{orgId}/users). We are looking to execute this /api/users in a batch app that runs periodically and do a cross verification to get the users not associated to any orgid or role. This way we can avoid the requirement of the user sending a note to the admin. When I execute the /accounts/api/users, (API Call), we receive a 401 Unauthorized response, despite the token is correct as it is working fine with the others APIs. there is no mention of any other parameter or requirement in the API reference.
Please advise what can be done to solve this authorization error and complete our app. Thank you in advance.
Had the same issue but figured it out.
Instead of calling /api/users, you should be calling
https://anypoint.mulesoft.com/accounts/api/organizations/{orgId}/members
to get a list of users

How to authenticate user with just a Google account on Actions on Google?

Currently Google Assitant includes an easy way to request non-identifiable information about the user and a detailed flow to authenticate the user on a third party service through OAuth2. What about if all I need is have the user authenticate on Google itself? I tried filling in the account linking flow using Google OAuth2 information, but that seems not to work. If that last thing is supposed to work fluently than that would be enough of an answer.
Context: Users already authenticate only with Google on a related webpage. All I need is to link this already authenticated account with the less-authenticated account on Google Assistant.
Update, 25 Oct 2018:
As of 13 September 2018, there is now a much simpler way to access the user's account if your project uses Google Sign-In. Google Sign-In for Assistant will give you an ID Token with information about the user, including their Google ID, with their permission. This permission can be granted just using voice and is fairly streamlined.
You can combine this with a web- or app-based Google Sign-In to get their permission to access OAuth scopes if you need to access Google's APIs.
Update, 25 Oct 2017:
As of around 4 Oct or 7 Oct, Google has updated their policy (again) to restore language restricting OAuth endpoints that are valid. The terms now include
When implementing account linking using OAuth, you must own your OAuth endpoint
and it appears (from the comments below) that they now check for the Google endpoints to prevent this method from working.
At this point, the only thing you can do is setup your own OAuth2 server.
Original Post:
Broadly speaking, the auth tasks you need to do are in four parts:
Configure your project (in the cloud console) so that the Calendar API is enabled and that the OAuth2 client is correctly configured.
Configure the Action for account linking in the action console.
Configure the Actions on Google Integration for your API.AI Agent to indicate that sign-in is required.
When API.AI calls your webhook to fulfill an Intent, it will include an auth token as part of the JSON. You can use this token to make calls to the Google APIs you need.
Configure Cloud Project
You need to configure your cloud project so that it has access to the Google APIs you need and setup the OAuth2 Client ID, Secret, and Redirect URI.
Go to https://console.cloud.google.com/apis/dashboard and make sure you have the project you're working with selected. Then make sure you have the APIs you need enabled.
Select the "Credentials" menu on the left. You should see something like this:
Select "Create credentials" and then "OAuth client ID"
Select that this is for a "Web application" (it is... kinda...)
Enter a name. In the screen shot below, I used "Action client" so I remember that this is actually for Actions on Google.
In the "Authorized Redirect URIs" section, you need to include a URI of the form https://oauth-redirect.googleusercontent.com/r/your-project-id replacing the "your-project-id" part with... your project ID in the Cloud Console. At this point, the screen should look something like this:
Click the "Create" button and you'll get a screen with your Client ID and Secret. You can get a copy of these now, but you can also get them later.
Click on "Ok" and you'll be taken back to the "Credentials" screen with the new Client ID added. You can click the pencil icon if you ever need to get the ID and Secret again (or reset the secret if it has been compromised).
Configure the Action Console
Once we have OAuth setup for the project, we need to tell Actions that this is what we'll be using to authenticate and authorize the user.
Go to https://console.actions.google.com/ and select the project you'll be working with.
In the Overview, make your way through any configuration necessary until you can get to Step 4, "Account Linking". This may require you to set names and icons - you can go back later if needed to correct these.
Select the Grant Type of "Authorization Code" and click Next.
In the Client Information section, enter the Client ID and Client Secret from when you created the credentials in the Cloud Console. (If you forget, go to the Cloud Console API Credentials section and click on the pencil.)
For the Authorization URL, enter https://accounts.google.com/o/oauth2/v2/auth
For the Token URL, enter https://www.googleapis.com/oauth2/v4/token
Click Next
You now configure your client for the scopes that you're requesting. Unlike most other places you enter scopes - you need to have one per line. Then click Next.
You need to enter testing instructions. Before you submit your Action, these instructions should contain a test account and password that the review team can use to evaluate it. But you can just put something there while you're testing and then hit the Save button.
Configure API.AI
Over in API.AI, you need to indicate that the user needs to sign-in to use the Action.
Go to https://console.api.ai/ and select the project you're working with.
Select "Integrations" and then "Actions on Google". Turn it on if you haven't already.
Click the "Sign in required for welcome intent" checkbox.
Handle things in your webhook
After all that setup, handling things in your webhook is fairly straightforward! You can get an OAuth Access Token in one of two ways:
If you're using the JavaScript library, calling app.getUser().authToken
If you're looking at the JSON body, it is in originalRequest.data.user.accessToken
You'll use this Access Token to make calls against Google's API endpoints using methods defined elsewhere.
You don't need a Refresh Token - the Assistant should hand you a valid Access Token unless the user has revoked access.
After contacting Google the current situation seems to be that you should set up your own OAuth2 server, and then on the login screen of your OAuth2 server you should start the Google OAuth2 flow.
you have to have your own endpoint with Google Oauth2 - it is correct that you can't use Google Oauth itself as a provider. To use the Google OAuth service, you can use a "sign in with Google" button in your own endpoint instead.
Source: Contacting Google Actions on Google Support
Kind of speechless right now... as this seems to be a huge oversight on Google's part.
I am able to make it work after a long time.
We have to enable the webhook first and we can see how to enable the webhook in the dialog flow fulfillment docs
If we are going to use Google Assistant, then we have to enable the Google Assistant Integration in the integrations first.
Then follow the steps mentioned below for the Account Linking in actions on google:-
Go to google cloud console -> APIsand Services -> Credentials -> OAuth 2.0 client IDs -> Web client -> Note the client ID, client secret from there
-> Download JSON - from json note down the project id, auth_uri, token_uri
-> Authorised Redirect URIs -> White list our app's URL -> in this URL fixed part is https://oauth-redirect.googleusercontent.com/r/ and append the project id in the URL
-> Save the changes
Actions on Google -> Account linking setup
1. Grant type = Authorisation code
2. Client info
1. Fill up client id,client secrtet, auth_uri, token_uri
2. Enter the auth uri as https://www.googleapis.com/auth and token_uri as https://www.googleapis.com/token
3. Save and run
4. It will show an error while running on the google assistant, but dont worry
5. Come back to the account linking section in the assistant settings and enter auth_uri as https://accounts.google.com/o/oauth2/auth
and token_uri as https://accounts.google.com/o/oauth2/token
6. Put the scopes as https://www.googleapis.com/auth/userinfo.profile and https://www.googleapis.com/auth/userinfo.email
and weare good to go.
7. Save the changes.
In the hosting server logs, we can see the access token value and through access token, we can get the details regarding the email address.
Append the access token to this link "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" and we can get the required details in the resulting json page.
accessToken = req.get("originalRequest").get("data").get("user").get("accessToken")
r = requests.get(link)
print("Email Id= " + r.json()["email"])
print("Name= " + r.json()["name"])
You need to implement the Oauth protocol with whatever Google Assistant app you are developing. Let me be a bit more clear:
The user is on the assistant, you need to link him to any data
you have on your App side
The access to the data you have about
your user is protected by an access token
Google then needs to
ask you for this token to have access to this resource
When
google has the token it can send it to the app so it validates every
requests to get the resource.
This is why you need to implement your own oauth server (Honestly it is just two more endpoints in your application): the identity is checked on google's side, but the link between the user and the resource to access can only be known by you.
The process above is valid, you just need to specify your own token endpoint and your own auth endpoint.
Note that if you only want to check that the user is logged in into google and get his email, you just need to implement the streamlined identity flow that does not require the /auth endpoint (Automatically Sign Up Users with Streamlined Identity Flows)
That beeing said I implemented the flow but get the same error :
expected_inputs[0].possible_intents[0]: Transactions/Identity API must be enabled before using.