Authentication recommendations for SQL files

I managed to use SQL Filestream locally, but when I try to upload files to a remote SQL server that uses SQL authentication, I get an Access Denied exception. Apparently, SQL Filestream only works with Windows authentication (Integrated Security = true), and not with the SQL authentication that we currently have.

Nobody uses Windows authentication in a production environment, so I just want to know how to overcome this limitation. What is the best practice?

    public static void AddItem(RepositoryFile repository, byte[] data)
{
    using (var scope = new TransactionScope())
    {
        using (var db = new MyEntities()) // DBContext
        {
            db.RepositoryTable.AddObject(repository);
            db.SaveChanges();
        }

        using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
        using (var cmd = new SqlCommand(string.Format("SELECT Data.PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT() FROM dbo.RepositoryTable WHERE ID='{0}'", repository.ID), con)) // "Data" is the column name which has the FILESTREAM. Data.PathName() gives me the local path to the file.
        {
            cmd.Connection.Open();
            using (var reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    var path = reader.GetString(0);
                    var transactionContext = reader.GetSqlBytes(1).Buffer;
                    var fileStream = new SqlFileStream(path, transactionContext, FileAccess.Write);

                    fileStream.Write(contents, 0, contents.Length); // I get the error at this line.
                    fileStream.Close();
                }
            }
        }

        scope.Complete();
    }
}
+3
source share
2 answers

You really should use integrated authentication when using FILESTREAM:

FILESTREAM SQL Server 2008

, Windows, , ​​ SQL Server , SQL Authentication, .

, FILESTREAM.

+3

, SqlFileStream. .

, . SqlFileStream SQL-, INSERT , . , "FileData" ( "guid" ) "Bytes", - :

Byte[] bytes = // assign your data here

using (SqlConnection conn = new SqlConnection(connectionString)) {
    SqlCommand insertCmd = new SqlCommand("INSERT INTO FileData (Id, Bytes) VALUES (@Id, @Bytes)", conn);

    insertCmd.CommandType = System.Data.CommandType.Text;
    insertCmd.Parameters.AddWithValue("@Id", Guid.NewGuid());
    insertCmd.Parameters.AddWithValue("@Bytes", bytes);
    insertCmd.Transaction = conn.BeginTransaction();

    try {
        insertCmd.ExecuteNonQuery();
        insertCmd.Commit();
    }
    catch (Exception e) {
        insertCmd.Transaction.Rollback();
    }
}

, SqlFileStream .

+2

Source: https://habr.com/ru/post/1780469/


All Articles