Cambiar y Proteger la cadena de conexion del app.config


La cadena de conexión es un dato sensible, por tal razón es necesario protegerla, de aquellos usuarios emprendedores o alguno que te odie. Para ciertas aplicaciones se necesita modificar la cadena de conexión en tiempo de ejecución.

En siguiente formulario permite leer, cambiar en tiempo de ejecución y proteger  la cadena de conexión.

image

Agrego a mi proyecto el archivo app.config:

   1: <?xml version="1.0" encoding="utf-8" ?>
   2: <configuration>
   3:  
   4:   <connectionStrings>
   5:     <add  name="cnxVentasDemo"
   6:           connectionString="Server=(local)\SQL2008;DataBase=VentasDemo;Integrated Security=SSPI;"
   7:           providerName="System.Data.SqlClient" />
   8:   </connectionStrings>
   9:  
  10: </configuration>

Agrego la referencia a System.Configuration y el respectivo Imports:

   1: Imports System.Configuration
   2:  
   3: Public Class Form1
   4:  
   5:   
   6: End Class

El siguiente código permite la lectura de la cadena de conexión:

   1: Private Sub btnObtieneCNX_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnObtieneCNX.Click
   2:         Dim MiCnx As ConnectionStringSettings
   3:  
   4:         MiCnx = ConfigurationManager.ConnectionStrings("CNXVentasDemo")
   5:  
   6:         If Not MiCnx Is Nothing Then
   7:             txtCadenaConexion.Text = MiCnx.ConnectionString
   8:         End If
   9:     End Sub

Para proteger la cadena de conexión, se abrirá el app.config, luego la sección connectionsString y finalmente preguntar si la sección esta protegida o no.

   1: Private Sub btnProtegerCNX_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnProtegerCNX.Click
   2:  
   3:        Try
   4:            'Se abre el app.config para recuperar la seccion ConnectionStrings
   5:            Dim MiAppConfig As Configuration = _
   6:            ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath)
   7:  
   8:            'Se recupera la seccion ConnectionStrings
   9:            Dim MiSeccion As ConnectionStringsSection = _
  10:            DirectCast(MiAppConfig.GetSection("connectionStrings"),  ConnectionStringsSection)
  11:  
  12:            'Se protege la seccion, caso contrario se desprotege
  13:            If MiSeccion.SectionInformation.IsProtected Then
  14:                MiSeccion.SectionInformation.UnprotectSection()
  15:            Else
  16:  
  17:                MiSeccion.SectionInformation.ProtectSection("DataProtectionConfigurationProvider")
  18:            End If
  19:  
  20:            'Se guarda los cambios
  21:            MiAppConfig.Save()
  22:  
  23:            If MiSeccion.SectionInformation.IsProtected Then
  24:                MessageBox.Show("Cadena de Conexion Protegida")
  25:            Else
  26:                MessageBox.Show("No esta protegida")
  27:            End If
  28:  
  29:        Catch ex As Exception
  30:            MessageBox.Show(ex.Message)
  31:        End Try
  32:    End Sub

La aplicación no necesita descifrar la sección connectionString, este paso es realizando automáticamente.

Para cambiar la cadena de conexión en tiempo de ejecución tenemos:

   1: Private Sub btnCambiarCNX_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCambiarCNX.Click
   2:        'Se abre el app.config para recuperar la seccion ConnectionStrings
   3:        Dim MiAppConfig As Configuration = _
   4:        ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath)
   5:  
   6:        'Se recupera la seccion ConnectionStrings
   7:        Dim MiSeccion As ConnectionStringsSection = _
   8:        DirectCast(MiAppConfig.GetSection("connectionStrings"), ConnectionStringsSection)
   9:  
  10:        'Se establece el nuevo valor de la cadena de conexion
  11:        MiSeccion.ConnectionStrings("CNXVentasDemo").ConnectionString = txtCadenaConexion.Text
  12:  
  13:        'Se guarda los cambios
  14:        MiAppConfig.Save()
  15:  
  16:        MessageBox.Show("Se guardo la cadena de conexion. Cierre la aplicación ó Reinicio la aplicación")
  17:  
  18:        'Se reinicia la aplicación
  19:        Application.Restart()
  20:  
  21:    End Sub

Es necesario reiniciar la aplicación o cerrarla, ya que la carga inicial se encuentra en la cache de la aplicación y por este motivo no se ve el cambio.

Saludos :)

Fuente: MSDN http://msdn.microsoft.com/es-es/library/ms243192(VS.80).aspx

2 comentarios:

Anónimo dijo...

Perfecta solucion yo he visto algo parecido en

http://www.syswoody.com/programacion/proteger-la-contrasena-del-appconfig-vshostexeconfig-o-archivo-execonfig

Alonso Morales Salazar on 16 de enero de 2011 08:29 dijo...

Excelente recurso.

 

Copyright 2008 All Rights Reserved Revolution Two Church theme by Brian Gardner Converted into Blogger Template by Bloganol dot com