Azure B2C Graph API issue - azure

I am trying to run the sample at:
https://github.com/Azure-Samples/ms-identity-dotnetcore-b2c-account-management
And am receiving this error:
Enter command, then press ENTER: 7
Create a user with the custom attributes 'FavouriteSeason' (string) and 'LovesPets' (boolean)
Have you created the custom attributes 'FavouriteSeason' (string) and 'LovesPets' (boolean) in your tenant?
Code: Request_BadRequest
Message: One or more property values specified are invalid.
Inner error:
AdditionalData:
date: 2020-06-30T23:24:26
request-id: dad23cee-984b-439c-a943-9e1bc6be4c9b
ClientRequestId: dad23cee-984b-439c-a943-9e1bc6be4c9b
I have created the custom attributes and can clear see them in the tenant...it even returns their ids. I've setup the Graph access level appropriately (I believe).
Any ideas? Thank you!

In Code, you need to update Tenant id, client id, client secret and also give B2cExtensionAppClientId= “your application display name” in appsettings.json
You have to create two custom attributes in the B2C portal
I. FavouriteSeason (string)
II. LovesPets (boolean)
Use below code to create the user with the custom attribute
try
{
//Create user
var result = await graphClient.Users
.Request()
.AddAsync(new User
{
GivenName = "Casey",
Surname = "Jensen",
DisplayName = "Casey Jensen",
Identities = new List<ObjectIdentity>
{
new ObjectIdentity()
{
SignInType = "emailAddress",
Issuer ="AADCxPb2c.onmicrosoft.com",
IssuerAssignedId = "x#AADCxPb2c.onmicrosoft.com",
}
},
PasswordProfile = new PasswordProfile()
{
Password = b2c_ms_graph.Helpers.PasswordHelper.GenerateNewPassword(4, 8, 4)
},
PasswordPolicies = "DisablePasswordExpiration",
AdditionalData = extensionInstance
}) ;
Console.WriteLine(result);
string userId = result.Id;
Console.WriteLine(result.Id);
Console.WriteLine($"Created the new user. Now get the created user with object ID '{userId}'...");

Can find it on your registered App on Azure AD B2C:
Click on "API Permissions" on left panel.
Then Chose "APIs my organization uses".
You can find the value under name "b2c-extensions-app. Do not modify. Used by AADB2C for storing user data.".

Related

Assign AD Group to Azure AD Application Role using Graph API

I have no problem adding a user to a role using
https://graph.windows.net/{TenantId}/users/{UserId}/appRoleAssignments?api-version=1.5
string data = JsonConvert.SerializeObject(new
{
id = roleId,
principalDisplayName = userEmail,
principalId = userId,
principalType = "User",
resourceId = servicePrincipalId
});
But this is not working for groups by changing:
https://graph.windows.net/{TenantId}/groups/{GroupId}/appRoleAssignments?api-version=1.5
principalDisplayName = GroupDisplayName,
principalId = groupId,
principalType = "Group"
Also tried without the principalDisplayName
I am receiving "Bad Request" and in Fiddler "One or more properties are invalid." with no extra information.
Can you login to azure portal with your tenant credential and check if you can assign AAD group to role? It's most likely related to your permission
Azure Active Directory -> Enterprise applications -> Find your application -> Users and Groups -> Add User

extension attributes for ad user in azure active directory using Microsoft.Graph

Hi I am trying to add extension property to azure ad user using Microsoft.Graph package.
var schema = new SchemaExtension()
{
Id = "Location",
TargetTypes = new List<string> { "User" },
Description = "DescribesLocation",
Properties = new List<ExtensionSchemaProperty>() { new ExtensionSchemaProperty { Name = "LocationCode", Type = "String" } }
};
var result = graphClient.SchemaExtensions.Request().AddAsync(schema).Result;
I have created a daemon application in azure ad registered applications and given below permissions to the application
Directory.Read.All
Directory.ReadWrite.All
User.Invite.All
User.Read
User.Read.All
User.ReadWrite.All
Group.Read.All
Group.ReadWrite.All
I am getting error message as Code: Authorization_RequestDenied
Message: Insufficient privileges to complete the operation. What other permissions are required for this operation and which permissions are not required?
You need the Directory.AccessAsUser.All permission. Here are some test cases that you may find useful.

ASP.Net MVC5: Using identity how to attach role with user after login

We protect action with authorize attribute with specific role name this way
[Authorize(Roles="members, admin")]
suppose users and roles are mapped in db table. so when user login then how could i attach role with logged in user using identity.
here i am posting url and sample which show how people do the same in mvc4 with custom form authentication. just see the code and i hope surely understand what i am trying to do with asp.net mvc 5 using identity.
https://www.codeproject.com/Articles/408306/Understanding-and-Implementing-ASP-NET-Custom-Form
see this above url for custom form authentication with asp.net mvc 4
protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
{
if (FormsAuthentication.CookiesSupported == true)
{
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
try
{
//let us take out the username now
string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
//let us extract the roles from our own custom cookie
string roles = DBHelper.GetUserRoles(username);
//Let us set the Pricipal with our user specific details
e.User = new System.Security.Principal.GenericPrincipal(
new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
}
catch (Exception)
{
//somehting went wrong
}
}
}
}
i am working with asp.net mvc 5 & identity system. please help and guide me. thanks
You have to get logged in user id first
var UserName= await User.Identity.GetUserId()
then you can assign any role to that logged in user like
var _context = new ApplicationDbContext();
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_context));
UserManager.AddToRole("UserName", "UserRole");

aspnetcore.identity - in role, but getting denied access

Core 2.0, using AspnetCore.Identity. I created a few roles, including "Admin".
//initializing custom roles
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
string[] roleNames = { "Admin", "Training", "Operations", "Membership", "Individual" };
IdentityResult roleResult;
foreach (var roleName in roleNames)
{
var roleExist = await RoleManager.RoleExistsAsync(roleName);
// ensure that the role does not exist
if (!roleExist)
{
//create the roles and seed them to the database:
roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
}
}
I checked the SQL tables, and they're all there.:
Then I add myself to the Admin role (not the full method, but the relevant parts):
var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var _eric = await UserManager.FindByEmailAsync("username#gmail.com");
await UserManager.AddToRoleAsync(_eric, "Admin");
I check the tables, and I'm in there (along with another guy I added to a different role):
I then travel over to my method and slap Authorize on it with two of the roles, one of which I'm in (Admin):
[Authorize(Roles ="Training, Admin")]
public ActionResult Index()
{
return View();
}
And then I get access denied. I'm missing something, but can't figure out what step I messed up. User is in there, I'm logged in, the data tables show me as having the role assigned, and the Authorize tag looks good.
Roles are claims and claims are loaded only on sign in. If you modify a claim (such as by adding a role), you must sign the user out and either automatically sign them back in or prompt the user to re-authenticate, to reload the claims.

Azure AD graph API query for non-empty property

How can I query graph.windows.net for accounts in our Azure AD that do have the email property set? I am asking for the query string, or even better a C# statement using ActiveDirectoryClient.
It doesn't seem possible to use $filter=email neq '' or other similar $filter construct to exclude users that don't have the email property set.
You can iterate all the Azure AD users and check if the users have a mail:
ActiveDirectoryClient activeDirectoryClient = AuthenticationHelper.GetActiveDirectoryClientAsApplication();
List<IUser> users = activeDirectoryClient.Users.ExecuteAsync().Result.CurrentPage.ToList();
var mailUsers = new List<IUser>();
foreach (IUser user in users)
{
if(user.Mail != null)
{
mailUsers.Add(user);
}
}
Please check the sample application at
https://github.com/Azure-Samples/active-directory-dotnet-graphapi-console

Resources