Can't Access SharePoint Online Programmatically Anymore - sharepoint

A week ago I was able to access SharePoint Online programmatically through a c# application. Now I am getting the following error:
The remote server returned an error: (503) Server Unavailable.
I can access the SharePoint site in my browser completely fine.
I tried accessing it through SharePoint Online Management Shell but I get the same error when doing the following:
$adminUPN="name#business.com"
$userCredential = Get-Credential -UserName $adminUPN -Message "Type the password."
Connect-SPOService -Url https://business.sharepoint.com/sites/bd/resume/ -Credential $userCredential
When I try and connect without the credentials using:
Connect-SPOService -Url https://business.sharepoint.com/sites/bd/resume/
It firstly pops up a Microsoft Sign in window to enter just my username/email, which looks normal. But when I enter my email, click next it takes me to different sign in page which looks off (See screenshot below, I removed company information with black scribble).
After I enter my password and hit enter I get a different error:
Connect-SPOService : Could not authenticate to SharePoint Online https://business.sharepoint.com/sites/bd/resume/ using OAuth 2.0
Firstly, I want to confirm if this is a problem on my end or if this a problem with permission, etc on the admin end.

The cause for your issue could be the fact that the LegacyAuthProtocolsEnabled property, at tenant level, is set to False. Setting the value of this property to True can solve the issue.
To get the current value run the following command in PowerShell:
Connect-SPOService
Get-SPOTenant
To set the value to True for LegacyAuthProtocolsEnabled run the following commands in PowerShell:
Connect-SPOService
Set-SPOTenant -LegacyAuthProtocolsEnabled $True
After you run the commands it's necessary to wait some time until will work.
According to documentation, a value of False prevents Office clients using non-modern authentication protocols from accessing SharePoint Online resources.
A value of True- Enables Office clients using non-modern authentication protocols (such as, Forms-Based Authentication (FBA) or Identity Client Runtime Library (IDCRL)) to access SharePoint resources.

Related

Powershell - Connecting to SQL Server using Connect-AzAccount (With MFA)

We have a SQL Server set up (created by me, with my account as the admin account), and using Management Studio, I can access the database just fine. I'm now trying to achieve the same thing through Powershell.I have created my own user using:
CREATE USER [<my ccount>] FROM EXTERNAL PROVIDER
I start by connecting using MFA (and signing in using the pop-up window/MFA):
Connect-AzAccount -SubscriptionId $subscriptionID
This works fine, and returns the expected values of the subscription specified, and my Azure AD Login as account. I can access my KeyVault and pull secrets from there.
I now would like to connect to my SQL Server using the credentials I'm already signed in with within the PowerShell session, and that's where I get stuck.
I tried a ConnectionString including Authentication=Active Directory Integrated, but that throws an error Exception calling "Open" with "0" argument(s): "One or more errors occurred.".
I then tried using a connection string like this: Server=tcp:<server>.database.windows.net,1433;Initial Catalog=<database>;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30, and adding an AccessToken using SqlConn.AccessToken = $(Get-AzAccessToken -ResourceUrl "Https://database.windows.net/").
However, when I then try to Open the connection, I get the error: "Login failed for user '<token-identified principal>'."
Googling led to several SO articles, but none of those use Connect-AzAccount, but the (what I believe to be outdated) Az Account (I.e. Connecting to SQL Server using Powershell with Azure AD MFA).
Other examples I found all add UID and Password, which should not be needed considering I authenticated already.
Is there a way to use the existing Connect-AzAccount session to authenticate against my Azure SQL Server, and if so, what format should the ConnectionString have? I have a feeling I'm very close to a solution, but just cannot seem to actually achieve the opening of the connection.
Thanks in advance.
After reading more and more, I finally stumbled across this thread. #golfalot's answer was exactly what I needed.
So the proper code to initialize the connection is:
# Sign in to Azure
Connect-AzAccount -SubscriptionID $subscriptionID
$connectionString = "Server=<server>.database.windows.net;Initial Catalog=<database>;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30"
$accessToken = (Get-AzAccessToken -ResourceUrl https://database.windows.net).Token
$sqlConn = New-Object System.Data.SqlClient.SqlConnection
$sqlConn.ConnectionString = $connectionString
$sqlConn.AccessToken = $accessToken
$sqlConn.Open()

How to create AzureProfile.json file using AzModule command in PowerShell?

I want to create the AzureProfile.json file using the Az Module command in PowerShell, so that I can import the json file anytime I want to login to Azure to start\stop my VM's.
Below is the command\script I am using to create it but it is giving me error as shown in the screenshot.
I tried using the below code as well but it gives same error.
Connect-AzAccount -UseDeviceAuthentication
Save-AzProfile -path "$PSScriptRoot\AzureProfile.json"
WARNING: Unable to acquire token for tenant 'organizations'
Connect-AzAccount : DeviceCodeCredential authentication failed: Retry
failed after 4 tries.
From the error message, it looks like the authentication of your account is failing in the Browser pop-up that comes after Login-AzAccount.
I ran the first set of commands and it ran successfully.
Powershell:
Created File:
Note that my PowerShell version is 5.7.0.18831.
You have tried both :
Connect-AzAccount -UseDeviceAuthentication
Login-AzAccount
Both Interactive and non-interactive mode of login.
The error is occurring while trying you communicate to azure. I am suspecting it could be an issue at a machine level or network level (proxy/firewall)
The above issue usually occurs (reproducible at my end) when there are connection issues with the Microsoft Services - blocked by proxy /firewall/GPO etc...
For a quick test you could run the below PowerShell command :
Invoke-WebRequest -Uri "https://login.microsoftonline.com/organizations/oauth2/v2.0/devicecode" -Body "client_id=1950a258-227b-4e31-a9cf-717495945fc2&scope=https%3A%2F%2Fmanagement.core.windows.net%2F%2F.default+offline_access+profile+openid" -Method Post
Sample Success Response :
Why the above command ?
The above end point https://login.microsoftonline.com/organizations/oauth2/v2.0/devicecode is hit when you use Connect-AzAccount -UseDeviceAuthentication by powershell.
If you encounter a timeout/Name unresolvable issue - the issue is with the network/machine config.

How to Connect-AzAccount in Powershell Core (without prompt)?

I did see this q/a: Connect-AzAccount without prompt
But when I tried the accepted answer, I get the following error:
[6/12/2020 12:36:20 AM] ERROR: Connect-AzAccount : Username + Password authentication is not supported in PowerShell Core. Please use device code authentication for interactive log in, or Service Principal authentication for script log in.
So I went to example 3 of the Connect-AzAccount documentation which specifies the "Service Principal" authentication method, so I mix the two because the suggested vanilla Get-Credential triggers another interactive session. So here's the script now:
$User = "myemail#gmail.com"
$PWord = ConvertTo-SecureString -String "**********" -AsPlainText -Force
$tenant = "f*********************************"
$Credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $User,$PWord
# $Credential = Get-Credential
Connect-AzAccount -Credential $Credential -Tenant $tenant -ServicePrincipal
which brings my next error: [6/12/2020 12:45:45 AM] ERROR: Connect-AzAccount : AADSTS700016: Application with identifier 'myemail' was not found in the directory 'f*********************************'. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant.
I'm really confused at this point because all I have done at this point in Azure is:
Create a new Azure account
Provision an Azure API Management instance through the UI (which btw, takes like 20 minutes)
Try the above code to connect to Azure inside of a Powershell Azure Function locally.
I think something is wrong with the information I've provided or how I've configured something.
$User is the email I signed up to Azure with.
$PWord is my Azure password
$tenant is the first thing I saw when I opened Azure AD:
What's wrong with how I'm trying to connect to Azure through Powershell Core?
Based on Example 3, it asks for entering your application ID for the username and service principal secret as the password.
So you need to create a service principal at first. And then use its application ID and client secret as the credential.
$User = "{application id}"
$PWord = ConvertTo-SecureString -String "{client secret}" -AsPlainText -Force
I don't like Azure documentation. It gives off a very different vibe from GCP and feels much less beginner friendly.
With that said, they did have some kind of write-up that addresses my issue of creating a service principal and using it to authenticate.
I actually ended up just finding a video (and I never do this) because I wanted to skip past all the technical jargon and just create the darn service principal.
It's not even intuitive - it's like Microsoft could have added a button in AZ AD or IAM that said "Create Service Principal" but no, you have to go to a bunch of other pages that say nothing about service principals. You'll see:
In Azure Portal, navigate to the App Registrations page in Azure Active Directory. What an "app registration" has to do with a service principal, I couldn't tell you. I also couldn't tell you what a service principal is, but I'd imagine it has something to do with service accounts.
Make a New Registration and give it some sort of name to describe what the scope of this service principal will entail. Like normal service account naming conventions. I don't think the account type matters but I chose Multitenant. Redirect URL has nothing to do with service principals, and honestly makes it all the more confusing. I would never associate service accounts with any kind of redirect url, but here we are.
You're going to arrive at a page with Display Name (the name of the service principal you gave it in step 2), Application (client) ID (this is actually your service account username, which is imo non-intuitive), and Object ID (I have no idea what this is but I never needed to use it.
Guess what, you have only created 1/3 of your service account. It doesn't even have a password yet. Within your created app registration, there's a Certificates & Secrets page. On that page, you want to add a new client secret. For my description I just put my service principal "display name". I don't think that was necessary because this client secret is within the scope of the app registration, so even if I named it "poop" I could reasonably assume what it was for. Azure will generate a nuanced client secret and display it, but not warn you that this is the only time you will be able to see the key. Copy it. This is, in normal people talk, your service principal password.
For the last step, you need to get out of dodge, I mean Azure AD. Navigate to your Subscriptions page and click on your active subcription. For some reason IAM is here, so click on that. At this point, your service principal has a username and password, but no actual permissions - you have to configure that manually too. Click Add -> Add Role Assignment. For role, you should do your research but if it's not serious Contributor is probably a safe bet. It has read/write but it doesn't supersede Owner. Make sure you're assigning access to a service principal, and search for its display name. Save.
With all of that done, Connect-AzAccount finally worked.

Trying to connect via PowerShell to Azure with new AZ Module

I'm desperate here with Powershell and Azure.
I use PowerShell 7.0.1 and AZ 4.1.0.
When I try to connect (by the way, as global admin via 'Connect-AzAccount'), I get this prompt every time: "WARNING: To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code xxxxxxxxx to authenticate."
Of course I do that and then I get this error message every time:
Connect-AzAccount: xxxxxxxxxxxxx: Device authentication is required.
Trace ID: xxxxxxxxxxxxxxxxxxxxxxxxx
Correlation ID: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Timestamp: 2020-05-20 09:12:18Z: Response status code does not indicate success: 401 (Unauthorized).
Does anyone have an idea why this does not work? I have also tried it temporarily without MFA, with the same result.
As Allen pointed, the right thing to do in this case is to engage the ActiveDirectory authentication team.
Meanwhile, can you try the preview of the new authentication experience here.
This uses a vastly updated authentication experience, and may unblock you while we work out the underlying issue.
Use the below script to install Az.Accounts 2.0.1-preview module.
Install-Module -Name Az.Accounts -AllowPrerelease
For more details, you could refer to this issue.
I have installed Az.Accounts 2.0.1-preview, but now a different error message appears. After connecting all seams working fine, but after calling a function it comes to an error again:
PS> Connect-AzAccount -Subscription 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
WARNING: Attempting to launch a browser for authorization code login.
WARNING: We have launched a browser for you to login. For the old experience with device code flow, please run 'Connect-AzAccount -UseDeviceAuthentication'.
WARNING: Unable to acquire token for tenant 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy'
Account SubscriptionName TenantId Environment
------- ---------------- -------- -----------
michael.kristen#inhouse.wko.at INH-Subscription xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx AzureCloud
PS> Get-AzDefault
Get-AzDefault: Your Azure credentials have not been set up or have expired, please run Connect-AzAccount to set up your Azure credentials.

Azure AD B2C Insufficient privileges to complete the operation while using Graph API

I have started with https://github.com/AzureADQuickStarts/B2C-WebApp-OpenIdConnect-DotNet as the base
Created sign in profile in Azure B2C preview.
Sign in flows works wonderfully with MFA, used custom pages with the help of https://github.com/azureadquickstarts/b2c-azureblobstorage-client/.
CSS and styling works . However I realized that sign up form will be less onerous with Javascript autocomplete.
B2C dues to security issues had prohibited Javascript.
So I filled email/password with B2C flows and then decided to redirect it my own page within a mvc route of my original project. This one uses https://github.com/Azure-Samples/active-directory-dotnet-graphapi-web/blob/master/WebAppGraphAPI/Controllers/UsersController.cs as an inspiration for Graph API.
I am able to successfully get token via
adClient = new ActiveDirectoryClient( serviceRoot, async () => await GetAppTokenAsync());
However the following fails with "Insufficient privileges to complete" exception
userResult = (User)adClient.Users.GetByObjectId(userObjectID).ExecuteAsync().Result;
I have tried doing the following https://social.msdn.microsoft.com/Forums/azure/en-US/6dd08794-ab89-4513-91e5-546c97a85adc/graph-client-throwing-insufficient-privileges-to-complete-the-operation-on-creating-ad-user?forum=WindowsAzureAD as well as try https://github.com/Azure-Samples/active-directory-dotnet-graphapi-console/issues/27 powershell trick
powershell fails with
C:\Users\Karan\Desktop\dev> $msolcred = Get-Credential cmdlet Get-Credential at command pipeline position 1 Supply values for the following parameters: Credential PS C:\Users\Karan\Desktop\dev> Connect-MsolService -credential $msolcred Connect-MsolService : Exception of type 'http://Microsoft.Online .Administration.Automation.MicrosoftOnlineException' was thrown. At line:1 char:1 + Connect-MsolService -credential $msolcred + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (:) [Connect-MsolService], Mic rosoftOnlineException + FullyQualifiedErrorId : 0x800488D6,http://Microsoft.Online .Administration.Autom ation.ConnectMsolService .....
also tried steps mentioned in https://learn.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-devquickstarts-graph-dotnet
Also added graph API permissions "Read / write directory" in B2C AD here
also ticked more options in Windows Azure Active Directory
As well as ticked then in Old portal.
This has been resolved. I had to create a new application. It was clearly written "Do not modify" against my B2C generated application - and I was modifying permissions for that. So I added a new application and granted that read and write directory. My mistake.

Resources