I've Encrypted connectionString section in web.config using ASPNET_REGIIS successfully.
however i've done this on my local machine.
When I tried to publish website on a shared hosting server I received a configuration file error.
Is there any way I could Encrypt on a shared hosting server using ASPNET_REGIIS without access to the physical server machine?
Thanks.
I found a solution, Might not be the best but I feel okay with it..
I encrypted web.Config once, using the first function.
I decrypt it on each call.
public static void EncryptConnString()
{
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
ConfigurationSection section = config.GetSection("connectionStrings");
if (!section.SectionInformation.IsProtected)
{
section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
config.Save();
}
}
public static MySqlConnection DecryptConnString()
{
MySqlConnection conn = new MySqlConnection();
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
ConfigurationSection section = config.GetSection("connectionStrings");
if (section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["DatabaseName"].ConnectionString);
return conn;
}
else
return null;
}
(using MySql)
Related
I have MSSQL 2008 installed on my local PC, and my Java application needs to connect to a MSSQL database. I am a new to MSSQL and I would like get some help on creating user login for my Java application and getting connection via JDBC. So far I tried to create a user login for my app and used following connection string, but I doesn't work at all. Any help and hint will be appreciated.
jdbc:jtds:sqlserver://127.0.0.1:1433/dotcms
username="shuxer" password="itarator"
There are mainly two ways to use JDBC - using Windows authentication and SQL authentication. SQL authentication is probably the easiest. What you can do is something like:
String userName = "username";
String password = "password";
String url = "jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url, userName, password);
after adding sqljdbc4.jar to the build path.
For Window authentication you can do something like:
String url = "jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB;integratedSecurity=true";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url);
and then add the path to sqljdbc_auth.dll as a VM argument (still need sqljdbc4.jar in the build path).
Please take a look here for a short step-by-step guide showing how to connect to SQL Server from Java using jTDS and JDBC should you need more details. Hope it helps!
You can use this :
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ConnectMSSQLServer
{
public void dbConnect(String db_connect_string,
String db_userid,
String db_password)
{
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(db_connect_string,
db_userid, db_password);
System.out.println("connected");
Statement statement = conn.createStatement();
String queryString = "select * from sysobjects where type='u'";
ResultSet rs = statement.executeQuery(queryString);
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
ConnectMSSQLServer connServer = new ConnectMSSQLServer();
connServer.dbConnect("jdbc:sqlserver://<hostname>", "<user>",
"<password>");
}
}
I am also using mssql server 2008 and jtds.In my case I am using the following connect string and it works.
Class.forName( "net.sourceforge.jtds.jdbc.Driver" );
Connection con = DriverManager.getConnection( "jdbc:jtds:sqlserver://<your server ip
address>:1433/zacmpf", userName, password );
Statement stmt = con.createStatement();
If your having trouble connecting, most likely the problem is that you haven't yet enabled the TCP/IP listener on port 1433. A quick "netstat -an" command will tell you if its listening. By default, SQL server doesn't enable this after installation.
Also, you need to set a password on the "sa" account and also ENABLE the "sa" account (if you plan to use that account to connect with).
Obviously, this also means you need to enable "mixed mode authentication" on your MSSQL node.
Try to use like this: jdbc:jtds:sqlserver://127.0.0.1/dotcms; instance=instanceName
I don't know which version of mssql you are using, if it is express edition, default instance is sqlexpress
Do not forget check if SQL Server Browser service is running.
You can try configure SQL server:
Step 1: Open SQL server 20xx Configuration Manager
Step 2: Click Protocols for SQL.. in SQL server configuration. Then, right click TCP/IP, choose Properties
Step 3: Click tab IP Address, Edit All TCP. Port is 1433
NOTE: ALL TCP port is 1433
Finally, restart the server.
Simple Java Program which connects to the SQL Server.
NOTE: You need to add sqljdbc.jar into the build path
// localhost : local computer acts as a server
// 1433 : SQL default port number
// username : sa
// password: use password, which is used at the time of installing SQL server management studio, In my case, it is 'root'
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Conn {
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
Connection conn=null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=company", "sa", "root");
if(conn!=null)
System.out.println("Database Successfully connected");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Try this.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class SQLUtil {
public void dbConnect(String db_connect_string,String db_userid,
String db_password) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(db_connect_string,
db_userid, db_password);
System.out.println("connected");
Statement statement = conn.createStatement();
String queryString = "select * from cpl";
ResultSet rs = statement.executeQuery(queryString);
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
} }
public static void main(String[] args) {
SQLUtil connServer = new SQLUtil();
connServer.dbConnect("jdbc:sqlserver://192.168.10.97:1433;databaseName=myDB",
"sa",
"0123");
}
}
Try this
Class.forName( "net.sourceforge.jtds.jdbc.Driver" );
String url ="Jdbc:jtds:sqlsever://ip/instanceName;instance=instanceName;databseName=dbName;user=yourUser;password=yourpass;";
I am trying to create a file in my ASP.NET application (IIS 7.5). The file write is done in a separate thread and is giving access not available error.
What kind of permission does the directory need? I have tried giving full access to IIS_IUSRS and IUSR. But this did not work. Everything works okay in my local machine, but once deployed on the server, I get access error.
string filePath = MapPath("c:\FilePath\");
PrintFile printFile = new PrintFile();
Thread printFileThread = new Thread(delegate()
{
printFile.PrintFile(filePath);
});
printFileThread.Start();
public void PrintFile(string filePath)
{
if (Directory.Exists(filePath) == false)
{
Directory.CreateDirectory(filePath);
}
FileStream fs = new FileStream(filePath + "NewFile.pdf", FileMode.Create);
}
I uploaded nopcommerce solution to appharbor (using this method Can't build notcommerce project under appharbor) and solution succesfully builded, but I receiving 403 error - Forbidden: Access is denied when trying to open page(Allow write-access to file system is set to true).
Thanks and hope for your help
The problem is that the standard NopCommerce solution contains two Web Projects. AppHarbor only deploys one web project per application, and in this case, we happen to deploy Nop.Admin which is not what you want.
To resolve this, you should take advantage of the AppHarbor solution file convention and create an AppHarbor.sln solution file that only references the Nop.Web project.
We use a wrapper in our base controller to ensure that all of our code is oblivious to appharbor port changing.
First, fix in Webhelper.cs:75
public virtual string GetThisPageUrl(bool includeQueryString, bool useSsl)
{
string url = string.Empty;
if (_httpContext == null)
return url;
if (includeQueryString)
{
string storeHost = GetStoreHost(useSsl);
if (storeHost.EndsWith("/"))
storeHost = storeHost.Substring(0, storeHost.Length - 1);
url = storeHost + _httpContext.Request.RawUrl;
}
else
{
#if DEBUG
var uri = _httpContext.Request.Url;
#else
//Since appharbor changes port number due to multiple servers, we need to ensure port = 80 as in AppHarborRequesWrapper.cs
var uri = new UriBuilder
{
Scheme = _httpContext.Request.Url.Scheme,
Host = _httpContext.Request.Url.Host,
Port = 80,
Path = _httpContext.Request.Url.AbsolutePath,
Fragment = _httpContext.Request.Url.Fragment,
Query = _httpContext.Request.Url.Query.Replace("?", "")
}.Uri;
#endif
url = uri.GetLeftPart(UriPartial.Path);
}
url = url.ToLowerInvariant();
return url;
}
So what we did is simply add files from https://gist.github.com/1158264 into Nop.Core\AppHarbor
and modified base controllers:
nopcommerce\Presentation\Nop.Web\Controllers\BaseNopController.cs
public class BaseNopController : Controller
{
protected override void Initialize(RequestContext requestContext)
{
//Source: https://gist.github.com/1158264
base.Initialize(new RequestContext(new AppHarborHttpContextWrapper(System.Web.HttpContext.Current),
requestContext.RouteData));
}
//Same file from here downwards...
}
nopcommerce\Presentation\Nop.Web.Admin\Controllers\BaseNopController.cs
public class BaseNopController : Controller
{
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
//set work context to admin mode
EngineContext.Current.Resolve<IWorkContext>().IsAdmin = true;
//Source: https://gist.github.com/1158264
base.Initialize(new RequestContext(new AppHarborHttpContextWrapper(System.Web.HttpContext.Current), requestContext.RouteData));
//base.Initialize(requestContext);
}
//Same file from here downwards...
}
Enable the Directory Browsing feature in IIS Express
Note This method is for the web developers who experience the issue when they use IIS Express.
To do this, follow these steps:
Open a command prompt, and then go to the IIS Express folder on your computer. For example, go to the following folder in a command prompt:
C:\Program Files\IIS Express
Type the following command, and then press Enter:
appcmd set config /section:directoryBrowse /enabled:true
refrence :https://support.microsoft.com/en-us/kb/942062
Actually what I needed was a step by step guide but anyway..
I have to show some rdl reports in a web-site using the ASP.NET report vievew and do all the necessary configurations for the Reporting Services. The users of the page should not deal with ANY authorization.
Here is my code for the report viewer:
rprtView.ServerReport.ReportServerCredentials = new ReportServerCredentials();
rprtView.ProcessingMode = Microsoft.Reporting.WebForms.ProcessingMode.Remote;
rprtView.ServerReport.ReportServerUrl = new Uri(#"http://mydomain/reports");
rprtView.ServerReport.ReportPath = #"/MyReports/PurchaseOrder";
rprtView.ShowParameterPrompts = false;
ReportParameter[] parameters = new ReportParameter[1];
parameters[0] = new ReportParameter();
parameters[0].Name = "OrderNumber";
parameters[0].Values.Add(orderNumber);
rprtView.ServerReport.SetParameters(parameters);
rprtView.ServerReport.Refresh();
Here is my overload for IReportServerCredentials
public class ReportServerCredentials : IReportServerCredentials
{
public bool GetFormsCredentials(out Cookie authCookie, out string userName, out string password, out string authority)
{
authCookie = null;
userName = password = authority = null;
return false;
}
public WindowsIdentity ImpersonationUser
{
get { return null; }
}
public ICredentials NetworkCredentials
{
get { return new NetworkCredential("myUserName", "myPassword"); }
}
}
I am able to login to "http://mydomain/reports", the default web site of the SSRS, using "myUserName" and "myPassword" (I am not sure if this is related). Still I am getting MissingEndPoint exception at SetParameters() method above. It says:
"The attempt to connect to the report server failed. Check your connection information and that the report server is a compatible version."
I am also responsible for configuring the Reporting Services for the necessary configuration for this scenario and I have heard that this issue is related to the config files in SSRS but I have no idea what to write in them. Any help is much appreciated!
The string provided for rprtView.ServerReport.ReportServerUrl should be for the Report Server service, not the Report Manager application.
Change this:
rprtView.ServerReport.ReportServerUrl = new Uri(#"http://mydomain/reports");
to this:
rprtView.ServerReport.ReportServerUrl = new Uri(#"http://mydomain/reportserver");
This page has some high-level info on the Report Manager interface, Report Server web service, and how they relate.
Here's my Windows/.NET security stack:
A Windows Service running as LocalSystem on a Windows Server 2003 box.
A .NET 3.5 Website running on the same box, under "default" production server IIS settings (so probably as NETWORKSERVICE user?)
On my default VS2008 DEV environment I have this one method, which gets called from the ASP.NET app, which works fine:
private static void StopStartReminderService() {
ServiceController svcController = new ServiceController("eTimeSheetReminderService");
if (svcController != null) {
try {
svcController.Stop();
svcController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10));
svcController.Start();
} catch (Exception ex) {
General.ErrorHandling.LogError(ex);
}
}
}
When I run this on the production server, I get the following error from the ServiceController:
Source: System.ServiceProcess ->
System.ServiceProcess.ServiceController -> IntPtr
GetServiceHandle(Int32) -> System.InvalidOperationException Message:
Cannot open eTimeSheetReminderService service on computer '.'.
Why is this happening, and how do I fix it?
EDIT:
The answer is below, mostly in comments, but to clarify:
The issue was Security related, and occurred because the NETWORKSERVICE account did not have sufficient rights to Start/Stop a service
I created a Local User Account, and added it to the PowerUsers Group (this group has almost admin rights)
I don't want my whole Web App to impersonate that user all the time, so I impersonate only in the method where I manipulate the service. I do this by using the following resources to help me do it in code:
MS KB article and this, just to get a better understanding
NOTE: I don't impersonate via the web.config, I do it in code. See the MS KB Article above.
To give IIS permission to start/stop a particular service:
Download and install Subinacl.exe. (Be sure to get the latest version! Earlier versions distributed in some resource kits don't work!)
Issue a command similar to: subinacl /service {yourServiceName} /grant=IIS_WPG=F
This grants full service control rights for that particular service to the built-in IIS_WPG group. (This works for IIS6 / Win2k3.) YMMV for newer versions of IIS.)
Try adding this to your Web.Config.
<identity impersonate="true"/>
This was a good question that intrigued me as well...
So here is what I did to solve this problem:
Step 1: Create a Windows user account on the local machine with minimal rights.
Step 2: Give this user rights to start and stop the service via subinacl.exe
i.e. subinacl.exe /service WindowsServiceName /GRANT=PCNAME\TestUser=STOE
Dowload from : http://www.microsoft.com/en-za/download/details.aspx?id=23510
Step 3: Use Impersonation to impersonate the use created in Step 1 to start and stop the Service
public const int LOGON32_PROVIDER_DEFAULT = 0;
WindowsImpersonationContext _impersonationContext;
[DllImport("advapi32.dll")]
// ReSharper disable once MemberCanBePrivate.Global
public static extern int LogonUserA(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
// ReSharper disable once MemberCanBePrivate.Global
public static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
// ReSharper disable once MemberCanBePrivate.Global
public static extern bool RevertToSelf();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
// ReSharper disable once MemberCanBePrivate.Global
public static extern bool CloseHandle(IntPtr handle);
private bool _impersonate;
public bool ImpersonateValidUser(String userName, String domain, String password)
{
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (RevertToSelf())
{
if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
var tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
_impersonationContext = tempWindowsIdentity.Impersonate();
if (_impersonationContext != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
_impersonate = true;
return true;
}
}
}
}
if (token != IntPtr.Zero)
CloseHandle(token);
if (tokenDuplicate != IntPtr.Zero)
CloseHandle(tokenDuplicate);
_impersonate = false;
return false;
}
#region Implementation of IDisposable
#endregion
#region Implementation of IDisposable
private void Dispose(bool dispose)
{
if (dispose)
{
if (_impersonate)
_impersonationContext.Undo();
_impersonationContext.Dispose();
}
}
public void Dispose()
{
Dispose(true);
}
#endregion
public static void StartStopService(bool startService, string serviceName)
{
using (var impersonateClass = new Impersonation())
{
impersonateClass.ImpersonateValidUser(Settings.Default.LocalUsername, Settings.Default.Domain, Settings.Default.Password);
using (var sc = new ServiceController(serviceName))
{
if (startService)
sc.Start();
else if (sc.CanStop)
sc.Stop();
}
}
}
Update for IIS 8 (and maybe some slightly earlier versions)
The usergroup IIS_WPG does not exist anymore. It has changed to IIS_IUSRS.
Also, to start stop a service it is not neccesary to give full permissions (F). Permissions to start, stop and pause a service (TOP) should be enough. As such the command should be:
subinacl /service {yourServiceName} /grant=IIS_IUSRS=TOP
Note that you need to point the command prompt (preferably elevated to run as administrator) to C:\Windows\System32 Folder before running this command.
Also make sure that you have copied the subinacl.exe file to C:\Windows\System32 from the installation directory if there is an error.
Just a hunch, but it does not appear to me the error is necessarily related to security. Did you give the service the same name on the production server?
If your web application has the database and windows service can access it, you can just use the flag in the DB to restart the service. In the service, you can read this flag and restart if not busy etc. Only in case if you can modify the code of the service.
If it's third party service you can create your own windows service and use database config to control (restart) services. It's the safe way and gives you much more flexibility and security.