Settings Results in 4 milliseconds

RPlotExporter couldn't find Rscript.exe in your PA ...
Category: Algorithms

Question How do you solve the error in BenchmarkDotNet that says "RPlotExporter ...


Views: 0 Likes: 48
Git Commands that will increase your productivity
Category: Git

Git Commands for Beginners that will Increase ProductivityPresentation</stron ...


Views: 289 Likes: 81
What are the Best Algorithms Google Bard vs ChatGP ...
Category: Technology

There are many different algorithms, each with its own strengths and weaknesses. Some of the mos ...


Views: 0 Likes: 29
recurring neural network in c#
Category: Research

Recurrent Neural Networks (RNNs) are a type of Artificial Neural Network (ANN) that are designed ...


Views: 0 Likes: 28
If posting to a group, requires app being installe ...
Category: Questions

Question Posting to Facebook Graph API shows an error "(#200) If posting to a group, requires ap ...


Views: 0 Likes: 43
Graphs Data Structure
Category: Computer Programming

When building a Social Media Application, it's hard not to think a ...


Views: 0 Likes: 23
What is New in Asp Net 7 and EF Core 7 (Best Featu ...
Category: Research

Asp.Net Core 7Navigation If you want the Entity to be included in a ...


Views: 0 Likes: 19
Onboarding users in ASP.NET Core using Azure AD Temporary Access Pass and Microsoft Graph
Onboarding users in ASP.NET Core using Azure AD Te ...

The article looks at onboarding different Azure AD users with a temporary access pass (TAP) and some type of passwordless authentication. An ASP.NET Core application is used to create the Azure AD member users which can then use a TAP to setup the account. This is a great way to onboard users in your tenant. Code https//github.com/damienbod/AzureAdTapOnboarding The ASP.NET Core application needs to onboard different type of Azure AD users. Some users cannot use a passwordless authentication (yet) and so a password setup is also required for these users. TAP only works with members and we also need to support guest users with some alternative onboarding flow. Different type of user flows are supported or possible AAD member user flow with TAP and FIDO2 authentication AAD member user flow with password using email/password authentication AAD member user flow with password setup and a phone authentication AAD guest user flow with federated login AAD guest user flow with Microsoft account AAD guest user flow with email code FIDO2 should be used for all enterprise employees with an office account in the enterprise. If this is not possible, then at least the IT administrators should be forced to use FIDO2 authentication and the companies should be planning on a strategy on how to move to a phishing resistant authentication. This could be forced with a PIM and a continuous access policy for administration jobs. Using FIDO2, the identities are protected with a phishing resistant authentication. This should be a requirement for any professional solution. Azure AD users with no computer can use an email code or a SMS authentication. This is a low security authentication and applications should not expose sensitive information to these user types. Setup The ASP.NET Core application uses Microsoft.Identity.Web and the Microsoft.Identity.Web.MicrosoftGraphBeta Nuget packages to implement the Azure AD clients. The ASP.NET Core client is a server rendered application and uses an Azure App registration which requires a secret or a certificate to acquire access tokens. The onboarding application uses Microsoft Graph applications permissions to create the users and initialize the temporary access pass (TAP) flow. The following application permissions are used User.EnableDisableAccount.All User.ReadWrite.All UserAuthenticationMethod.ReadWrite.All The permissions are added to a separate Azure App registration and require a secret to use. In a second phase, I will look at implementing the Graph API access using Microsoft Graph delegated permissions. It is also possible to use a service managed identity to acquire a Graph access token with the required permissions. Onboarding members using passwordless When onboarding a new Azure AD user with passwordless and TAP, this needs to be implemented in two steps. Firstly, a new Microsoft Graph user is created with the type member. This takes an unknown length of time to complete on Azure AD. When this is finished, a new TAP authentication method is created. I used the Polly Nuget package to retry this until the TAP request succeeds. Once successful, the temporary access pass is displayed in the UI. If this was a new employee or something like this, you could print this out and let the user complete the process. private async Task CreateMember(UserModel userData) { var createdUser = await _aadGraphSdkManagedIdentityAppClient .CreateGraphMemberUserAsync(userData); if (createdUser!.Id != null) { if (userData.UsePasswordless) { var maxRetryAttempts = 7; var pauseBetweenFailures = TimeSpan.FromSeconds(3); var retryPolicy = Policy .Handle<HttpRequestException>() .WaitAndRetryAsync(maxRetryAttempts, i => pauseBetweenFailures); await retryPolicy.ExecuteAsync(async () => { var tap = await _aadGraphSdkManagedIdentityAppClient .AddTapForUserAsync(createdUser.Id); AccessInfo = new CreatedAccessModel { Email = createdUser.Email, TemporaryAccessPass = tap!.TemporaryAccessPass }; }); } else { AccessInfo = new CreatedAccessModel { Email = createdUser.Email, Password = createdUser.Password }; } } } The CreateGraphMemberUserAsync method creates a new Microsoft Graph user. To use a temporary access pass, a member user must be used. Guest users cannot be onboarded like this. Even though we do not use a password in this process, the Microsoft Graph user validation forces us to create one. We just create a random password and will not return this, This password will not be updated. public async Task<CreatedUserModel> CreateGraphMemberUserAsync (UserModel userModel) { if (!userModel.Email.ToLower().EndsWith(_aadIssuerDomain.ToLower())) { throw new ArgumentException("A guest user must be invited!"); } var graphServiceClient = _graphService .GetGraphClientWithManagedIdentityOrDevClient(); var password = GetRandomString(); var user = new User { DisplayName = userModel.UserName, Surname = userModel.LastName, GivenName = userModel.FirstName, OtherMails = new List<string> { userModel.Email }, UserType = "member", AccountEnabled = true, UserPrincipalName = userModel.Email, MailNickname = userModel.UserName, PasswordProfile = new PasswordProfile { Password = password, // We use TAP if a paswordless onboarding is used ForceChangePasswordNextSignIn = !userModel.UsePasswordless }, PasswordPolicies = "DisablePasswordExpiration" }; var createdUser = await graphServiceClient.Users .Request() .AddAsync(user); return new CreatedUserModel { Email = createdUser.UserPrincipalName, Id = createdUser.Id, Password = password }; } The TemporaryAccessPassAuthenticationMethod object is created using Microsoft Graph. We create a use once TAP. The access code is returned and displayed in the UI. public async Task<TemporaryAccessPassAuthenticationMethod?> AddTapForUserAsync(string userId) { var graphServiceClient = _graphService .GetGraphClientWithManagedIdentityOrDevClient(); var tempAccessPassAuthMethod = new TemporaryAccessPassAuthenticationMethod { //StartDateTime = DateTimeOffset.Now, LifetimeInMinutes = 60, IsUsableOnce = true, }; var result = await graphServiceClient.Users[userId] .Authentication .TemporaryAccessPassMethods .Request() .AddAsync(tempAccessPassAuthMethod); return result; } The https//aka.ms/mysecurityinfo link can be used to complete the flow. The new user can click this link and enter the email and the access code. Now that the user is authenticated, he or she can add a passwordless authentication method. I use an external FIDO2 key. Once setup, the user can register and authenticate. You should use at least two security keys. This is an awesome way of onboarding users which allows users to authenticate in a phishing resistant way without requiring or using a password. FIDO2 is the recommended and best way of authenticating users and with the rollout of passkeys, this will become more user friendly as well. Onboarding members using password Due to the fact that some companies still use legacy authentication or we would like to support users with no computer, we also need to onboard users with passwords. When using passwords, the user needs to update the password on first use. The user should add an MFA, if not forced by the tenant. Some employees might not have a computer and would like user a phone to authenticate. An SMS code would be a good way of achieving this. This is of course not very secure, so you should expect these accounts to get lost or breached and so sensitive data should be avoided for applications used by these accounts. The device code flow could be used together on a shared PC with the user mobile phone. Starting an authentication flow from a QR Code is unsecure as this is not safe against phishing but as SMS is used for these type of users, it’s already not very secure. Again sensitive data must be avoided for applications accepting these low security accounts. It’s all about balance, maybe someday soon, all users will have FIDO2 security keys or passkeys to use and we can avoid these sort of solutions. Onboarding guest users (invitations) Guest users cannot be onboarded by creating a Microsoft Graph user. You need to send an invitation to the guest user for your tenant. Microsoft Graph provides an API for this. There a different type of guest users, depending on the account type and the authentication method type. The invitation returns an invite redeem URL which can be used to setup the account. This URL is mailed to the email used in the invite and does not need to be displayed in the UI. private async Task InviteGuest(UserModel userData) { var invitedGuestUser = await _aadGraphSdkManagedIdentityAppClient .InviteGuestUser(userData, _inviteUrl); if (invitedGuestUser!.Id != null) { AccessInfo = new CreatedAccessModel { Email = invitedGuestUser.InvitedUserEmailAddress, InviteRedeemUrl = invitedGuestUser.InviteRedeemUrl }; } } The InviteGuestUser method is used to create the invite object and this is sent as a HTTP post request to the Microsoft Graph API. public async Task<Invitation?> InviteGuestUser (UserModel userModel, string redirectUrl) { if (userModel.Email.ToLower().EndsWith(_aadIssuerDomain.ToLower())) { throw new ArgumentException("user must be from a different domain!"); } var graphServiceClient = _graphService .GetGraphClientWithManagedIdentityOrDevClient(); var invitation = new Invitation { InvitedUserEmailAddress = userModel.Email, SendInvitationMessage = true, InvitedUserDisplayName = $"{userModel.FirstName} {userModel.LastName}", InviteRedirectUrl = redirectUrl, InvitedUserType = "guest" }; var invite = await graphServiceClient.Invitations .Request() .AddAsync(invitation); return invite; } Notes Onboarding users with Microsoft Graph can be complicated because you need to know which parameters and how the users need to be created. Azure AD members can be created using the Microsoft Graph user APIs, guest users are created using the Microsoft Graph invitation APIs. Onboarding users with TAP and FIDO2 is a great way of doing implementing this workflow. As of today, this is still part of the beta release. Links https//entra.microsoft.com/ https//learn.microsoft.com/en-us/azure/active-directory/authentication/howto-authentication-temporary-access-pass https//learn.microsoft.com/en-us/graph/api/authentication-post-temporaryaccesspassmethods?view=graph-rest-1.0&tabs=csharp https//learn.microsoft.com/en-us/graph/authenticationmethods-get-started https//learn.microsoft.com/en-us/azure/active-directory/authentication/howto-authentication-passwordless-security-key-on-premises Create Azure B2C users with Microsoft Graph and ASP.NET Core Onboarding new users in an ASP.NET Core application using Azure B2C Disable Azure AD user account using Microsoft Graph and an application client Invite external users to Azure AD using Microsoft Graph and ASP.NET Core https//learn.microsoft.com/en-us/azure/active-directory/external-identities/external-identities-overview https//learn.microsoft.com/en-us/azure/active-directory/external-identities/b2b-quickstart-add-guest-users-portal


Video: Show a user’s emails in an ASP.NET Core app using Microsoft Graph
Video Show a user’s emails in an ASP.NET Core app ...

I’ve been working a lot with .NET Core and Microsoft Graph lately and decided to put together a short video based on a Microsoft Learn module covering how the technologies can be used together. If you haven’t used Microsoft Graph before, it provides a secure, unified API to access organizational data and intelligence (data stored in Microsoft 365 for example). So why would you ever want to access a signed in user’s emails and include them in your custom app? The simple answer is, “Bring organizational data where your users need it everyday!”. Instead of users switching from your app to find a relevant email, calendar event, Microsoft Teams chat (and more) by jumping between various productivity apps, you can pull that type of data directly into your custom app. This allows users to work more efficiently and make more informed decisions all while minimizing context shifts. In this video I’ll introduce you to The role of security in making Microsoft Graph calls.Microsoft Identity and Microsoft Graph Middleware configuration.The role of permissions/scopes and access tokens.The Microsoft Graph .NET Core SDK and how it can be used.How to create reusable classes that handle making Microsoft Graph calls.Dependency injection and how it can be used to access a GraphServiceClient object.How to retrieve a batch of email messages using the UserMessagesCollectionRequest class. Show a user’s emails in an ASP.NET Core app using Microsoft Graph


Reset user account passwords using Microsoft Graph and application permissions in ASP.NET Core
Reset user account passwords using Microsoft Graph ...

This article shows how to reset a password for tenant members using a Microsoft Graph application client in ASP.NET Core. An Azure App registration is used to define the application permission for the Microsoft Graph client and the User Administrator role is assigned to the Azure Enterprise application created from the Azure App registration. Code https//github.com/damienbod/azuerad-reset Create an Azure App registration with the Graph permission An Azure App registration was created which requires a secret or a certificate. The Azure App registration has the application User.ReadWrite.All permission and is used to assign the Azure role. This client is only for application clients and not delegated clients. Assign the User Administrator role to the App Registration The User Administrator role is assigned to the Azure App registration (Azure Enterprise application pro tenant). You can do this by using the User Administrator Assignments and and new one can be added. Choose the Azure App registration corresponding Enterprise application and assign the role to be always active. Create the Microsoft Graph application client In the ASP.NET Core application, a new Graph application can be created using the Microsoft Graph SDK and Azure Identity. The GetChainedTokenCredentials is used to authenticate using a managed identity for the production deployment or a user secret in development. You could also use a certificate. This is the managed identity from the Azure App service where the application is deployed in production. using Azure.Identity; using Microsoft.Graph; namespace SelfServiceAzureAdPasswordReset; public class GraphApplicationClientService { private readonly IConfiguration _configuration; private readonly IHostEnvironment _environment; private GraphServiceClient? _graphServiceClient; public GraphApplicationClientService(IConfiguration configuration, IHostEnvironment environment) { _configuration = configuration; _environment = environment; } /// <summary> /// gets a singleton instance of the GraphServiceClient /// </summary> public GraphServiceClient GetGraphClientWithManagedIdentityOrDevClient() { if (_graphServiceClient != null) return _graphServiceClient; string[] scopes = new[] { "https//graph.microsoft.com/.default" }; var chainedTokenCredential = GetChainedTokenCredentials(); _graphServiceClient = new GraphServiceClient(chainedTokenCredential, scopes); return _graphServiceClient; } private ChainedTokenCredential GetChainedTokenCredentials() { if (!_environment.IsDevelopment()) { // You could also use a certificate here return new ChainedTokenCredential(new ManagedIdentityCredential()); } else // dev env { var tenantId = _configuration["AzureAdGraphTenantId"]; var clientId = _configuration.GetValue<string>("AzureAdGraphClientId"); var clientSecret = _configuration.GetValue<string>("AzureAdGraphClientSecret"); var options = new TokenCredentialOptions { AuthorityHost = AzureAuthorityHosts.AzurePublicCloud }; // https//docs.microsoft.com/dotnet/api/azure.identity.clientsecretcredential var devClientSecretCredential = new ClientSecretCredential( tenantId, clientId, clientSecret, options); var chainedTokenCredential = new ChainedTokenCredential(devClientSecretCredential); return chainedTokenCredential; } } } Reset the password Microsoft Graph SDK 4 Once the client is authenticated, Microsoft Graph SDK can be used to implement the logic. You need to decide if SDK 4 or SDK 5 is used to implement the Graph client. Most applications must still use Graph SDK 4 but no docs exist for this anymore. Refer to Stackoverflow or try and error. The application has one method to get the user and a second one to reset the password and force a change on the next authentication. This is ok for low level security, but TAP with a strong authentication should always be used if possible. using Microsoft.Graph; using System.Security.Cryptography; namespace SelfServiceAzureAdPasswordReset; public class UserResetPasswordApplicationGraphSDK4 { private readonly GraphApplicationClientService _graphApplicationClientService; public UserResetPasswordApplicationGraphSDK4(GraphApplicationClientService graphApplicationClientService) { _graphApplicationClientService = graphApplicationClientService; } private async Task<string> GetUserIdAsync(string email) { var filter = $"startswith(userPrincipalName,'{email}')"; var graphServiceClient = _graphApplicationClientService .GetGraphClientWithManagedIdentityOrDevClient(); var users = await graphServiceClient.Users .Request() .Filter(filter) .GetAsync(); return users.CurrentPage[0].Id; } public async Task<string?> ResetPassword(string email) { var graphServiceClient = _graphApplicationClientService .GetGraphClientWithManagedIdentityOrDevClient(); var userId = await GetUserIdAsync(email); if (userId == null) { throw new ArgumentNullException(nameof(email)); } var password = GetRandomString(); await graphServiceClient.Users[userId].Request() .UpdateAsync(new User { PasswordProfile = new PasswordProfile { Password = password, ForceChangePasswordNextSignIn = true } }); return password; } private static string GetRandomString() { var random = $"{GenerateRandom()}{GenerateRandom()}{GenerateRandom()}{GenerateRandom()}-AC"; return random; } private static int GenerateRandom() { return RandomNumberGenerator.GetInt32(100000000, int.MaxValue); } } Reset the password Microsoft Graph SDK 5 Microsoft Graph SDK 5 can also be used to implement the logic to reset the password and force a change on the next signin. using Microsoft.Graph; using Microsoft.Graph.Models; using System.Security.Cryptography; namespace SelfServiceAzureAdPasswordReset; public class UserResetPasswordApplicationGraphSDK5 { private readonly GraphApplicationClientService _graphApplicationClientService; public UserResetPasswordApplicationGraphSDK5(GraphApplicationClientService graphApplicationClientService) { _graphApplicationClientService = graphApplicationClientService; } private async Task<string?> GetUserIdAsync(string email) { var filter = $"startswith(userPrincipalName,'{email}')"; var graphServiceClient = _graphApplicationClientService .GetGraphClientWithManagedIdentityOrDevClient(); var result = await graphServiceClient.Users.GetAsync((requestConfiguration) => { requestConfiguration.QueryParameters.Top = 10; if (!string.IsNullOrEmpty(email)) { requestConfiguration.QueryParameters.Search = $"\"userPrincipalName{email}\""; } requestConfiguration.QueryParameters.Orderby = new string[] { "displayName" }; requestConfiguration.QueryParameters.Count = true; requestConfiguration.QueryParameters.Select = new string[] { "id", "displayName", "userPrincipalName", "userType" }; requestConfiguration.QueryParameters.Filter = "userType eq 'Member'"; // onPremisesSyncEnabled eq false requestConfiguration.Headers.Add("ConsistencyLevel", "eventual"); }); return result!.Value!.FirstOrDefault()!.Id; } public async Task<string?> ResetPassword(string email) { var graphServiceClient = _graphApplicationClientService .GetGraphClientWithManagedIdentityOrDevClient(); var userId = await GetUserIdAsync(email); if (userId == null) { throw new ArgumentNullException(nameof(email)); } var password = GetRandomString(); await graphServiceClient.Users[userId].PatchAsync( new User { PasswordProfile = new PasswordProfile { Password = password, ForceChangePasswordNextSignIn = true } }); return password; } private static string GetRandomString() { var random = $"{GenerateRandom()}{GenerateRandom()}{GenerateRandom()}{GenerateRandom()}-AC"; return random; } private static int GenerateRandom() { return RandomNumberGenerator.GetInt32(100000000, int.MaxValue); } } Any Razor page can use the service and update the password. The Razor Page requires protection to prevent any user or bot updating any other user account. Some type of secret is required to use the service or an extra id which can be created from an internal IT admin. DDOS protection and BOT protection is also required if the Razor page is deployed to a public endpoint and a delay after each request must also be implemented. Extreme caution needs to be taken when exposing this business functionality. private readonly UserResetPasswordApplicationGraphSDK5 _userResetPasswordApp; [BindProperty] public string Upn { get; set; } = string.Empty; [BindProperty] public string? Password { get; set; } = string.Empty; public IndexModel(UserResetPasswordApplicationGraphSDK5 userResetPasswordApplicationGraphSDK4) { _userResetPasswordApp = userResetPasswordApplicationGraphSDK4; } public void OnGet(){} public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return Page(); } Password = await _userResetPasswordApp .ResetPassword(Upn); return Page(); } The demo application can be started and a password from a local member can be reset. The https//mysignins.microsoft.com/security-info url can be used to test the new password and add MFA or whatever. Notes You can use this solution for applications with no user. If using an administrator or a user to reset the passwords, then a delegated permission should be used with different Graph SDK methods and different Graph permissions. Links https//aka.ms/mysecurityinfo https//learn.microsoft.com/en-us/graph/api/overview?view=graph-rest-1.0 https//learn.microsoft.com/en-us/graph/sdks/paging?tabs=csharp https//learn.microsoft.com/en-us/graph/api/authenticationmethod-resetpassword?view=graph-rest-1.0&tabs=csharp


Reset passwords in ASP.NET Core using delegated permissions and Microsoft Graph
Reset passwords in ASP.NET Core using delegated pe ...

This article shows how an administrator can reset passwords for local members of an Azure AD tenant using Microsoft Graph and delegated permissions. An ASP.NET Core application is used to implement the Azure AD client and the Graph client services. Code https//github.com/damienbod/azuerad-reset Setup Azure App registration The Azure App registration is setup to authenticate with a user and an application (delegated flow). An App registration “Web” setup is used. Only delegated permissions are used in this setup. This implements an OpenID Connect code flow with PKCE and a confidential client. A secret or a certificate is required for this flow. The following delegated Graph permissions are used Directory.AccessAsUser.All User.ReadWrite.All UserAuthenticationMethod.ReadWrite.All ASP.NET Core setup The ASP.NET Core application implements the Azure AD client using the Microsoft.Identity.Web Nuget package and libraries. The following packages are used Microsoft.Identity.Web Microsoft.Identity.Web.UI Microsoft.Identity.Web.GraphServiceClient (SDK5) or Microsoft.Identity.Web.MicrosoftGraph (SDK4) Microsoft Graph is not added directly because the Microsoft.Identity.Web.MicrosoftGraph or Microsoft.Identity.Web.GraphServiceClient adds this with a tested and working version. Microsoft.Identity.Web uses the Microsoft.Identity.Web.GraphServiceClient package for Graph SDK 5. Microsoft.Identity.Web.MicrosoftGraph uses Microsoft.Graph 4.x versions. The official Microsoft Graph documentation is already updated to SDK 5. For application permissions, Microsoft Graph SDK 5 can be used with Azure.Identity. Search for users with Graph SDK 5 and resetting the password The Graph SDK 5 can be used to search for users and reset the user using a delegated scope and then to reset the password using the Patch HTTP request. The Graph QueryParameters are used to find the user and the HTTP Patch is used to update the password using the PasswordProfile. using System.Security.Cryptography; using Microsoft.Graph; using Microsoft.Graph.Models; namespace AzureAdPasswordReset; public class UserResetPasswordDelegatedGraphSDK5 { private readonly GraphServiceClient _graphServiceClient; public UserResetPasswordDelegatedGraphSDK5(GraphServiceClient graphServiceClient) { _graphServiceClient = graphServiceClient; } /// <summary> /// Directory.AccessAsUser.All User.ReadWrite.All UserAuthenticationMethod.ReadWrite.All /// </summary> public async Task<(string? Upn, string? Password)> ResetPassword(string oid) { var password = GetRandomString(); var user = await _graphServiceClient .Users[oid] .GetAsync(); if (user == null) { throw new ArgumentNullException(nameof(oid)); } await _graphServiceClient.Users[oid].PatchAsync( new User { PasswordProfile = new PasswordProfile { Password = password, ForceChangePasswordNextSignIn = true } }); return (user.UserPrincipalName, password); } public async Task<UserCollectionResponse?> FindUsers(string search) { var result = await _graphServiceClient.Users.GetAsync((requestConfiguration) => { requestConfiguration.QueryParameters.Top = 10; if (!string.IsNullOrEmpty(search)) { requestConfiguration.QueryParameters.Search = $"\"displayName{search}\""; } requestConfiguration.QueryParameters.Orderby = new string[] { "displayName" }; requestConfiguration.QueryParameters.Count = true; requestConfiguration.QueryParameters.Select = new string[] { "id", "displayName", "userPrincipalName", "userType" }; requestConfiguration.QueryParameters.Filter = "userType eq 'Member'"; // onPremisesSyncEnabled eq false requestConfiguration.Headers.Add("ConsistencyLevel", "eventual"); }); return result; } private static string GetRandomString() { var random = $"{GenerateRandom()}{GenerateRandom()}{GenerateRandom()}{GenerateRandom()}-AC"; return random; } private static int GenerateRandom() { return RandomNumberGenerator.GetInt32(100000000, int.MaxValue); } } Search for users SDK 4 The application allows the user administration to search for members of the Azure AD tenant and finds users using a select and a filter definition. The search query parameter would probably return a better user experience. public async Task<IGraphServiceUsersCollectionPage?> FindUsers(string search) { var users = await _graphServiceClient.Users.Request() .Filter($"startswith(displayName,'{search}') AND userType eq 'Member'") .Select(u => new { u.Id, u.GivenName, u.Surname, u.DisplayName, u.Mail, u.EmployeeId, u.EmployeeType, u.BusinessPhones, u.MobilePhone, u.AccountEnabled, u.UserPrincipalName }) .GetAsync(); return users; } The ASP.NET Core Razor page supports an auto complete using the OnGetAutoCompleteSuggest method. This returns the found results using the Graph request. private readonly UserResetPasswordDelegatedGraphSDK4 _graphUsers; public string? SearchText { get; set; } public IndexModel(UserResetPasswordDelegatedGraphSDK4 graphUsers) { _graphUsers = graphUsers; } public async Task<ActionResult> OnGetAutoCompleteSuggest(string term) { if (term == "*") term = string.Empty; var usersCollectionResponse = await _graphUsers.FindUsers(term); var users = usersCollectionResponse!.ToList(); var usersDisplay = users.Select(user => new { user.Id, user.UserPrincipalName, user.DisplayName }); SearchText = term; return new JsonResult(usersDisplay); } The Razor Page can be implemented using Bootstrap or whatever CSS framework you prefer. Reset the password for user X using Graph SDK 4 The Graph service supports reset a password using a delegated permission. The user is requested using the OID and a new PasswordProfile is created updating the password and forcing a one time usage. /// <summary> /// Directory.AccessAsUser.All /// User.ReadWrite.All /// UserAuthenticationMethod.ReadWrite.All /// </summary> public async Task<(string? Upn, string? Password)> ResetPassword(string oid) { var password = GetRandomString(); var user = await _graphServiceClient.Users[oid] .Request().GetAsync(); if (user == null) { throw new ArgumentNullException(nameof(oid)); } await _graphServiceClient.Users[oid].Request() .UpdateAsync(new User { PasswordProfile = new PasswordProfile { Password = password, ForceChangePasswordNextSignIn = true } }); return (user.UserPrincipalName, password); } The Razor Page sends a post request and resets the password using the user principal name. public async Task<IActionResult> OnPostAsync() { var id = Request.Form .FirstOrDefault(u => u.Key == "userId") .Value.FirstOrDefault(); var upn = Request.Form .FirstOrDefault(u => u.Key == "userPrincipalName") .Value.FirstOrDefault(); if(!string.IsNullOrEmpty(id)) { var result = await _graphUsers.ResetPassword(id); Upn = result.Upn; Password = result.Password; return Page(); } return Page(); } Running the application When the application is started, a user password can be reset and updated. It is important to block this function for non-authorized users as it is possible to reset any account without further protection. You could PIM this application using an azure AD security group or something like this. Notes Using Graph SDK 4 is hard as almost no docs now exist, Graph has moved to version 5. Microsoft Graph SDK 5 has many breaking changes and is supported by Microsoft.Identity.Web using the Microsoft.Identity.Web.GraphServiceClient package. High user permissions are used in this and it is important to protection this API or the users that can use the application. Links https//aka.ms/mysecurityinfo https//learn.microsoft.com/en-us/graph/api/overview?view=graph-rest-1.0 https//learn.microsoft.com/en-us/graph/sdks/paging?tabs=csharp https//github.com/AzureAD/microsoft-identity-web/blob/jmprieur/Graph5/src/Microsoft.Identity.Web.GraphServiceClient/Readme.md https//learn.microsoft.com/en-us/graph/api/authenticationmethod-resetpassword?view=graph-rest-1.0&tabs=csharp


Neural Networks in C#
Category: Other

Neural network in C# using TensorFlow library. using Syst ...


Views: 0 Likes: 8

Login to Continue, We will bring you back to this content 0



For peering opportunity Autonomouse System Number: AS401345 Custom Software Development at ErnesTech Email Address[email protected]