Pop

32.Aplicaciones web.Página de Login (1).Curso de C# con Visual Studio 2017.

32- . Aplicaciones web.Página de Login (1)

   - En este capítulo del curso de programación en c# con visual studio 2017 vamos a ver como crear un página de Login que valida contra una base de datos SQL Server. En el caso, que el usuario que esta intentado entrar en el sitio web exista en el sistema le dejara ingresar, si no lanzaremos un error de autenticación.

- Para validar que el usuario existe, buscamos en la base datos via procedimiento almacenado el valor que usuario introduza en el campo usuario (en nuestro caso el email). Si encontramos el email en nuestro sistema devolvemos a la aplicación el email y la password cifrada asociada que tiene, si no le encontramos lanzamos un error que mostraremos por pantalla.
- Una vez que tenemos la password y el usuario comprobamos que la password almacenada coincide con la que usuario introduzca. En el video siguiente lo veréis con más claridad:



* Os dejo el código del ejempo visto en el video:

  • Página de default.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="GestionVarios.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table width="200" border="0" cellspacing="0" cellpadding="0">
                          <tr>
                            <td height="24">
                              <table width="200" border="0" cellspacing="0" cellpadding="0">
                                <tr>
                                  <td width="75" align="right" valign="top">
                                    Usuario:&nbsp;&nbsp;&nbsp;&nbsp;
                                  </td>
                                  <td width="125">
                                    <asp:TextBox ID="txtUsuario" runat="server" ></asp:TextBox>
                                    <asp:RegularExpressionValidator ID="mvalUsuarioValida" runat="server"
                                          ErrorMessage="Usuario incorrecto" ControlToValidate="txtUsuario"
                                          ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" Display="Dynamic" ForeColor="Red" ></asp:RegularExpressionValidator>
                                    <asp:RequiredFieldValidator ID="mvalRequiereUsuario" runat="server" ErrorMessage="<br>Indique el usuario" ControlToValidate="txtUsuario" Display="Dynamic" ForeColor="Red"></asp:RequiredFieldValidator>
                                  </td>
                                </tr>
                              </table>
                            </td>
                          </tr>
                          <tr>
                            <td height="24">
                              <table width="200" border="0" cellspacing="0" cellpadding="0">
                                <tr>
                                  <td width="75" align="right" valign="top" class="texto_news">
                                    Password:&nbsp;
                                  </td>
                                  <td width="125">
                                    <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" ></asp:TextBox>
                                    <asp:RegularExpressionValidator ID="mvalPasswordValida" runat="server" ErrorMessage="<br>Contraseña incorrecta" ControlToValidate="txtPassword" ValidationExpression="\w+.{5,}" Display="Dynamic" ForeColor="Red"></asp:RegularExpressionValidator>
                                    <asp:RequiredFieldValidator ID="mvalRequiereContraseña" runat="server" ErrorMessage="<br>Indique la contraseña" ControlToValidate="txtPassword" Display="Dynamic" ForeColor="Red"></asp:RequiredFieldValidator>
                                  </td>
                                </tr>
                              </table>
                            </td>
                          </tr>
                          <tr>
                            <td align="right" valign="middle">
                                <asp:Button runat="server" Text="Inicio sesion" OnClick="Unnamed1_Click" />
                                <br />
                                <asp:Label runat="server" ID="lblError"></asp:Label>
                            </td>
                          </tr>
                          
                          <tr>
                            <td>
                              <table width="200" border="0" cellspacing="0" cellpadding="0">
                                 <tr>
                                  <td height="22" align="left"><a href="~/AltaUsuario.aspx" runat="server"  target="_blank"><b>Darse de alta </b></a></td>
                                </tr>
                                <tr>
                                  <td align="left">
                                    <asp:LinkButton ID="lnkOlvido" runat="server"
                                     CausesValidation="false" OnClick="lnkOlvido_Click"><b>¿Olvidó su password?</b></asp:LinkButton>
                                  </td>
                                </tr>
                              </table>
                            </td>
                          </tr>
                        </table>
        </div>
    </form>
</body>
</html>

  • Página de default.aspx.cs:
 using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace GestionVarios
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Unnamed1_Click(object sender, EventArgs e)
        {
          
            SqlConnection conexion = new SqlConnection(ConfigurationManager.ConnectionStrings["EmpresaConnectionString"].ConnectionString);
            string usuarioGuardadaBaseDatos  = String.Empty;
            byte[] passGuardadaBaseDatos = null;
            try
            {
                conexion.Open();
                SqlCommand com = conexion.CreateCommand();
                com.CommandType = System.Data.CommandType.StoredProcedure;
                com.CommandText = "dbo.ValidarUsuario";
               com.Parameters.Add("@email", SqlDbType.VarChar, 255).Value = txtUsuario.Text;

                SqlDataReader reader = com.ExecuteReader();

                if (reader.Read())
                {
                    usuarioGuardadaBaseDatos = reader["email"].ToString();
                    if(usuarioGuardadaBaseDatos!=String.Empty)
                    passGuardadaBaseDatos = (byte[])reader["pass"];
                 
                }
                else
                    throw new Exception("Usuario o pass incorrecto.");

                if(usuarioGuardadaBaseDatos!=String.Empty && ValidarDatos(usuarioGuardadaBaseDatos, passGuardadaBaseDatos))
                {
                    Response.Redirect("~/Pedidos.aspx");
                    Response.End();
               }
                else
                    throw new Exception("Usuario o pass incorrecto.");

            }
            catch (Exception ex)
            {
                lblError.Text = "Se produjo un error iniciando sesion:" + ex.Message;
                lblError.ForeColor = Color.Red;
            
            }
            finally
            {
                if (conexion != null && conexion.State == System.Data.ConnectionState.Open)
                    conexion.Close();

                conexion.Dispose();
            }

         
        }

        private Boolean ValidarDatos(string usuario, byte[] pass)
        {
            Boolean usuarioCorrecto = false;
            string passDescifrada = String.Empty;

            String miclave = ConfigurationManager.AppSettings["clave"];
            byte[] claveCifrado = System.Text.Encoding.ASCII.GetBytes(miclave);
            Cifrado c = new Cifrado(claveCifrado);
            passDescifrada = c.descifrar(pass);

     
            if (passDescifrada == txtPassword.Text && txtUsuario.Text == usuario)
                usuarioCorrecto = true;

            return usuarioCorrecto;
        }

        protected void lnkOlvido_Click(object sender, EventArgs e)
        {

        }

  
    }
}

  • Clase cifrado.cs:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Web;

namespace GestionVarios
{
    public class Cifrado
    {
        Aes miAes = null;

        public Cifrado(byte[] clave)
        {
            miAes = Aes.Create();
            miAes.Key = clave;
            miAes.IV = clave;
        }

        public byte[] cifrar(string original)
        {
            byte[] encrypted = EncriptarStringToBytesAes(original, miAes.Key, miAes.IV);
            return encrypted;
        }

        public string descifrar(byte[] encrypted)
        {
            string roundtrip = DesencriptarStringFromBytesAes(encrypted, miAes.Key, miAes.IV);
            return roundtrip;

        }

        private byte[] EncriptarStringToBytesAes(string cadena, byte[] clave, byte[] IV)
        {

            if (cadena == null || cadena.Length <= 0)
                throw new ArgumentNullException("plainText");

            if (clave == null || clave.Length <= 0)
                throw new ArgumentNullException("Key");

            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");

            byte[] encrypted;

           using (Aes aesAlg = Aes.Create())
           {
                aesAlg.Key = clave;
                aesAlg.IV = IV;
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(cadena);

                        }
                        encrypted = msEncrypt.ToArray();
                    }

                }

            }
            return encrypted;
        }

        private string DesencriptarStringFromBytesAes(byte[] textoCifrado, byte[] clave, byte[] IV)
        {
            if (textoCifrado == null || textoCifrado.Length <= 0)
                throw new ArgumentNullException("cipherText");
            if (clave == null || clave.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");
            string plaintext = null;

            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = clave;
                aesAlg.IV = IV;

                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
             
                using (MemoryStream msDecrypt = new MemoryStream(textoCifrado))
                {

                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                          plaintext = srDecrypt.ReadToEnd();

                        }
                    }

                }
            }
            return plaintext;
        }

    }
} 

No hay comentarios:

Publicar un comentario

Curso .NET Core en C# - 34.Creamos nuestro propio log

34.Creamos nuestro propio log Hola a todos. En este curso, analizaremos todos los conceptos básicos, intermedios y avanzados de  ASP.NET...