I am getting below error while trying to create user on remote computer.
System.UnauthorizedAccessException: General access denied error at System.DirectoryServices.Interop.UnsafeNativeMethods.IAds.GetInfo() at System.DirectoryServices.DirectoryEntry.RefreshCache() at System.DirectoryServices.AccountManagement.PrincipalContext.DoMachineInit() at System.DirectoryServices.AccountManagement.PrincipalContext.Initialize() at System.DirectoryServices.AccountManagement.PrincipalContext.ContextForType(Type t) at System.DirectoryServices.AccountManagement.Principal.GetStoreCtxToUse() at System.DirectoryServices.AccountManagement.Principal.set_DisplayName(String value) at testemail.CreateLocalWindowsAccount(String username, String password, String displayName, String description, Boolean canChangePwd, Boolean pwdExpires)
here is the code.
public void CreateLocalWindowsAccount(string username, string password, string displayName, string description, bool canChangePwd, bool pwdExpires)
{
try
{
PrincipalContext context = new PrincipalContext(ContextType.Machine, "127.0.0.1");
UserPrincipal user = new UserPrincipal(context);
user.SetPassword(password);
user.DisplayName = displayName;
user.Name = username;
user.Description = description;
user.UserCannotChangePassword = canChangePwd;
user.PasswordNeverExpires = pwdExpires;
user.Save();
//now add user to "Users" group so it displays in Control Panel
GroupPrincipal group = GroupPrincipal.FindByIdentity(context, "Remote Desktop Users");
group.Members.Add(user);
group.Save();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
Related
I would like to download a PDF report from our Microsoft Report Server using my C# code. I don't know why, but I' m doing something wrong. I always get an error back that the authentication failed (HTTP 401).
public static async Task<Stream> DownloadWebDocument(string url) {
if (string.IsNullOrEmpty(url))
throw new ArgumentNullException(nameof(url));
WebRequest request = WebRequest.Create(url);
request.Method = "GET";
request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
request.Credentials = new NetworkCredential("MyUsername", "MyPassword", "MyDomain");
//request.Headers.Add("Authorization", $"Basic {Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("MyUsername:MyPassword"))}");
try {
using WebResponse response = await request.GetResponseAsync();
return response.GetResponseStream();
} catch (Exception ex) {
var a = ex.Message;
throw;
}
//return await DownloadWebDocument(uri);
}
This code always runs into the exception. But why?
PS:
As requested, here's the stack trace. There is no inner exception.
bei System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
bei System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde ---
bei System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
bei System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
bei DE.ZA.TrailerLoadingAssistant.Web.Code.WebHelper.<DownloadWebDocument>d__0.MoveNext() in C:\Users\Reichelt\source\repos\DE.ZA.TrailerLoading\DE.ZA.TrailerLoadingAssistant.Web\Code\WebHelper.cs:Zeile 28.
I realized, that if I use request.Credentials = CredentialCache.DefaultCredentials, it works. So there must be something wrong with my credentials. But it's definitely no typo.
I've had this problem and it seemed someone was changing the network permissions. One week using Credentials would work then the next week using DefaultCredentials worked. Really strange, so I put in a Try/Catch and resort to the DefaultCredentials if the Service Account fails, see the code comment:
public class SRSHelper
{
private ReportingService2005 rsServ;
private ReportingExecution2005 rsExec = new ReportingExecution2005();
private ReportParameter[] reportParameters;
private ExecutionInfo execInfo = null;
public SRSHelper(string reportUserName, string decryptedPassword, string reportDomain, string reportServerURL)
{
rsServ = new ReportingService2005(reportServerURL);
rsExec.Url = reportServerURL + #"ReportExecution2005.asmx";
System.Net.NetworkCredential creds = new System.Net.NetworkCredential();
creds.UserName = reportUserName;
creds.Password = decryptedPassword;
creds.Domain = reportDomain;
rsExec.Credentials = creds;
rsServ.Credentials = creds;
}
public ReportParameter[] GetSRSReportParameters(string reportName)
{
string report = "/Reporting/" + reportName;
bool forRendering = false;
string historyID = null;
ParameterValue[] values = null;
DataSourceCredentials[] credentials = null;
try
{
return rsServ.GetReportParameters(report, historyID, forRendering, values, credentials);
}
catch
{
//If the Service Account credentials fail to work - try the users credentials - XYZ vendor regularly change things around or the network fails or for some reason beyond our control we have to change the settings.
rsExec.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
rsServ.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
return rsServ.GetReportParameters(report, historyID, forRendering, values, credentials);
}
}
Actually I use different method to render my report as PDF document:
public static byte[] DownloadAsPDF(string ReportServer, string ReportPath)
{
ReportViewer ReportViewer1 = new ReportViewer();
ReportViewer1.ServerReport.ReportServerCredentials = new
CustomReportCredentials("MyUsername", "MyPassword", "MyDomain");
ReportViewer1.ProcessingMode =
Microsoft.Reporting.WebForms.ProcessingMode.Remote;
ReportViewer1.ServerReport.ReportServerUrl = new Uri(ReportServer);
ReportViewer1.ServerReport.ReportPath = ReportPath;
byte[] bytes = ReportViewer1.ServerReport.Render("PDF");
return bytes;
}
public class CustomReportCredentials :
Microsoft.Reporting.WebForms.IReportServerCredentials
{
// local variable for network credential.
private string _UserName;
private string _PassWord;
private string _DomainName;
public CustomReportCredentials(string UserName, string PassWord,
string DomainName)
{
_UserName = UserName;
_PassWord = PassWord;
_DomainName = DomainName;
}
public System.Security.Principal.WindowsIdentity ImpersonationUser
{
get
{
return null; // not use ImpersonationUser
}
}
public ICredentials NetworkCredentials
{
get
{
// use NetworkCredentials
return new NetworkCredential(_UserName, _PassWord,
_DomainName);
}
}
public bool GetFormsCredentials(out Cookie authCookie, out string
user, out string password, out string authority)
{
authCookie = null;
user = password = authority = null;
return false;
}
}
I have the requirement that the ldap user has to change password for himself, without having the older password. As this is for the forgot password feature.
public static JsonObject updatePassword(String username, String newPassword, String dnTemplate) {
JsonObject response=new JsonObject();
String dn = "uid=" + username + "," + dnTemplate;
ModificationItem[] mods = new ModificationItem[1];
mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
new BasicAttribute("userPassword", hashMD5Password(newPassword)));
try {
ldapContext.modifyAttributes(dn, mods);
ldapContext.close();
} catch (NamingException e) {
System.out.println(e);
}
return response;
}
public static void main(String[] args) {
boolean isldapContext=LDAPUtils.initilaizeLDAP("ldap://ip:389","","","");
System.out.println("isldapContext:"+isldapContext);
JsonObject res=LDAPUtils.updatePassword("username","password","ou=People,dc=xxx,dc=xxx");
System.out.println(res);
}
When the above code is executed, m getting the below error:
isldapContext:true
javax.naming.AuthenticationNotSupportedException: [LDAP: error code 8 - modifications require authentication]; remaining name 'uid=111,ou=People,dc=xxx,dc=xxx'
I trying impliment Active Directory authentication for my ASP.NET MVC application. I use System.DirectoryServices and during login find user in UserManager. If user not found I'm trying find user in Active Directory and if successful register user in asp.net mvc app with UserManager.CreateAsync().
private ApplicationUserManager _userManager;
private ApplicationRoleManager _roleManager;
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel loginModel, string returnUrl)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindAsync(loginModel.UserName, loginModel.Password);
if (user != null)
{
await SignInAsync(user, loginModel.RememberMe);
return RedirectToLocal(returnUrl);
}
string userFullName;
if (AuthenticateActiveDirectoryUser("mydomain.local", loginModel.UserName, loginModel.Password, out userFullName))
{
var newUser = new ApplicationUser { UserName = loginModel.UserName, FullName = userFullName };
var result = await UserManager.CreateAsync(newUser, loginModel.Password);
if (result.Succeeded)
{
await SignInAsync(newUser, loginModel.RememberMe);
return RedirectToLocal(returnUrl);
}
AddErrors(result);
}
else
{
ModelState.AddModelError("", "Invalid UserName or Password");
}
}
return View(loginModel);
}
private bool AuthenticateActiveDirectoryUser(
string domain,
string username,
string password,
out string fullName)
{
fullName = string.Empty;
var domainAndUsername = string.Format("{0}\\{1}", domain, username);
var ldapPath = "";
var entry = new DirectoryEntry(ldapPath, domainAndUsername, password);
try
{
// Bind to the native AdsObject to force authentication.
var obj = entry.NativeObject;
var search = new DirectorySearcher(entry) { Filter = "(SAMAccountName=" + username + ")" };
search.PropertiesToLoad.Add("cn");
var result = search.FindOne();
if (result == null)
return false;
try
{
fullName = (string)result.Properties["cn"][0];
}
catch
{
fullName = string.Empty;
}
}
catch (Exception ex)
{
return false;
}
return true;
}
But in my implementation ignored cases if user change password in Active Directory account or AD Account was deleted.
I can check it manually in my code, but maybe exists other ways in ASP.NET Identity to implement authentication by Active Directory user account?
see if this can help u
protected bool ActiveDirectoryLogin(string Username, string Password, string Domain)
{
bool Success = false;
//System.DirectoryServices.DirectoryEntry Entry =
// new System.DirectoryServices.DirectoryEntry("LDAP://***.**.**.**:389/cn=***-People,o=**,dc=**,dc=edu,dc=sa", "uid=" + Username + ",cn=***-People,o=***,dc=***,dc=edu,dc=sa", Password, AuthenticationTypes.None);
System.DirectoryServices.DirectoryEntry Entry =
new System.DirectoryServices.DirectoryEntry("LDAP://ldapmaster.***.edu.sa:389/cn=***-People,o=***,dc=***,dc=edu,dc=sa", "uid=" + Username + ",cn=***-People,o=***,dc=***,dc=edu,dc=sa", Password,AuthenticationTypes.None);
//System.DirectoryServices.DirectoryEntry Entry =
// new System.DirectoryServices.DirectoryEntry("LDAP://ldapmaster.***.edu.sa:389/cn=***-People,o=***,dc=***,dc=edu,dc=sa", Username , Password, AuthenticationTypes.None);
System.DirectoryServices.DirectorySearcher Searcher = new System.DirectoryServices.DirectorySearcher(Entry);
try
{
Object nat = Entry.NativeObject;
Success = true;
// System.DirectoryServices.SearchResult Results = Searcher.FindOne();
// Success = (Results != null);
}
catch (Exception e)
{
Success = false;
}
return Success;
}
I have few textboxes whose values are to be inserted into SQl table on Submit button click. But it gives me "Object reference not set to an instance of an object" Exception. Below is the code I have written for this. Please do help me in this.
contact_new.aspx.cs
protected void btnSubmit_Click(object sender, EventArgs e)
{
DateTime dtime;
dtime = DateTime.Now;
string ocode = offercode.Text;
string firstname = firstnamepreapp.Text;
string lastname = lastnamepreapp.Text;
string email = emailpreapp.Text;
string phoneno = phonepreapp.Text;
string timetocall = besttimepreapp.SelectedItem.Value;
string time = dtime.ToString();
//Insert the data into autoprequal table
<--- GIVES ME AN ERROR ON THIS LINE --->
Insert.insertINTOautoprequal(ocode, time, firstname, lastname, email, phoneno, timetocall);
}
Insert.cs (App_code class)
namespace InsertDataAccess
{
public class Insert
{
public Insert()
{
//
// TODO: Add constructor logic here
//
}
public static bool insertINTOautoprequal(string code, string time, string first, string last, string email, string phoneno, string timetocall)
{
bool success = false;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connstring"].ConnectionString);
conn.Open();
string query = "Insert INTO autoprequal(offercode, timeofday, firstname, lastname, emailID, phone, besttimetocall) Values(#offercode, #time, #first, #last, #email, #phoneno, #timetocall);";
SqlCommand cmd = new SqlCommand(query, conn);
try
{
cmd.Parameters.AddWithValue("#offercode", code);
cmd.Parameters.AddWithValue("#time", time);
cmd.Parameters.AddWithValue("#first", first);
cmd.Parameters.AddWithValue("#last", last);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#phoneno", phoneno);
cmd.Parameters.AddWithValue("#timetocall", timetocall);
if (cmd.ExecuteNonQuery() == 1) success = true;
else success = false;
return success;
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
}
}
Step through the code, as the error is most likely bubbling up from the SQL insert routine. I woulud guess the connection string is not being pulled from the configuration file, but without stepping through that is a wild guess. I would take time to learn how to debug in Visual Studio, as it will help you easily spot what cannot be a problem so you can focus on what is likely to be the problem.
I want to be able to view a SQL Server 2005 Reporting Services report from an ASP.NET application in a DMZ through a ReportViewer control. The SQLand SSRS server are behind the firewall.
`So I had to change the way an ASP.NET 2.0 application called reports from pages. Originally, I used JavaScript to open a new window.
ViewCostReport.OnClientClick = "window.open('" + Report.GetProjectCostURL(_PromotionID) + "','ProjectCost','resizable=yes')";
The issue I had was that the window.open call would only work within the client network and not on a new web server located in their DMZ. I had to create a new report WebForm that embedded a ReportViewer control to view the reports.
The other issue I had is that the Report Server had to be accessed with windows Authentication since it was being used by another application for reports and that app used roles for report access. So off I went to get my ReportViewer control to impersonate a windows user. I found the solution to be this:
Create a new class which implements the Microsoft.Reporting.WebForms.IReportServerCredentials interface for accessing the reports.
public class ReportCredentials : Microsoft.Reporting.WebForms.IReportServerCredentials
{
string _userName, _password, _domain;
public ReportCredentials(string userName, string password, string domain)
{
_userName = userName;
_password = password;
_domain = domain;
}
public System.Security.Principal.WindowsIdentity ImpersonationUser
{
get
{
return null;
}
}
public System.Net.ICredentials NetworkCredentials
{
get
{
return new System.Net.NetworkCredential(_userName, _password, _domain);
}
}
public bool GetFormsCredentials(out System.Net.Cookie authCoki, out string userName, out string password, out string authority)
{
userName = _userName;
password = _password;
authority = _domain;
authCoki = new System.Net.Cookie(".ASPXAUTH", ".ASPXAUTH", "/", "Domain");
return true;
}
}
Then I created an event for the button to call the report:
protected void btnReport_Click(object sender, EventArgs e)
{
ReportParameter[] parm = new ReportParameter[1];
parm[0] =new ReportParameter("PromotionID",_PromotionID);
ReportViewer.ShowCredentialPrompts = false;
ReportViewer.ServerReport.ReportServerCredentials = new ReportCredentials("Username", "Password", "Domain");
ReportViewer.ProcessingMode = Microsoft.Reporting.WebForms.ProcessingMode.Remote;
ReportViewer.ServerReport.ReportServerUrl = new System.Uri("http://ReportServer/ReportServer");
ReportViewer.ServerReport.ReportPath = "/ReportFolder/ReportName";
ReportViewer.ServerReport.SetParameters(parm);
ReportViewer.ServerReport.Refresh();
}