How to pre-create federated Azure AD (AAD) users in Azure AD B2C? - azure-active-directory

I have our main AAD federated to our Azure AD B2C using OpenID Connect. For metadata I'm using the following endpoint: https://login.microsoftonline.com/{tenant_id}/v2.0/.well-known/openid-configuration
This set up works fine when users are sign up. When a user signs up, a user is created in B2C. But I need to create these users in advance. For this purpose, I'm using Microsoft Graph APIs to create users. The following code creates a user in B2C but it is not correctly linked to AAD user. When I try to login with AAD user in B2C, it gives me following error
AADB2C99002: User does not exist. Please sign up before you can sign in.
var user = new User
{
AccountEnabled = true,
DisplayName = "Last, First",
Identities = new List<ObjectIdentity>()
{
new ObjectIdentity
{
SignInType = "federated",
Issuer = "https://login.microsoftonline.com/{tenant_id}/v2.0",
IssuerAssignedId = "{**unique_user_object_id_from_federated_active_directory**}"
}
},
PasswordPolicies = "DisablePasswordExpiration"
};

I demonstrated this scenario here in detail:
https://github.com/azure-ad-b2c/samples/tree/master/policies/link-local-account-with-federated-account

Related

Microsoft graph API: permission grant for application (app roles) (NOT delegate via Oauth2PermissionGrants)

We are using the Microsoft graph API (.net SDK).
We know that we can use GraphServiceClient.Oauth2PermissionGrants for delegated grant (in Azure AD app it's "Expose an API").
But when it comes to granting admin consent for application type (via app role of other applications), like below:
In the portal, we can just click "Grant admin consent for XXXX".
I could not figure out how to GraphServiceClient.PermissionGrants does not seem to be the one we are after.
Googled around, found the related answer Azure OAuth: Unable to programmatically create app with admin consent for permissions , which leads me to the actual API used https://learn.microsoft.com/en-us/graph/api/serviceprincipal-post-approleassignedto?view=graph-rest-1.0&tabs=csharp
In a nutshell, use app role assignment via AppRoleAssignedTo:
GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var appRoleAssignment = new AppRoleAssignment
{
PrincipalId = Guid.Parse("THE-OBJECT-ID-OF-THE-PRINCIPAL-OF-THE-AZURE-AD-APPLICATION-THAT-NEEDS-ACCESS"),
ResourceId = Guid.Parse("THE-OBJECT-ID-OF-THE-PRINCIPAL-OF-THE-AZURE-AD-APPLICATION-THAT-HAS-THE-APP-ROLE-DEFINED"),
AppRoleId = Guid.Parse("THE-ID-OF-THE-APP-ROLE-DEFINED-IN-THE-RESOURCE-ID-ABOVE")
};
await graphClient.ServicePrincipals["THE-OBJECT-ID-OF-THE-PRINCIPAL-OF-THE-AZURE-AD-APPLICATION-THAT-HAS-THE-APP-ROLE-DEFINED"].AppRoleAssignedTo
.Request()
.AddAsync(appRoleAssignment);

AAD - Owner password credential flow

Hi I am trying to use owner password credential flow by giving username and password and it is giving below error. I am using the native application as the client Id.
UserPasswordCredential credentials = new UserPasswordCredential(_userName, _password);
AuthenticationContext authContext = new AuthenticationContext(_authority);
var accessToken = await authContext.AcquireTokenAsync(_apiResourceId, _clientId, credentials);
accessToken.AccessToken;
AdalServiceException: AADSTS65001: The user or administrator has not consented to use the application with ID 'xxxxxxxx' named 'nativeclient'. Send an interactive authorization request for this user and resource
I have a scenario where I cannot use client credential flow. Is there anything I am missing as when I use the powershell client ID 1950a258-227b-4e31-a9cf-717495945fc2 it works. How can I consent this application on the context of user as I am not the tenant admin.
It depends on whether the permissions you have added require admin-consent.
You can see it on Azure portal:
If the permissions require admin-consent, you have to use an admin account to do the consent by clicking "Grant admin consent for {your tenant}" here:
If the permissions don't require admin-consent, you just need to use a non-admin account to do the consent by accessing https://login.microsoftonline.com/{your tenant}/oauth2/authorize?client_id={Client ID}&response_type=code&redirect_uri={Reply URL}&resource={Resource you want to access, for example: https://graph.microsoft.com/}&prompt=consent.
Besides, could you please provide more details the "scenario where I cannot use client credential flow"?

Does what you send in Scope Governs whether you can login with Microsoft Account using Azure AD V2 Endpoints

I have registered a application using the App Registration (Preview) Blade and added the Azure Service Management API as API Permissions I downloaded the MSAL based Sample from
https://github.com/azure-samples/active-directory-dotnet-webapp-openidconnect-v2
Now in startup.auth.cs if i change the Scope i.e keep openid and add https://management.azure.com and then run and try and Login with a Microsoft Account i get the following error
This Doesn't Look like a Work or School Email you cant Sign-in here with Personal Account use your work or School Account Instead.
if i remove the Scope for https://managment.azure.com and just keep Openid profile offline_access i get the Consent Screen and Login
new OpenIdConnectAuthenticationOptions
{
// The Authority represents the v2.0 endpoint - https://login.microsoftonline.com/common/v2.0
// The Scope describes the initial permissions that your app will need. See https://azure.microsoft.com/documentation/articles/active-directory-v2-scopes/
ClientId = clientId,
Authority = String.Format(CultureInfo.InvariantCulture, aadInstance, "common", "/v2.0"),
RedirectUri = redirectUri,
Scope = "openid https://management.azure.com/.default",
PostLogoutRedirectUri = redirectUri,
I am Expecting to have the user Login and Obtain a Token for management API , i am Looking for Reasons for getting the above Error is this Expected ? The Account that i am using exists in my directory as a Member . this works if i use a Managed user(user#tenant.onmicrosoft.com) to Login
Since personal MS accounts cannot be used to manage Azure subscriptions unless they are added to an Azure AD, you should use the organizations endpoint instead of common.
In v1 "common" meant any AAD tenant.
In v2 "common" means any AAD tenant + any personal MS account.
If you wanted only personal accounts, you can use "consumers".
https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-protocols-oidc#fetch-the-openid-connect-metadata-document
You can use "organizations" to allow any AAD tenant but disallow MS accounts.
Of course a user can just edit the URL and login with a personal MS account anyway, so you'll want to check the tenant id of the logged in user.
The tenant id for MS accounts is always 9188040d-6c67-4c5b-b112-36a304b66dad, per the docs: https://learn.microsoft.com/en-us/azure/active-directory/develop/id-tokens#payload-claims.
So check the idp claim.

Signing up new AAD B2C users with various emails to LiveID automatically?

I have a .Net Core 2.0 Web App that connects to Azure Graph, authenticates you via OpenID and adds new local accounts to the tenant. My issue is that when I add those new users, they might or might not have their various emails registered on microsoft, LiveID. Is there maybe a way of binding their emails to microsoft in case they're not already registered? In case this is not clear enough, have an example.
In case this is not clear enough, have an example :
I add a local user with those parameters to my tenant
{
"accountEnabled":true,
"creationType":"LocalAccount",
"displayName":"LccotCh222602",
"passwordProfile":{
"password":"Ar3g345%#3ha",
"forceChangePasswordNextLogin":false
},
"signInNames":[
{
"type":"userName",
"value":"TestAccount"
},
{
"type":"emailAddress",
"value":"TestAccount#gmail.com"
}
]
}
And now when I try to log in to my app here (image reference) the user is not found because he hasn't registered the TestAccount#gmail.com email in Microsoft yet.
I'd like to either add that email to Microsoft automatically or find a way around it. Any tips will be much appreciated.
The new register account should work for Azure AD B2C. Here are the steps which works well for me:
1.Register the account using the REST below:
POST:https://graph.windows.net/adb2cfei.onmicrosoft.com/users?api-version=1.6
authorization: bearer {access_token}
{
"accountEnabled":true,
"creationType":"LocalAccount",
"displayName":"LccotCh222602",
"passwordProfile":{
"password":"Ar3g345%#3ha",
"forceChangePasswordNextLogin":false
},
"signInNames":[
{
"type":"userName",
"value":"TestAccount"
},
{
"type":"emailAddress",
"value":"TestAccount#gmail.com"
}
]
}
2.Login with the new register account(TestAccount#gmail.com/Ar3g345%#3ha)
https://login.microsoftonline.com/ADB2CFei.onmicrosoft.com/oauth2/v2.0/authorize?p=B2C_1_B2C_SignUpOrSignIn&client_id=420a3a24-97cf-46ca-a882-f6c047b0d845&nonce=defaultNonce&redirect_uri=https%3A%2F%2Flocalhost%3A44316%2F&scope=openid&response_type=id_token&prompt=login
And to sign-in the local account with Email, please ensure that you have enable the email sign-in like below and sign-in the app with the policy:

Identity Server 3 AzureAd Claims not returning

I have a working Identity Server application, and I'm setting it up to work with Azure AD. I've got my Azure Ad App registration and I can authenticate with it properly.
Looking at this and trying to do something similar to store the 3rd party user IDs associated with a user, but I'm not getting the sub or nameIdentifier claims back from AAD.
Do I need to request these from AzureAD somehow? - Their docs seem to be to be saying that the "sub" claim is (or at least can be) returned: https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-token-and-claims#_subject. This article seems to say that sub isn't returned, but it's for multitenant applications, so I'm not too sure if that's relevant.
I'm sure I'm missing something simple, but can't find anything relevant on Google.
Cheers,
Alex
The article Work with claims-based identities is too old and this Azure AD token reference article should be right about the token claims in the token issued by Azure AD.
Based on the test, I could get the sub claim from Azure AD and it also issued by the IdentityServer3 like figure below:
Here is the code I configed for the IdentityServer3 for your reference:
var webApp = WebApp.Start("https://localhost:44333", app =>
{
app.UseIdentityServer(new IdentityServerOptions
{
SiteName = "NDC Demo",
SigningCertificate = cert,
Factory = factory,
AuthenticationOptions = new AuthenticationOptions
{
IdentityProviders = ConfigureAdditionalIdentityProviders,
EnableAutoCallbackForFederatedSignout = true
}
});
});
public static void ConfigureAdditionalIdentityProviders(IAppBuilder app, string signInAsType)
{
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
AuthenticationType = "aad",
Caption = "Azure AD",
SignInAsAuthenticationType = signInAsType,
Authority = "https://login.microsoftonline.com/{tenantId}",
ClientId = "{clientIdFromAzurePortal}",
RedirectUri = "{redirectUri}",
});
}
If you still have the problem, would you mind sharing the request to Azure AD which you can capture it using Fiddler.

Resources