Azure AD two Apps SSO - azure-active-directory

Stackoverflow I need your help.
Introduction:
We have two applications that are available through separate domains. These two applications are currently provisioned using Azure AD and PKCE login.
Azure AD manages the clients.
My question now: is it possible to configure Azure AD to allow SSO through these two applications.
Customer logs into application A and switches to B and is logged in there immediately, so without entering PW again.
Somehow I haven't found a tutorial or something similar that looks at this case, maybe I'm searching for the wrong keywords.
Thanks a lot
Application A has A customers -> a.de -> Angular SPA
Application B has A and B customers -> b.de -> Angular SPA
Yeah, hmm, what I tried. I was looking for tutorials or something like that.
I Hope this is possible with Azure AD

I have found a solution.
However, this is not yet finally tested, so to enjoy with caution.
Hints:
The scopes must be enabled in the azure.portal for the applications otherwise it gets stuck in a kind of login loop.
portal.app-reg(not Enterprise APP).Api Permission
In the initial component in ngInit:
const activeAccount = this.authService.instance.getActiveAccount();
const activeAccountEmail = activeAccount?.username;
//loginhin for ssoSilent
const silentRequest: SsoSilentRequest = {
scopes: ['User.Read'], //a scope (aka "permission") refers to any aspect of a resource that an Access Token grants rights.
loginHint: activeAccountEmail
};
//silentsso on inital pageload/reload
this.authService.ssoSilent(silentRequest)
.subscribe({
next: (result: AuthenticationResult) => {
console.log('SsoSilent succeeded!');
},
error: (error) => {
console.error("ERROR: "+error);
this.authService.loginRedirect();
}
});

Related

Amplify shared user pool not working in one of two apps

I am using a Cognito User Pool, for SAML integration with my corporate Azure AD directory. Everything has been set up and is working fine locally, as well as on both dev and prod environments associated with one of the apps.
However, when I tried to deploy another app with exactly the same code and configuration, the app works fine locally (i.e. I am able to log in using my corporate credentials) but the deployed sites do not work - both dev and prod keep returning the error The user is not authenticated when the following code is run:
Auth.currentAuthenticatedUser()
.then(currentUser => setUser(currentUser))
.catch((error) => console.log(error));
One of the solutions in SO suggested that the user needs to be confirmed. There are two problems with that:
The account status is set to EXTERNAL_PROVIDER and cannot be altered, and
If the issue was with the user account (or the provider), the other instances (local as well as online) would also have thrown the error.
I configure the callbacks as follows:
awsconfig.oauth.redirectSignIn = `${window.location.origin}/`;
awsconfig.oauth.redirectSignOut = `${window.location.origin}/`;
Amplify.configure(awsconfig);
And I trigger the login using the following code, based on another answer:
<button onClick={() => Auth.federatedSignIn({provider: '<My corp provider string>'})}>
Again, the same code is working fine locally (though still using the same user pool).
Any idea why the user is not being considered authenticated for just these two environments? Any help is appreciated.

Struggling to get Playwright to work with Azure Active Directory Conditional Access

I'm working on standing up a Playwright testing framework around our front-end PHP application to prototype automated testing for our team. Our authentication is managed by Azure Active Directory with 2FA as well as Conditional Access for our devices. The problem I'm encountering is the conditional access not liking the pseudo-incognito Chromium browser used by Playwright. Below is the message I get while attempting my login in the Edge InPrivate window (same error message as Chromium):
I've gone through the authentication section on Playwright's documentation as well as searching, but I'm not having any luck with getting past the conditional access issue. The failing TypeScript code I'm currently running is:
import test from "#playwright/test";
const { chromium } = require('playwright');
test('Log into Application', async () => {
const userDataDir = '\UserData';
const context = await chromium.launchPersistentContext(userDataDir, { headless: false });
const page = await context.newPage();
await page.goto('https://MyApplication.com');
await page.pause();
})
Any help would be deeply appreciated.
According to last bulleted point in Grant controls | Microsoft Docs.
Conditional Access cannot consider Microsoft Edge in InPrivate mode as
a compliant device or an approved client app.
In normal chromium browser (not in private mode ) to work,you need to install and run a supported browser, based on your operating system. If you're using Windows 10, the supported browsers include Microsoft Edge, Internet Explorer, and Google Chrome.If you're using a different operating system, you can check the complete list of supported browsers.
(Or)
The error message may be because the Global admin was created an conditional access policy in the Office 365 tenant at your company due to security reason, so only specific device registered in Azure, will be allowed to use for you. So, in that case you should talk with the "IT HelpDesk" department at your company, and you should ask them to configure and allow all browsers there.
An administrator can make use of access controls to either grant or block access to resources : Grant controls
You may need to contact the admin to raise a support ticket from the Office 365 admin center for further investigation
Reference: Troubleshooting compliance error
If you have global admin rights,You can troubleshoot unexpected
sign-in outcomes related to Conditional Access using error messages
and Azure AD sign-ins log.
You can click on more details and see the information.
Sign in to the Azure portal as a global administrator, security administrator, or global reader
Browse toAzure Active Directory > Sign-ins.
Find the event for the sign-in to review. Add or remove filters .
The Conditional Access tab will show the specific policy or policies that resulted in the sign-in interruption.
You can see and check basic info, device details whether registered or not and other policy details that are not compliant .
For complete details of troubleshooting. Please check this Troubleshooting | Microsoft Docs for complete details of troubleshooting.
Reference:
You Can’t Get There From Here – Vince's Server Stuff (vincecarbone.com)

How to update Secret Token property in Azure AD Synchronization API?

I am trying to find a way how to programmatically change properties of Enterprise Application (non-catalogue app), specifically Secret Token and Tenant ULR in 'Provisioning' blade, allowing to synchronize user/group objects between AAD and an external app (e.g. SaaS app) that supports it.
My customer has a strict policy to rotate all secrets and keys in Azure in regular intervals, so they want to be able to have an automation runbook that would change that token in the app (it is actually an Azure Databricks instance that supports this sync) as well as in AAD.
I checked whether there was a direct PowerShell support but I couldn’t find a specific cmdlet for this scenario (tried both GA and preview versions of AAD PowerShell 2.0).
I found a good documentation page describing AAD Synchronization API - https://learn.microsoft.com/en-us/graph/api/resources/synchronization-overview?view=graph-rest-beta – however, I am unable to find, how to update the Secret Token property.
Ideally, I would like to see a code sample of a REST call on how change that specific property using Synchronization API. A PowerShell example would be even better. Any help is much appreciated. Thanks.
Here's how to do it for non-gallery SCIM apps:
PUT https://graph.microsoft.com/beta/servicePrincipals/99abefe8-3ad8-488f-b14f-df209cbc1ab3/synchronization/secrets
{
value: [
{ key: "BaseAddress", value: "xxxxxxxxxxxxxxxxxxxxx" },
{ key: "SecretToken", value: "xxxxxxxxxxxxxxxxxxxxx" }
]
}
Replace the GUID after servicePrincipals with your real servicePrincipal object ID.
For apps that aren't non-gallery SCIM apps, the credential names required can be discovered in the metadata -> configurationFields part of the synchronizationTemplate object:
https://learn.microsoft.com/en-us/graph/api/resources/synchronization-synchronizationtemplate?view=graph-rest-beta

How do I get the "Assigned Role" of a User in Azure Active Directory?

I am using Azure AD with a registered Application and I am using the Microsoft Graph API to query the AD.
The following code below tells which groups the User is Assigned to
var memberof = await graphClient.Users[xxx].MemberOf.Request().GetAsync();
I am using standard AD package and it seems that groups are somewhat restricted and I need to buy the "Premium AD Package" to use them fully.
So I don't want to use the group information. I am interested in the roles that I assign my users that I have put into my application manifest.
e.g
"appRoles": [
{
"allowedMemberTypes": [
"User"
],
"displayName": "Case Manager",
"id": "{A_Guid}",
"isEnabled": true,
"description": "Case Manager's can create and assign Cases to other users",
"value": "CaseManager"
},
So, how can I use the Graph Api to tell me if a user has a particular role ?
1. Microsoft Graph API
The ability to read all application specific roles assigned to a user (i.e. AppRoleAssignments) is only available as part of Microsoft Graph API beta endpoint currently AFAIK. This is not available as part of v1.0. You can read about versions here
As evident from name "beta", it's not expected to be a stable version that can be relied upon for production applications. Read more specific points in this SO Post by Marc LaFleur
Exact API (Microsoft Docs Reference):
GET https://graph.microsoft.com/beta/users/{id | userPrincipalName}/appRoleAssignments
I tried using GraphServiceClient (.NET SDK for Microsoft Graph) but wasn't able to find anything related to AppRoleAssignments. (probably because SDK uses metadata from stable 1.0 version and not the beta version)
In any case, if you can still test this, use Microsoft Graph Explorer or directly call the endpoint from C# code
string graphRequest = $"https://graph.microsoft.com/beta/users/{my user GUID}/appRoleAssignments";
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, graphRequest);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
HttpResponseMessage response = await client.SendAsync(request);
2. Windows Azure AD Graph API
Even though it's recommended to use Microsoft Graph API whenever possible, there are still some cases where Microsoft Graph hasn't caught up yet so you are forced to use Azure AD Graph API. Application management related cases are some of those.
So you could use this Azure AD Graph API. I quickly tested this from Azure AD Graph Explorer and it works fine.
https://graph.windows.net/{yourtenantid}/users/{id}/appRoleAssignments?api-version=1.6
Just like Microsoft Graph Library for .NET you can use Azure AD Graph Client Library for .NET and your code would look something like this..
aadgraphClient.Users["<user guid>"].AppRoleAssignments;
On a side note, since you've asked the question specifically for Microsoft Graph API, I've answered it accordingly.
At least for the currently signed in user for an application, you can always find the Application Roles assigned to them from the Role claims available as part of the access token from Azure Active Directory.
This although only helps with roles for current user and not in management sort of scenarios if you're trying to go across all users for an application. Here's a sample that reads role claims and does authorization based on App Roles for currently signed in user.
Authorization in a web app using Azure AD application roles & role claims
I just found a way to get roles of an user at an application level.
You can create application level roles by updating the manifest's appRoles array.
[azure/app registrations/<your-app>/manifest)]
I used Microsoft.Graph.Beta, to get access to service principals api.
var userRoles = await _client.Me.AppRoleAssignments.Request().GetAsync();
The above query would fetch all the application roles for the user.
var appRoleAssignments = await _Client.ServicePrincipals[<<application_objectId>>].Request().GetAsync();
The above query would fetch all the roles of an application assigned at manifest level.
And application object Id could be found at [azure/app registrations/<your-app>)] -> Object ID
And execute the below to get list of user roles
var roles = new List<string>();
if (appRoleAssignments != null && appRoleAssignments.AppRoles.Any())
{
var userRolesOfCurrentResource = userRoles.First(role => role.ResourceId == Guid.Parse(<<application object id>>));
if(userRolesOfCurrentResource!=null)
{
var role = appRoleAssignments.AppRoles.First(role => role.Id == userRolesOfCurrentResource.AppRoleId);
if (role!=null)
{
roles.Add(role.Value);
}
}
}

SharePoint 2013 Unauthorized exception for provider-hosted Apps

I receive "Unauthorized" exception on the host side for a provider-hosted App for SharePoint 2013.
Uri hostWeb = new Uri(Request.QueryString["SPHostUrl"]);
using (var clientContext = TokenHelper.GetS2SClientContextWithWindowsIdentity(hostWeb, Request.LogonUserIdentity))
{
clientContext.Load(clientContext.Web, web => web.Title);
clientContext.ExecuteQuery();
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
Certificates were installed, Anonymos access was disabled. I can't understand the reason of this problem.
I have ran into the exact same problem before... i resolved it by implementing OAuth and have it redirect to the app main page with "write" permission.
Response.Redirect(TokenHelper.GetAuthorizationUrl("mysharepoint.com", "Web.Write", "myapp.com/default.aspx"));
Basically what this does is that it'll authentication the login user with your sharepoint site, once it's authenticated, it'll redirect (with write permission) to your app site.
Here is how to implement OAuth: http://msdn.microsoft.com/en-us/library/office/jj687470(v=office.15).aspx
Looks like this is High Trust App. If you have exhausted the tips at http://msdn.microsoft.com/en-us/library/fp179932.aspx, then there is an illformed SPTrustedSecurityTokenIssuer. You can find out all of them using the below PS. Ideally it should be IssuerId#Realm. If there is one which is not, then remove that. But remember not to remove first one which is for workflows
Get-SPTrustedSecurityTokenIssuer | select Name,RegisteredIssuerName
First you have to Check user in 'Request.LogonUserIdentity'. actually this happens when your user does not have access to your site in IIS.
so to set the correct user in 'Request.LogonUserIdentity' follow the below steps:
open your IIS --> Authentication -->Anonymous Authentication --> edit--> Specific user [ User which you get in 'Request.LogonUserIdentity']. --> iisreset
now user have permission to access your IIS site.

Resources