I'm having a tough time with the Graph API and specifically the Disconnect-MgGraph command. I'm trying to automate getting User Administrator privileges through a script, but it rarely works as expected. Usually, I need to authenticate with MFA, but most of the time it fails because Disconnect-MgGraph doesn't clear the old MFA token. I end up not being prompted for MFA when I should be, which defeats the purpose. I've tried Disconnect-MgGraph followed by Connect-MgGraph multiple times, but it only works occasionally. I've scoured the internet, but I can't find any clear answers from Microsoft or the community. Is there anyone who knows why this happens or any good workarounds? I've also heard the standard response of using the Azure GUI, but that's not an option for me. I'm looking for a way to automate this process more efficiently due to the nature of my job. Any advice would be greatly appreciated!
4 Answers
You might want to consider setting up an app registration and using a service principal with a client secret or certificate for authentication. Also, are you using Entra as your identity provider and MS Auth for MFA? If you have ADFS, ensure that the MFA settings are correct. Sometimes conditional access policies might not apply as they should. Plus, try clearing the contents in the `.mg` folder in your user directory to wipe the cached tokens.
I typically use the `-UseDeviceAuthentication` option for connect commands. That way, I can handle the authentication in a separate browser session, which has worked well for me.
I've run into the same issues. Disconnect-MgGraph is definitely tricky! One suggestion is to clear the token cache with this command: `Remove-Item "$env:USERPROFILE.mg" -Recurse -Force`. You might find this useful. Check the GitHub page on known issues for more details!
I haven't had this issue before, but have you thought about using "process scope" when connecting? It might help avoid caching issues. Also, I've heard that EasyPIM handles this a bit differently, which could be worth checking out.

Related Questions
XML Signature Verifier
Voltage Divider Calculator
SSL Certificate Decoder
SQL Formatter
Online Font Playground to Test Google or Custom Fonts
File Hash Generator Online – Get Instant MD5 and SHA-256 Hashes