msdeploy error ERROR_USER_UNAUTHORIZED: Web deployment task failed - msbuild

Web deployment task failed. Error ERROR_USER_UNAUTHORIZED
We are using Tfs Build Automation and msdeploy for publishing an web application on remote machine.
On "Visual Studio Build" step we set this parameters on "MSBuild Arguments":
/p:DeployOnBuild=true;PublishProfile=myProfile;AllowUntrustedCertificate=true;UserName=$(UserName);Password=$(Password)
After quing the build we get this error:
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\Web\Microsoft.Web.Publishing.targets(4276,5): Error ERROR_USER_UNAUTHORIZED: Web deployment task failed. (Connected to the remote computer ("MySERVER") using the Web Management Service, but could not authorize. Make sure that you are using the correct user name and password, that the site you are connecting to exists, and that the credentials represent a user who has permissions to access the site. Learn more at: http://go.microsoft.com/fwlink/?LinkId=221672#ERROR_USER_UNAUTHORIZED.)
I am sure that username and password is correct, and the user isAdministrator on the server (MySERVER).
I checked the Management Service log on IIS and found something important:
the build agent's username(tfsadmin) sent for deploy on IIS instead of the user/pass that I set in build variables.
Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status time-taken
2018-01-03 09:29:02 MYSERVERIP HEAD /msdeploy.axd site=MySiteName 8172 - MyBuildServerIP - - 401 2 5 1322
2018-01-03 09:29:02 MYSERVERIP HEAD /msdeploy.axd site=MySiteName 8172 tfsadmin MyBuildServerIP - - 401 1 1326 86
Update 1:
I add more information, as you see below in build log, in msBuildArgs the password is empty (instead of ********)!
WebDeploy Version : 3.6
TFS Version : 2015.1
Target Machine (MySERVER) : Windows 2012 R2
IIS Version : 8.5
The "tfsadmin" user has local administrator of target server (MyServer) and IIS Manager Permission on the target IIS Site.
Build log :
2018-01-06T06:37:19.9298797Z Starting task: Build solution $/MyProject/MySolution.sln
2018-01-06T06:37:20.0529203Z Executing the powershell script: D:\Agents\Agent-01\tasks\VSBuild\1.0.16\VSBuild.ps1
2018-01-06T06:37:20.3760645Z ##[debug]Entering script VSBuild.ps1
2018-01-06T06:37:20.3790648Z ##[debug]vsLocation =
2018-01-06T06:37:20.3800653Z ##[debug]vsVersion = 14.0
2018-01-06T06:37:20.3810663Z ##[debug]msBuildLocation =
2018-01-06T06:37:20.3820668Z ##[debug]msBuildVersion =
2018-01-06T06:37:20.3830692Z ##[debug]msBuildArchitecture = x64
2018-01-06T06:37:20.3840679Z ##[debug]msBuildArgs = /p:DeployOnBuild=true;PublishProfile=myProfile;AllowUntrustedCertificate=true;UserName=tfsadmin;Password=;Pass2=********
2018-01-06T06:37:20.3840679Z ##[debug]solution = D:\Agents\Agent-01\_work\2\s\MyProject\MySolution.sln
2018-01-06T06:37:20.3860721Z ##[debug]platform =
2018-01-06T06:37:20.3870700Z ##[debug]configuration =
2018-01-06T06:37:20.3880727Z ##[debug]clean = true
2018-01-06T06:37:20.3890697Z ##[debug]restoreNugetPackages = true
2018-01-06T06:37:20.3890697Z ##[debug]logProjectEvents = true
2018-01-06T06:37:20.4010877Z ##[debug]Loading module from path 'D:\Agents\Agent-01\agent\worker\Modules\Microsoft.TeamFoundation.DistributedTask.Task.Internal\Microsoft.TeamFoundation.DistributedTask.Task.Internal.dll'.
...
Can anybody help me ?

You are correct that the wrong username and password were ultimately used to authenticate the request. Running the command net helpmsg 1326 (1326 is the sc-win32-status value from the log entry you provided) yields "The user name or password is incorrect."
Also interesting is the request/response logged before that. The substatus value 2 for a 401 means "Access is denied due to server configuration favoring an alternate authentication method." according to TechNet. And net helpmsg 1322 yields "This operation is disallowed as it could result in an administration account being disabled, deleted or unable to logon."
Review (or re-review) the instructions at https://learn.microsoft.com/en-us/iis/publish/using-web-deploy/configure-the-web-deployment-handler
If your deployment is still not working, take a look at Microsoft's Troubleshooting Common Problems with Web Deploy.

Deploy from VS with the command line will use the user name and password you provided. However deploy from TFS will use the build agent. So, the first thing is that the service account of the build process should has the correct permission to access the remote server.
Just try to give the build service account local administrator permissions and IIS Manager Permissionson to the site's scope on the remote server ("MySERVER"). Then set the username parameter to "" (empty quotes) and the password field omitted.
Reference: Build only works with username and password in msbuild arguments
This error code can surface because of a number of different reasons.
It typically indicates an authentication or authorization problem, and
can happen because of any of hte following reasons:
If connecting using the Web Management Service:
Verify that the username and password are correct
Verify that the site exists
Verify that the user has IIS Manager Permissions to the site's scope
If connecting using the Remote Agent Service:
Verify that the username and password are correct
Verify that the user account you specified is a member of the Administrators group on the remote computer. NOTE: Because of a bug
in Web Deploy 2.0, the user must be either the built-in Administrator
or a member of the Domain Administrators security group. Attempts to
sync with any other user account, even if it is an administrator,
will see this error code. Verify that the site exists
Reference : ERROR_USER_UNAUTHORIZED
UPDATE:
By default, Web Deploy will connect using HTTP Basic Authentication.
When using HTTP Basic Authentication, specific credentials must be supplied,
e.g.
msdeploy.exe -verb:dump -source:apphostconfig,wmsvc=demo-host,authType:basic,username=someuser,password=somepassword
In your scenario, you can try set the AuthType as NTLM, then try it again.
Just try adding the line <AuthType>NTLM</AuthType> to the publish .pubxml file.

Try this:
On your server go to Computer Management
From the left pan select Local Users and Groups
Go to users find the tfsadmin user
Right click on it and click on Set Password
Give your existing password (whatever it is)
This seems unnecessary but worked for me. I hope someone can explain the "why".

Related

Host .net core app with iis give a database access error

I have a .Net Core 2.0 application that I host in IIS 7.
With IIS Express the application works fine and I'm able to connect to the database successfully. With IIS I get this error:
Cannot open database "Books" requested by the login. The login failed. Login failed for user 'DOMAINNAME\PCNAME$'.
My connectionString in appsettings.production.json file looks like this :
"ConnectionStrings": {
"BooksDatabase": "Server=PCNAME\\SQLEXPRESS;Database=Books;user id=iisAccess;password=iisPassword;Trusted_Connection=True;ConnectRetryCount=0;MultipleActiveResultSets=true"
};
What am I doing wrong and why does it say that the "login failed for 'DOMAINNAME\PCNAME$'" when I put the credentials user id=iisAccess;password=iisPassword; in my JSON file?
You are asking for Windows Authentication:
Trusted_Connection=True
Remove this part of the connection string and give it another try.
The reason for the error goes along these lines:
IISExpress runs as a normal process in your logon session. So it runs with your Windows Credentials. When your app is running inside IISExpress it is actually running under your credential, and when you connect to the database using Windows Authentication, is your login that SQL Server will receive.
The full IIS on the other hand runs as a service under a different session and a different user account. There are the application pools that also play a part and run under yet another account. But the main thing is that those default IIS accounts are local accounts, so they have no "visibility" to another computers. Hence when your app tries to connect to SQL Server, SQL "sees" the machine account, which goes by the name DOMAIN\MACHINE$.
Most likely, ASPNETCORE_ENVIRONMENT is not set correctly on the server (i.e. either not set at all or not set to Production).
On your server, edit the system environment variables and add one (if it doesn't already exist) with the name ASPNETCORE_ENVIRONMENT and the value Production. Also, edit the advanced settings of your app pool in IIS for the application and ensure that the key Load User Profile is set to True.

Installing Teamcity build agent as a user: failed to install the service. selected account does not have enough rights

I want to install a TeamCity BuildAgend as a user. When entering my user credentials here:
I always get this error:
NOTE: My account (user) is Administrator with full permission!
How can I do this?
The error message says it does not have "enough rights to run as a service",
this is slightly different from just being an administrator.
Go to Control Panel> Administrative Tools> Local Security Policy.
Select Local Policies> User Rights Assignment.
Scroll down through the list of policies and look for Log on as a service.
Add the account you're using to the list of accounts with this right.
That should in theory be all you need to allow the service to run under that user.
The best powershell command that I have found for this is:
Grant-Privilege -Identity $SERVICE_USERNAME -Privilege SeServiceLogonRight
Requires use of the Carbon framework.
I'm a Windows 10 Home user and the steps above did not work for me, but the following did:
Enable gpedit.msc by running the batch file as explained here under Method 1: https://www.askvg.com/how-to-enable-group-policy-editor-gpedit-msc-in-windows-7-home-premium-home-basic-and-starter-editions/
Run gpedit.msc
Go to Local Computer Policy / Computer Configuration / Windows Settings / Security Settings / Local Policies / User Rights Assignment
Double-click Log on as a service
On the window that appears, click Add User or Group...
Enter your username and click the Check Names button
Your name will be modified, adding the machine name as the prefix. Click OK
Click OK on the Log on as a service Properties window to apply the change.
It is a little bit of a pain, but after doing that, I was able to continue installing TeamCity

Jenkins and Visual Studio Online integration authentication

right now I am trying to Setup Continuouse Integration - Delivery for a basic WCF Service, which will be hosted on a Microsoft Azure VM. The Project is Version Controlled through Visual Studio Online. So I installed Jenkins (also on the Azure VM), TFS plugin etc. and started the first Test Build:
As Server URL I used "[VSO Adress]/DefaultCollection"
and for Login purposes my Microsoft Account (I can Access VSO with that). The Problem is, when I run the Build I get the following error in Jenkins:
Started by user Developer
Building in workspace C:\Program Files (x86)\Jenkins\jobs\test\workspace
[workspace] $ "C:\Program Files (x86)\TEE-CLC-11.0.0.1306\TEE-CLC-11.0.0\tf.cmd" workspaces -format:brief -server:[VSO Adress]/DefaultCollection ****"
An error occurred: Access denied connecting to TFS server [VSO Adress] (authenticating as har****#*******o.com)
FATAL: Executable returned an unexpected result code [100]
ERROR: null
Finished: FAILURE
So my question is, whether it is generally possible to connect Jenkins and VSO that way and if so, which login credentials are needed
You will not be able to authenticate with your Microsoft ID as Jenkins is not able to get the encrypted token. If you head over to VSO you can open your profile (top right) and configure alternative credentials you can use them to login.
Also you can get service account credentials through the API. I created a simple tool for this: http://nakedalm.com/tfs-service-credential-viewer/
It's crude but usually works.

Granting write permissions to a networked UNC folder for ASP.NET under IIS 7.5 and Windows Server 2008 R2

BLUF
Our application is attempting to write a file to a UNC folder using an ASP.NET web service running under .NET 4.5, IIS 7.5, and Windows Server 2008 R2. However, any attempt to write the file to the desired location results in an access denied exception.
The task seems simple however me and my team have been troubleshooting this for a while now and we are stumped as to what may be causing the error. Below are the details of our setup and what we have tried and found so far. Names have been changed to protect the innocent.
Environment Setup
The web server, mywebserver, has a website named My.Site.Com with a corresponding application pool named My.Site.Com. The application pool is configured as shown below.
.NET Framework Version : v4.0
Enable 32-bit Applications : False
Managed Pipeline Mode : Integrated
Name : My.Site.Com
Identity : ApplicationPoolIdentity
Load User Profile : False
The UNC path we are attempting to write to is \myotherserver\mydirectories\output where mydirectories is the actual share. On this share a domain group named mygroup-www has been granted full permissions to the share and all subfolders. The machine account (i.e., mywebserver) is a member of this mygroup-www group.
NOTE: For the moment, this UNC path actually lives on the same
machine, mywebserver. However, this will eventually be moved to a machine other
than mywebserver in our test environment and in the production environment
when that it is ready. Currently, I only have the one test environment to troubleshoot with.
The error can be replicated by executing the following code.
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public string ExportReport(int reportId)
{
try
{
string output = ConfigHelper.OutputPath + "test.html"; // UNC path
string url = ConfigHelper.VirtualPath + "test.html";
string[] lines = { "Hello", "World!" };
File.WriteAllLines(output, lines); // Access Denied!
return url;
}
catch (System.Exception ex)
{
Logger.ErrorException("Error exporting report", ex);
throw;
}
}
Troubleshooting
Failed Attempts
We tried various combinations of group/user permissions on the folders (listed below). When running these tests we also ran Process Monitor. For each configuration we saw the same result. The w3wp.exe process attempted to create the file in the desired location but reported a result of ACCESS DENIED. The user of each configuration was IIS APPPOOL\My.Site.Com as expected.
Granting mydomain\mymachine$ full permissions to \myotherserver\mydirectories
Granting mydomain\mymachine$ full permissions to \myotherserver\mydirectories\output
NOTE: I have also tried modifying the code so that it would read a
simple file from \myotherserver\mydirectories\output. When
attempting to read the file, the process fails with an ACCESS DENIED
message as it did when writing the file.
Successful Attempts
We also tried several configurations that worked.
Grant the local IIS APPPOOL\My.Site.Com permissions
The first configuration to work was to grant the IIS APPPOOL\My.Site.Com full permissions to \myotherserver\mydirectories The file was successfully written however the process's user was quite unexpectedly a domain account that was set up for a web application on the same machine in another website. This remains very confusing but worked as the 'other' account also has write permissions to the share.
This won't work in production as we cannot use local accounts to grant access to networked resources but is an interesting data point nonetheless.
Change the App Pool Identity to Domain User
The second configuration that worked was to change the My.Site.Com application pool's identify to domain account that had full permissions to \myotherserver\mydirectories. This was a 'vanilla' domain account that was manually created by us. We did not capture what the user of the process was but that may be another useful data point.
This option may be possible, however it breaks away from best practices with IIS 7.5 and may not be allowed in our production environment due to fairly stringent IT policies.
Run the Site On My Development Machine
The third test was to run the site locally on my development machine, mydevmachine. My local IIS configuration is identical to mywebserver with the exception that I am running Windows 7 instead of Windows Server 2008. I granted full permissions for mydomain\mydevmachine to the \myotherserver\mydirectories and ran the application. The file was successfully written. According to Process Monitor the user for the process was correctly set to IIS APPPOOL\My.Site.Com.
Conclusion
We would like to enable write access as designed using the machine account of mywebserver. We have read ApplicationPoolIdentity user cannot modify files in shared folder in Windows Server 2008 and Permissions for Shared Folder for IIS 7 Application Pool Identity Across Domain and Application Pool Identities.
According to this information we should be able use the machine account to grant read and write access to networked resources such as the UNC path. In fact, I can do this in the desired manner when running the web site from my development machine.
There are a couple thoughts that come to mind. Perhaps there is something wrong with the machine account of the test web server. Or perhaps that 'other' software is interfering with the process somehow.
Any thoughts as to what may be causing this issue? What else should we do to troubleshoot?
Reboot your 'mywebserver'.
Marvel at the now mysteriously functional ApplicationPoolIdentity.
Install MS HotFix KB2545850 and learn the details about this bug in KB2672809 which also shows the steps to reproduce and demonstrate this apparently random problem. Direct download link here.
Speculate why Microsoft has not managed to release a normal windows update for this in the 3 years since that hotfix was published. While people still continue running into it and pulling their hair out because of this obscure problem.
Learn about the other folks who have shared and enjoyed this gift from MS that still continues to keep on giving:
IIS application using application pool identity loses primary token?
DirectoryServicesCOMException 80072020 From IIS 7.5 Site Running Under ApplicationPoolIdentity
ApplicationPoolIdentity cannot access network resources
ApplicationPoolIdentity IIS 7.5 to SQL Server 2008 R2 not working
Windows Authentication Failed when using application pool identity
IIS 7.5 stops using machine account to connect to network resource when using AppPoolIdentity
Your Windows 7 dev machine probably worked fine because it reboots more often than the server. Congrats on your very well written and thorough bug report. I rarely see that here.
I had similar problem accessing a network share using AppPoolIdentity in an ASP.NET application (access denied).
Using NetworkService account or other domain account worked but these were not the best solution.
I performed almost all the tests you did but finally found something that worked.
I figured out that the Network Service account was not used when accessing the shares, just like you did (i expected domain\machine$ account)
This worked for us:
On your IIS web site, go to Authentication and change the Anonymous Authentication item to "Application Pool Identity". It's by default set to "IUSR". This solved our problem.
Also maybe activating ASP.NET impersonation (still in Authentication menu) may help.
Thibault
I have faced same issue, I resolved by creating one domain account for each environemt (QA, STAGE, PRODUCTION). In Application pool identity I have set custom account and I used domain user for respective account. Now It gives me the ability to write and read the files from UNC Path.

Strange Web Deploy access issue

I'm getting an odd problem with connecting to a server.
The server's logs read:
2013-05-21 11:18:24 [IP ADDRESS] HEAD /msdeploy.axd site=[SITE NAME] 8172 administrator [MY IP] - 401 1 1326 214
I am using the administrator account so I can't understand why it's not allowing access!
I am using VS2012 and Web Deploy 3.0 on Server 2008R2 x86.
UPDATE
When using the command msdeploy.exe -verb:dump -source:iisApp=<sitename>,username=administrator,password=<urpassword>,authtype=‌​basic,computername=https://<yourserver>:8172/msdeploy.axd?Site=<sitename> -authtype=basic as suggested by #ShaikhOwais I get the following error:
Error Code: ERROR_USER_UNAUTHORIZED
More Information: Connected to the remote computer ("[COMPUTER NAME]") using the Web Management Service, but could not authorize. Make sure that you are using the correct user name and password, that the site you are connecting to exists, and that the credentials represent a user who has permissions to access the site.
"Make sure that you are using the correct user name and password" - yep.
"that the site you are connecting to exists" - yep
"the credentials represent a user who has permissions to access the site" - it's the administrator...
As stated in the comment above, you need to qualify the username with the domain to which your admin user belongs.
Your script should thus be:
msdeploy.exe -verb:dump -source:iisApp=<sitename>,username=
<DOMAIN>\administrator,password=<urpassword>,authtype=‌​
basic,computername=https://<yourserver>:8172/msdeploy.axd?Site=<sitename>
-authtype=basic
It happen with me and it was share permissions issue that time
Can you try "net use \server\c$\path\to\fodler" and see if you can access this directory?
If it does not help can you please reply -
Are you getting first time this error ? was you able to web deploy on the same server earlier or you are doing first time with this server ?