System.IO Exception: Logon failure: unknown user name or bad password - asp.net

System.IO Exception: Logon failure: unknown user name or bad password.
1 minute ago | LINK
Hi All I am trying to resolve this issue with all possible solutions but could not succeed.
Requirement - I should be able to access XML file located in network share share folder for validation of users and other purposes.
Problem: I am able to access the XML file located in Network Share folder when debugging using VS 2010 but not when i published to IIS 7.
Methods Approached: I created a user account XXX and with password and made the user part of Administrators group. Set the website application pool identity to custome user account(XXX) created.
In the web.config I added a line:
<identity impersonate="true" userName="XXX" password="XXXXX"/>
Code where exception is caught-
string UserConfigXML ="\\\\servername\\Engineering\\Kiosk Back Up\\UserCFG.XML";
reader = new StreamReader(UserConfigXML);
string input = null;
string[] sArray;
while ((input = reader.ReadLine().Trim()) != "</USERS>")
{
if (input.Contains("<USER NAME="))
{
sArray = input.Split(new Char[] { '"' });
string sUserName = sArray[1].ToString().ToUpper();
string sDelivery = "";
while ((input = reader.ReadLine().Trim()) != ("</USER>"))
{
char[] array2 = new char[] { '<', '>' };
if (input.Contains("<DELIVERY_MECHANISM>"))
{
string[] mechanism = input.Split(array2);
sDelivery = mechanism[2].ToString().ToUpper();
if (sDelivery == "WEBMAIL")
{
UsersList.Add(sUserName);
}
}
}
}
}
return UsersList;
Any ideas how to resolve the issue?.

I propose 3 fixes for 2 different scenarios:
If you have both computers (server & computer holding the xml) hooked up using domain authentication: create a domain user and give it rights to access that file in the computer holding the xml.
Any other situation than the one mentioned above: create a user with the same name and password on both computers and set that as the one impersonated by the application pool.
(UNSECURE) Works in any scenario, without impersonation: put the XMLs in a network share that allows anonymous access.

Related

when I use asmx service and SSRS report service I am getting "The request failed with http status 401: unauthorised"

I was trying to call report related service (asmx) from my asp.net web application by running locally.
Then an exception happened saying. The request failed with http status401:unauthorised.
In my analysis I understood the issue caused due to below code
SSRSWebService.ReportingService2005 rs = new SSRSWebService.ReportingService2005();
rs.Credentials = new MyReportServerCredentials().NetworkCredentials;
and
Uri reportUri = new Uri(ConfigurationManager.AppSettings["ReportServerManagement.ReportingService2005"]);
this.rptViewer.ServerReport.ReportServerCredentials = new MyReportServerCredentials();
In my detailed analysis I understood that the issue was because of the credential set up in serviceObject.credential OR ServerReport.ReportServerCredentials was wrong. This can be rectified in two different way either by setting credential to default with below code
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;//"rs" is report object
Or locate below code and set up proper authenticated user credential in the code
public WindowsIdentity ImpersonationUser
{
get
{
// Use the default Windows user. Credentials will be
// provided by the NetworkCredentials property.
return null;
}
}
public ICredentials NetworkCredentials
{
get
{
// Read the user information from the Web.config file.
// By reading the information on demand instead of
// storing it, the credentials will not be stored in
// session, reducing the vulnerable surface area to the
// Web.config file, which can be secured with an ACL.
// User name
string userName =
<<AccurateUserName;>>
// Password
string password =
<<AccuratePassword;>>
// Domain
string domain = <<AccurateDomainName;>>
return new NetworkCredential(userName, password, domain);
}
}
In order to check whether which user has the access, we need to type service url ending with asmx (http:/MyServiceHostedServer/MyService.asmx) in a web browser. It will prompt a user name and password . Give our username as :Domain\Username and password.If we are able to see wsdl xml file then that user has the access.

Azure AD Application Add User to Active Directory using Client Credentials

I am trying to add a user to an application Active Directory but with little success. I am using the GraphServiceClient with.Net Core
The documentation here says I need these permissions
Azure AD Graph Client Beta Docs
Application Directory.ReadWrite.All
But I cannot find where in the Azure Portal I can assign this permission.
The code is above, the GraphServiceClient is in beta at the moment and this is not part of the API yet, so I am calling the request manually.
Below is my code for authentication, I am using my applications client secret which is set against the application in the AD. I can read directory data fine.
public async Task AuthenticateRequestAsync(HttpRequestMessage request)
{
try
{
if (null == _configuration)
{
throw new InvalidOperationException("Azure AD Configuration is not set");
}
var authContext = new AuthenticationContext(
$"{_configuration.Instance}/{_configuration.Domain}", false);
var credentials = new ClientCredential(_configuration.ClientId, _configuration.ClientSecret);
var authResult =
await authContext.AcquireTokenAsync("https://graph.microsoft.com/", credentials);
request.Headers.Add("Authorization", "Bearer " + authResult.AccessToken);
}
catch (Exception ex)
{
_logger.Error("Authentication Provider, unable to get token", ex);
}
}
Update - After checking with Rohit's advice, you can see I have the permissions set. But notice they are all in blue with the ticks next to them! I have changed and saved, you can see the save button is disabled. I have clicked Grant Permissions. Is this relevant?
But I cannot find where in the Azure Portal I can assign this
permission.
In Azure portal navigate to Azure Active Directory > App Registrations > Your specific app > Settings > Required Permissions
Click on Add and Select Microsoft Graph
Now, in the Application Permissions section, check "Read and write directory data"
Once you're done, do "Grant Permissions" for Admin consent, as this permission needs it.

Using WebClient to get a intranet files

In our I have company intranet a server, that is responsible for storing files. Initially, the server had to operate only in an intranet environment, but now there is a need to share files with external web applications. Making this server accessible from the internet is not an option.
I want to create a ASP.NET MVC solution that uses the WebClient to get these files from the intranet server and send back them to the user through FileResult of the external app. This client would be provided with custom domain user credentials. So far I have tried to create a CredentialCache class, set correct credentials and append it to WebClients Credentials property like in the following code:
public ActionResult Download(int id, string fileName)
{
var fileService = new FilesService();
var documentUrl = fileService.GetUrlFileByFileId(id);
string filePath = "http://my.intranet.com/" + documentUrl;
var fileNameFromUrl = filePath.Substring(filePath.LastIndexOf("\\") + 1);
byte[] filedata;
CredentialCache cc = new CredentialCache();
cc.Add(new Uri("http://my.intranet.com/"),
"ntlm",
new NetworkCredential("myUserName", "myPassword", "myDomain"));
using (var client = new WebClient())
{
client.Credentials = cc;
filedata = client.DownloadData(filePath);
}
string contentType = MimeMapping.GetMimeMapping(filePath);
var cd = new ContentDisposition
{
FileName = fileName,
Inline = false
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(filedata, contentType);
}
According to the question posted in Domain credentials for a WebClient class don't work it should work, but it’s not. It’s running only if I run the problem on localhost, but when I publish my solution on a test server, it return 401 error. My question is did how to get this working? And is it possible to download files through this method?
UPDATE--- I've published my test app on another server and it started to working. Now the test app is on another server than the server That stores files. Any ideas why it's not working when both are on the same machine?
401 error is unauthorized, so perhaps the issue is related to permissions. Are you sure the user account you are using to login to that folder has the proper access?
Ok, I found the solution on this site: https://blogs.msdn.microsoft.com/distributedservices/2009/11/10/wcf-calling-wcf-service-hosted-in-iis-on-the-same-machine-as-client-throws-authentication-error/
The solution was to add an registry entry and add my web apps to this entry to allow back connections.

Delete file from server: Access to the path is denied

I call this function from with my code-behind:
DeleteFile(Server.MapPath("/") + "sitemap_index.xml")
Public Shared Function DeleteFile(ByVal filename As String) As Boolean
'deletes file from server
Dim bResult As Boolean = False
Try
If File.Exists(filename) Then
'delete file
File.Delete(filename)
bResult = True
Else
bResult = True
End If
Catch ex As Exception
End Try
Return bResult
End Function
I then get the error: Access to the path 'E:\zz\wwwroot\sitemap_index.xml' is denied.
In other sites of myself this logic works great, however on the current site it doesnt. I checked the security settings on my windows server 2008 R2 Standard.
See here the settings I have on my Windows server on folder wwwroot:
SYSTEM: Full Control
NETWORK SERVICE: Read + Write + Read & Execute + List folder contents
IIS_IUSRS: Read + Write
As was suggested by other posts I've been reading I tried adding other user groups, but I have no ASPNET service/group on my server.
When logged in as administrator (Forms authentication) I can click a button to recreate the sitemap_index.xml and sitemaps.xml
Users should be able to delete and add images to the wwwroot\images\uploads folder
Which group should I give what permissions to allow the above to be possible AND secure?
Check the access for the Application Pool user.
Find the application pool that your site is using, right click on it and choose Advanced Settings.... The name of the user that the pool is using is listed next to Identity.
Note that if the identity says "ApplicationPoolIdentity", you should check the access for the user IIS AppPool\<Name of the app pool here> Info about ApplicationPoolIdentity
It looks like Modify permissions are required to delete files. Try granting NetworkService Modify permissions.
I had this problem too. When I applied the codes in this way, I did not encounter any permission requests.
public void DeleteDirectory(string target_dir)
{
string[] files = Directory.GetFiles(target_dir);
string[] dirs = Directory.GetDirectories(target_dir);
foreach (string file in files)
{
System.IO.File.SetAttributes(file, FileAttributes.Normal);
System.IO.File.Delete(file);
}
foreach (string dir in dirs)
{
DeleteDirectory(dir);
}
Directory.Delete(target_dir, false);
}

Open web.config from console application?

I have a console capplication that runs on the same computer that hosts a bunch of web.config files. I need the console application to open each web.config file and decrypt the connection string and then test if the connection string works.
The problem I am running into is that OpenExeConfiguration is expecting a winforms application configuration file (app.dll.config) and OpenWebConfiguration needs to be run through IIS. Since this is my local machine, I'm not running IIS (I use Visual Studio's built-in server).
Is there a way I can open the web.config files while still getting the robustness of .NET's capabilities to decrypt the connectionstrings?
Thanks
Update
The OpenWebConfiguration works if you are querying IIS directly or are the website in question that you want to look up the web.config for. What I am looking to accomplish is the same sort of functionality, but from a console application opening up the web.config file of a website on my same machine not using an IIS query because IIS isn't running on my machine.
Ok I got it... compiled and accessed this so i know it works...
VirtualDirectoryMapping vdm = new VirtualDirectoryMapping(#"C:\test", true);
WebConfigurationFileMap wcfm = new WebConfigurationFileMap();
wcfm.VirtualDirectories.Add("/", vdm);
// Get the Web application configuration object.
Configuration config = WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");
ProtectSection(config, #"connectionStrings", "DataProtectionConfigurationProvider");
This is assuming you have a file called web.config in a directory called C:\Test.
I adjusted #Dillie-O's methods to take a Configuration as a parameter.
You must also reference System.Web and System.configuration and any dlls containing configuration handlers that are set up in your web.config.
The when the ConfigurationManager class grab a section from the config file, it has an "IsProtected" property that it can infer for a given section that you grab. If it is protected, you can then Unprotect it using some code.
The basic method for encrypting/decrypting goes like this (taken from article link below):
private void ProtectSection(string sectionName, string provider)
{
Configuration config =
WebConfigurationManager.
OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section =
config.GetSection(sectionName);
if (section != null &&
!section.SectionInformation.IsProtected)
{
section.SectionInformation.ProtectSection(provider);
config.Save();
}
}
private void UnProtectSection(string sectionName)
{
Configuration config =
WebConfigurationManager.
OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section =
config.GetSection(sectionName);
if (section != null &&
section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
config.Save();
}
}
Check out this article for the full details on working with this.
public static string WebKey(string key)
{
var configFile = new System.IO.FileInfo(webconfigPath);
var vdm = new VirtualDirectoryMapping(configFile.DirectoryName, true, configFile.Name);
var wcfm = new WebConfigurationFileMap();
wcfm.VirtualDirectories.Add("/", vdm);
System.Configuration.Configuration config = WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");
System.Configuration.AppSettingsSection appSettingSection = (System.Configuration.AppSettingsSection)config.GetSection("appSettings");
System.Configuration.KeyValueConfigurationElement kv = appSettingSection.Settings.AllKeys
.Where(x => x.Equals(key))
.Select(x => appSettingSection.Settings[key])
.FirstOrDefault();
return kv != null ? kv.Value : string.Empty;
}
I think you want to use WebConfigurationManager class with its OpenWebConfiguration method.
It takes a path to the web.config and should open it just like it would in a HTTPContext based application.

Resources