Search code examples
c#azurepowershellauthenticationmulti-factor-authentication

How to connect to Azure Active Directory from asp.net web forms application by providing credentials interactively?


I want to provide any user the ability to connect to the powershell Azure Active Directory module through my website and perform some administrative actions in their Microsoft tenant. The code I am using is:

InitialSessionState iss = InitialSessionState.CreateDefault2();

iss.ImportPSModule(new[] { "MSOnline" });

var shell = PowerShell.Create(iss);

var connectCmd = new Command("Connect-MsolService");

shell.Commands.AddCommand(connectCmd);

var results = shell.Invoke();

but I'm getting the following error after Invoke:

Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly style to display a notification from a service application

This is not the case when I run PowerShell code in PowerShell ISE as:

Import-Module MSOnline

Connect-MsolService

Instead, I get a sign in dialogue where I can provide credentials to sign in.

I want the same experience for the website user where they get the sign in dialog.

In C# code, I don't want to pass the credentials as parameter to the Connect-MsolService cmdlet but collect it interactively from the user so that it works with MFA enabled accounts too.

Note: The user will be interacting with the website deployed on a web server and never logs into the server directly. Powershell code embedded in C# will also run on the web server.

My internet search has yielded nothing that I can use so far. Is there a way to get this working? Please share any tips, ideas, solutions.


Solution

  • Your code is running on the web server (Being a web application) & not on the client consuming it - the pop up will be tried to open on the server - Hence the error !

    Since you mentioned that you will not be able pass the credentials.

    The other option that you could use to authenticate using the access token.

     Connect-Msolservice -MsGraphAcessToken <Token>
    

    You are using C# and so you can make use of the MSAL (Microsoft Authentication library) to perform the interactive login and acquire the token. You could refer to this article for more information.

    The acquired token can be subsequently passed to the powershell commandlet to perform the necessary actions.