I have .NET Framework application where I try to read data from AWS parameter store using AmazonSimpleSystemsManagementClient on my local environment. Besides I have credentials generated by AWS CLI and located in
Users/MyUser/.aws
folder. When I try to connect to the parameter store from CMD using the creds it works fine. Though the AmazonSimpleSystemsManagementClient in the application with default constructor, it throws exception "Unable to get IAM security credentials from EC2 Instance Metadata Service." When I tried to pass BasicAWSParameters to the client with hardcoded working keys I got another exception "The security token included in the request is invalid".
Also I tried installing EC2Config, initializing AWS SDK Store from Visual Studio AWS Toolkit. Though it didn't change the game.
I would want to avoid using environment variables or hardcoding the keys since keys are generated and valid only 1 hour. Then I should regenerate so copying them somewhere every time is not convenient for me.
Please advice how to resolve the issue.
Some code
_client = new AmazonSimpleSystemsManagementClient()
public string GetValue(string key)
{
if (_client == null)
return null;
var request = new GetParameterRequest
{
Name = $"{_baseParameterPath}/{key}",
WithDecryption = true,
};
try
{
var response = _client.GetParameterAsync(request).Result;
return response.Parameter.Value;
}
catch (Exception exc)
{
return null;
}
}
credentials file looks as following (I removed key values not to expose):
[default]
aws_access_key_id= KEY VALUE
aws_secret_access_key= KEY VALUE
aws_session_token= KEY VALUE
[MyProfile]
aws_access_key_id= KEY VALUE
aws_secret_access_key= KEY VALUE
aws_session_token= KEY VALUE
As long as you have your creds in .aws/credentials, you can create the Service client and the creds will be located and used. No need to create a BasicAWSParameters object.
Creds in a file named credentials:
[default]
aws_access_key_id=Axxxxxxxxxxxxxxxxxxxxxxxxxxx
aws_secret_access_key=/zxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
This .NET code works.
using System;
using System.Threading.Tasks;
using Amazon.SimpleSystemsManagement;
using Amazon.SimpleSystemsManagement.Model;
namespace ConsoleApp1 {
class Program {
static async Task Main(string[] args) {
var client = new AmazonSimpleSystemsManagementClient();
var request = new GetParameterRequest()
{
Name = "RDSConnection"
};
var response = client.GetParameterAsync(request).GetAwaiter().GetResult();
Console.WriteLine("Parameter value is " + response.Parameter.Value);
}
}
}
I'm wondering if there is a way I can setup a .net mvc app the same way a .net core app can be setup with Key Vault.
https://learn.microsoft.com/en-us/aspnet/core/security/key-vault-configuration?view=aspnetcore-2.2#secret-storage-in-the-development-environment
I want to be able to pull secrets in my local development environment without provisioning an Azure Key Vault.
In a .net core app I was able to follow the above link and get everything working.
// ran this command in powershell
dotnet user-secrets set "db-connection-string" "db-connection-string-value"
Setup the key vault with an empty endpoint in Program.cs (this is just for testing).
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((ctx, builder) =>
{
var keyVaultEndpoint = GetKeyVaultEndpoint();
if (!string.IsNullOrEmpty(keyVaultEndpoint))
{
var azureServiceTokenProvider = new AzureServiceTokenProvider();
var keyVaultClient = new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback(
azureServiceTokenProvider.KeyVaultTokenCallback));
builder.AddAzureKeyVault(
keyVaultEndpoint, keyVaultClient, new DefaultKeyVaultSecretManager());
}
}
).UseStartup<Startup>()
.Build();
private static string GetKeyVaultEndpoint() => "";
And I am able to access my secret locally using the below code.
public void OnGet()
{
Message = "My key val = " + _configuration["db-connection-string"];
}
In my asp.net app I am able to pull secrets from an Azure Key Vault. I just don't want to have to do that when developing locally since each developer could have a slightly different connection string to their local database, and requiring them to use a Key Vault in Azure is going to be annoying and cause frustration. Maybe we shouldn't use Key Vault for "legacy" applications. Any help is appreciated.
This seems similar to our development environment.
We wanted developers to use some values from the key vault, but to be able to override particular values for their local environment. (particularly the database connection string).
In the ConfigureAppConfiguration method you can register multiple configuration providers. If two configuration providers write to the same configuration key, the last registered provider gets precedence.
Knowing this, you can have a local file appSettings.json, which defines the database connection string:
{
"db-connection-string": "Data Source = DEVELOPMENT_PC;Initial Catalog=MyLocalDatabase;Integrated Security=True"
}
Then register this provider after you have registered the key vault provider.
.ConfigureAppConfiguration((ctx, builder) =>
{
var keyVaultEndpoint = GetKeyVaultEndpoint();
if (!string.IsNullOrEmpty(keyVaultEndpoint))
{
var azureServiceTokenProvider = new AzureServiceTokenProvider();
var keyVaultClient = new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback(
azureServiceTokenProvider.KeyVaultTokenCallback
)
);
builder.AddAzureKeyVault(
keyVaultEndpoint,
keyVaultClient,
new DefaultKeyVaultSecretManager()
);
}
var appSettingsFilePath = GetJsonAppSettingsFile(); // Hardcoded, or add some other configuratin logic
if (!string.IsNullOrEmpty(appSettingsFilePath))
{
builder.AddJsonFile(appSettingsFilePath);
}
}
Obviously, the production environment will have an empty or non-existent appSettings.json file, and all values will be derived from the key store. Or alternatively, you use the appSettings.json file in your production environment, but just for configuration values that do not contain secrets.
We are deploying a full-framework (.Net 4.5.1) website to an IIS server.
We are intermittently experiencing the error:
Application Error: System.AggregateException: One or more errors occurred. ---> System.Exception: SelectAllTOCBasedOnRole failed to execute. ---> System.InvalidOperationException: The .Net Framework Data Providers require Microsoft Data Access Components(MDAC). Please install Microsoft Data Access Components(MDAC) version 2.6 or later. ---> System.Runtime.InteropServices.COMException: Retrieving the COM class factory for component with CLSID {2206CDB2-19C1-11D1-89E0-00C04FD7A829} failed due to the following error: 800703fa Illegal operation attempted on a registry key that has been marked for deletion. (Exception from HRESULT: 0x800703FA).
The site is accessing a DB2 database.
MDAC 2.8.1 is installed on the server. Microsoft OLE DB Provider for DB2 Version 5.0 is also installed on all machines running the site.
If we restart the application pool the error is resolved for a while. The error will then, randomly, start again and continue until the app pool is restarted again.
The same web app is on another server that doesn't seem to exhibit this issue though I cannot see any actual differences between the servers and what components they have installed.
The piece of code that is connecting to the DB2 instance is below. Maybe there is something funky in this..?
public async Task<IList<WebTOC>> GetAllTOCAsync(string countryCode, string languageCode, string employeeNumber, string tocIdentifier)
{
IList<WebTOC> results = new List<WebTOC>();
using (OleDbConnection connection = new OleDbConnection(_connectionString))
{
// Parameter order matters with OLEDBCommands
try
{
using (OleDbCommand command = connection.CreateCommand())
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
command.CommandText = _selectAllTOCCommand;
command.Parameters.AddWithValue("?", $"{tocIdentifier}%");
command.Parameters.AddWithValue("?", countryCode);
command.Parameters.AddWithValue("?", languageCode);
command.Parameters.AddWithValue("?", employeeNumber);
command.Parameters.AddWithValue("?", DateTime.Now.ToString("yyyy-MM-dd"));
LogHelper.Log($"Prepare DB2 Command selectAllToCCommand", level: LogHelper.LogLevel.Debug);
//// FAILS HERE WHEN ATTEMPING TO OPEN THE CONNECTION ////
connection.Open();
try
{
using (INullSafeDataReader dataReader = new NullSafeDataReader(await command.ExecuteReaderAsync()))
try
{
results = dataReader.MapToList<WebTOC>(true);
}
finally
{
dataReader.Close();
}
}
catch (Exception exDR)
{
LogHelper.Log($"Failed to read data from DB2", level: LogHelper.LogLevel.Error);
throw new Exception("Failed to read data from database.", exDR);
}
}
}
catch (Exception ex)
{
/// HITS THIS CATCH ///
LogHelper.Log($"SelectAllTOCBasedOnRole failed to execute", level: LogHelper.LogLevel.Error);
throw new Exception("SelectAllTOCBasedOnRole failed to execute.", ex);
}
finally
{
if (connection.State != System.Data.ConnectionState.Closed)
connection.Close();
connection.Dispose();
}
}
return results;
}
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 have written a java sftp application based on Jcraft.jsch running on solaris. Each time the application connects to remote host a duplicate entry is done in known_hosts file. Any help on how to stop this. The connection code is as below:
public boolean connect(Properties props) throws JSchException {
FileSystemOptions fso = new FileSystemOptions();
try {
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(fso, "no");
session = SftpClientFactory.createConnection(host, port, login.toCharArray(), password.toCharArray(), fso);
Channel channel = session.openChannel("sftp");
channel.connect();
command = (ChannelSftp) channel;
} catch (FileSystemException e) { ...
Thanks