How to cleanly automate authentication for Azure Devops feeds? - azure

Presumably there are lots of companies who are facing the same struggle we are.
For any microservice, before running a dotnet restore we need to first ensure we've successfully configured our ADO package feeds with an active token.
To achieve this we have a script which downloads and runs the CredentialProvider.VSS.exe (as suggested by Microsoft), using the output to build credentials which then register the feeds on the user's computer. This needs to happen daily as the tokens generated will expire.
The script above is ugly and worse yet, every repository needs it in order to ensure feeds are configured with active tokens. Even if we moved the ugly script to a PowerShell module for example, how would we authenticate against the PS feed in order to download that module?
I don't see why the CredentialProvider is neccessary, why can't nuget just prompt us for credentials whenever our token expires? Has anyone come up with a cleaner solution out there which manages authentication to ADO feeds across multiple repositories?

How to cleanly automate authentication for Azure Devops feeds?
To authentication for Azure Devops feeds, you could try to use the NuGet authenticate task, which configure NuGet tools to authenticate with Azure Artifacts and other NuGet repositories.
Then we could create a new NuGet service connection with PAT:
You can use a longer-term PAT for certification, so you don't have to change certification every day.

another approach using nuget.confg as below
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="AzureDevOpsFeed" value="https://pkgs.dev.azure.com/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/index.json" />
<add key="nuget" value="https://xxxxxxxxxxxxxxxxxxxxx/index.json" />
</packageSources>
<packageSourceCredentials>
<VSTSFeed>
<add key="UserName" value="#{PAT_UserName}#" />
<add key="ClearTextPassword" value="#{PersonalAccessToken}#" />
</VSTSFeed>
</packageSourceCredentials>
</configuration>

Related

Azure App Service Can't Access SharePoint

We have a simple Azure App Service app and part of that app accesses a SharePoint doc library to upload files. This has worked for years but recently stopped working. We generated a new clientid and secret thinking that was the problem - still no luck. We have been working with Microsoft for 3 weeks on the problem and they have been useless - they don't even know what a doc library is most the time and all they do is "take screenshots and will get back."
I can get a token and use it to pull resources in Postman just fine.
The following is the code in web.config:
`<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="ida:ClientId" value="spclientid" />
<add key="ida:AADInstance" value="https://login.microsoftonline.com/" />
<add key="ida:ClientSecret" value="spclientsecret" />
<add key="ida:Domain" value="ourdomain.com" />
<add key="ida:TenantId" value="tenantid" />
<add key="ida:PostLogoutRedirectUri"
value="https://login.microsoftonline.com/common/oauth2/v2.0/logoutsession/" />
</appSettings>`
Errors:1
Error :2
Error: 3
At our rope's end with this one, any ideas?
Thanks in advance.
• You must use ‘AllowAppOnlyPolicy=true’ in your manifest file for the registered Azure AD sharepoint app to acquire token from the registered application in Azure AD on behalf of the service principal created through your ‘App Service’. Also, you can grant the required permissions for accessing the sharepoint online website through your ‘App service’ as shown below in the snapshot through the Azure AD app registration portal instead of the ‘App manifest’ file: -
Thus, when you are providing the correct permissions to the ‘Sharepoint’ portal through this ‘Service Principal’ in Azure AD for OAuth 2.0 as well as configuring the ‘Authentication’ token and protocols too correctly, the Azure App Service should be able to access the Sharepoint doc library to upload files.
• Finally, please once again check the correct value of the secret ID and its value that is being used to connect to the sharepoint website on behalf of the SP app in Azure AD. Also, do check the correct tenant ID, domain and AADInstance of the registered SP for your app service, the details of which you have mentioned in the ‘App settings.json’ file of the code.
For more details and clarification on this, kindly refer to the below links explaining the issues regarding the ‘Sharepoint’ token helper issues and CSOM platform issues regarding various browsers that are used to try to access the same: -
https://github.com/SharePoint/sp-dev-docs/issues/6955
https://learn.microsoft.com/en-us/sharepoint/dev/spfx/use-aadhttpclient

How to: Password Protect Azure App service

I have website that is Hosted in a Azure App Service. are there any options in azure so that I can put a password on the website. Ideally without changing the websites code.
Just a basic password or user name and password, doesn't need to be google or facebook login or AD login.
It is a .net based website and I have seen a few options to do this, but it means I have to change the code of the website in someway or another.
Surely with all that sophisticated cloud technology, I can go in to the portal and set a password at a server level? - Or is the only way to make some kind of change to the application?
It is possible to enable Basic Authentication for Azure Web Apps with some settings in the applicationHost.xdt. You can load some modules in this file on the start of your Web App.
Steps:
Navigate to your WebApp in the Azure Portal
In the left menu, search for the header Development Tools an select Advanced Tools (Kudu)
Use the Debug Console > CMD tool, to navigate to the WebApp directory: \home\site
Create a file named: applicationHost.xdt
Paste the following:
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<location path="%XDT_SITENAME%" xdt:Locator="Match(path)">
<system.webServer>
<rewrite xdt:Transform="InsertIfMissing">
<allowedServerVariables xdt:Transform="InsertIfMissing">
<add name="RESPONSE_WWW_AUTHENTICATE" xdt:Locator="Match(name)" xdt:Transform="InsertIfMissing" />
</allowedServerVariables>
<rules xdt:Transform="InsertIfMissing">
<rule name="BasicAuthentication" stopProcessing="true" xdt:Transform="InsertIfMissing" xdt:Locator="Match(name)">
<match url=".*" />
<conditions>
<add input="{HTTP_AUTHORIZATION}" pattern="^Basic dXNlcjpwYXNzd29yZA==" ignoreCase="false" negate="true" />
</conditions>
<action type="CustomResponse" statusCode="401" statusReason="Unauthorized" statusDescription="Unauthorized" />
<serverVariables>
<set name="RESPONSE_WWW_AUTHENTICATE" value="Basic realm=Project" />
</serverVariables>
</rule>
</rules>
</rewrite>
</system.webServer>
</location>
</configuration>
Change the Basic Auth to your liking (default in example is: user:password)
Make sure the web.config rewrite rules don't contain <clear /> as this wil remove the effects from the applicationHost.xdt file
Save the file and Stop and Start your WebApp (a simple Restart will not suffice)
Notes:
Not sure if this works on Linux based WebApps..
You can add this step to you're deployment pipelines by using FTP
Update: I've noticed issues with applicationHost.xdt while using it on secondary Web App slots. Only the primary slot seems to work.
PS: Cross-post from my answer here.
You can use Authentication and authorization in Azure App Service.
Authentication/Authorization was previously known as Easy Auth.
Azure App Service provides built-in authentication and authorization support, so you can sign in users and access data by writing minimal or no code in your web app, RESTful API, and mobile back end, and also Azure Functions. This article describes how App Service helps simplify authentication and authorization for your app.
Source: Authentication and authorization in Azure App Service and Azure Functions.
EDIT:
The above is a solution to have a password protected App Service without changing any code whatsoever. At this point there is no alternative, as you can see in the open feedback issue Allow HTTP Basic authentication on basic apps
Hi everyone, we understand the demand for this feature, but we do not plan to support authentication at this level. We suggest using EasyAuth for this scenario.
https://learn.microsoft.com/en-us/azure/app-service/overview-authentication-authorization
EDIT 2:
This method forces the user to use google or facebook, etc...
This is not true. You can also create a user in your Azure Active Directory and use that one with Easy Auth. The username would be something like username#<YOUR-TENANT>.onmicrosoft.com

Web Deployment Publish parameters.xml to match windows authentication providers

I have a Web Deployment publish profile in my visual studio project.
I have multiple environments, which in one I use NTLM provider and on the other I user Negotiate:Kerberos provider on the windows authentication mode.
My question is: How can I set the parameters.xml "match" value in order to set the right provider when using msdeploy.
The provider tag is as follows:
<add value="NTLM" />
Or instead:
<add value="Negotiate:Kerberos" />
Is it even possible to pull this of via parameters.xml only?
If not what is the right way of doing so?
Found a workaround.
At the parameters.xml I created a <parameter> element with the following:
<parameterEntry kind="XmlFile" scope="\\web\.config$" match="/configuration/system.webServer/security/authentication/windowsAuthentication/providers/add/#value" />
This parameterEntry will match the providers.
Afterwards, at the deploy time, the value that will be replacing the matched value in the parameterEntry will be: Negotiate:Kerberos.
In this way, I managed to replace the values. Currently it's kind of problematic to place multiple providers, but I think it can be accomplished with matchers and the parameters.xml by changing it a little bit.

Impersonate settings in config for multiple databases

I have a console application which connects to two different SQL databases. I'm using the "impersonate" tag within the config file to force the application to login as "APP_USER". The APP_USER account utilizes windows authentication & has been granted permissions in both databases.
The first DB connection works fine, but the second one fails as it is trying to log in as my account which does not have access.
System.Data.SqlClient.SqlException: Login failed for user 'DOMAIN\CURRENT_USER'.
What do I need to change in my config to make the application login to both databases as another user?
<configuration>
<connectionStrings>
<add name="Connection1" connectionString="metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=DB1;initial catalog=DBcat1;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="Connection2" connectionString="metadata=res://*/Models.Model2.csdl|res://*/Models.Model2.ssdl|res://*/Models.Model2.msl;provider=System.Data.SqlClient;provider connection string="data source=DB2;initial catalog=DBcat2;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<system.web>
<identity impersonate="true" userName="DOMAIN\APP_USER" password="password"/>
</system.web>
</configuration>
Apparently the config-setting route can only be used in asp.net projects. In order to accomplish this within a console application, you have to write code that utilizes LogonUser within the advapi32.dll library.
Similar question: StackOverflow: Windows Impersonation from C#
I based my final code off of the following project: Code Project: A small C# Class for impersonating a User
Everything seems to be working fine now.

Authorization token passed by user Invalid. Azure Cache

Maybe I'm misunderstanding how to create a cache but none of the the IDs or Access keys is working on the to enable the azure cache. I've gone through the following tutorials:
http://msdn.microsoft.com/en-us/library/windowsazure/gg618003.aspx
http://msdn.microsoft.com/en-us/wazplatformtrainingcourse_buildingappswithcacheservice_topic3#_Toc310505080
http://msdn.microsoft.com/en-us/library/windowsazure/gg618003.aspx
And about 1/2 a dozen different how to create a cache in azure pages and I'm still getting.
Authorization token passed by user Invalid.
I've got a website and cloud service with linked storage and nowhere can I find a url "yourcachename.cache.windows.net" or an Authentication Token in the manage Azure portal. Any suggestions would be greatly appreciated.
It turns out that I was getting confused between versions of Azure. I'm not sure what version this started in but I was working in 1.8 and I did not need an access key. Once I added the below sections to the web.config everything worked.
<dataCacheClients>
<dataCacheClient name="default">
<autoDiscover isEnabled="true" identifier="{your cache worker role}" />
<localCache isEnabled="true" sync="TimeoutBased" objectCount="100000" ttlValue="300" />
</dataCacheClient>
</dataCacheClients>
<cacheDiagnostics>
And then in order to get Sessions to work I needed to add this:
<sessionState mode="Custom" customProvider="AFCacheSessionStateProvider">
<providers>
<add name="AFCacheSessionStateProvider" type="Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider, Microsoft.Web.DistributedCache" cacheName="default" dataCacheClientName="default" applicationName="AFCacheSessionState"/>
</providers>
</sessionState>
You need to login to the old portal via the link on the new portal, click on shared caching, service bus and access control. Create/Select a namespace and the auth token would be displayed on the right hand side bar.

Resources