?
Solved

WebForms Asp.Net Authentication

Posted on 2014-12-17
6
Medium Priority
?
108 Views
Last Modified: 2015-02-10
Hi,
I'm pretty new developing .Net applications. I would like your advice on the authentication matter. We still don't know what practice is better for managing sessions.

Currently, we have developed webForms that validate using 'sessions ' on every page.
Second, we have developed pages that use 'Cookies'
Third and Final, we have added an "authentication mode = "forms" in the web.config file.

All of them programatically defined to last 60 minutes.
Finally, after a user clicks the signout button, the user can still get connected :(
0
Comment
Question by:José Perez
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 36

Expert Comment

by:Miguel Oz
ID: 40506379
When you logout:
Q1. Did your code clear the Session object?
Q2. Did your code call FormsAuthentication.SignOut and redirect to login page? (See sample on link provided)
0
 
LVL 82

Expert Comment

by:David Johnson, CD, MVP
ID: 40506433
in the logout procedure - clear the cookie. or set the cookie as logged out
0
 
LVL 2

Author Comment

by:José Perez
ID: 40508291
This is the code:

TheSystem FORM

using System;
using System.Data;
using System.Web;
using System.Web.Security;

namespace TheSystem.loginOn
{
    public partial class index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if ((System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
            {
                FormsAuthentication.SignOut();
                Response.Redirect("~/Leave.html", true);
            }
        }

        protected void Validate_Click(object sender, EventArgs e)
        {
            FormsAuthentication.SignOut();

            string rut = this.login.Text.Replace(";", "").Replace("--", "");
            string contraseña = this.pass.Text.Replace(";", "").Replace("--", "");

            if (LoginService.Autenticar(rut, contraseña) == true)
            {
                //Se verifica en la base de datos el UsuarioID y se almacena en la variable tblUsuario.
                DataTable tblUsuario = LoginService.prConsultaUsuario(rut, contraseña);

                //se declara y se le da el valor a la variable de sesión UsuarioID
                Session["userId"] = tblUsuario.Rows[0]["id"].ToString();
                Session["userName"] = tblUsuario.Rows[0]["name"].ToString();
                Session["userPerf"] = tblUsuario.Rows[0]["perf"].ToString();
                Session["time"] = DateTime.Now;
                Session.Timeout = 60;               
                ////Manda a la principal en caso de ser correcto el login
                ////Response.Redirect("~/");

                FormsAuthenticationTicket tkt = new FormsAuthenticationTicket(1,
                                                    Session["userName"].ToString(),
                                                    DateTime.Now,
                                                    DateTime.Now.AddMinutes(60),
                                                    false,
                                                    Session["userPerf"].ToString(),
                                                    FormsAuthentication.FormsCookiePath);

                Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(tkt)));

                string strRedirect = Request["ReturnUrl"];
                if (strRedirect == null)
                {
                    strRedirect = "~/Views/ClientCall.aspx";
                }
                Response.Redirect(strRedirect, true);
            }
            else
            {
                //Mensaje de error en caso de no ser usuario registrado
                lblMensaje.Text = "Usuario o Contraseña Incorrecto";
            }
        }
    }
}

Open in new window

WEB.CONFIG

    <authentication mode="Forms">
      <forms loginUrl="Login/default.aspx" 
             name=".TheSystem" 
             timeout="60"
             defaultUrl="default.aspx"
             protection="All"
             path="/"
             requireSSL="false"
             slidingExpiration="true"
             cookieless="UseDeviceProfile"
             domain="" 
             enableCrossAppRedirects="false">
             <credentials passwordFormat="SHA1" />
      </forms>
      <passport redirectUrl="internal" />
    </authentication>

Open in new window


GLOBAL.ASAX


        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            if (HttpContext.Current.User != null)
            {
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    if (HttpContext.Current.User.Identity is FormsIdentity)
                    {
                        FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
                        FormsAuthenticationTicket ticket = id.Ticket;

                        // Get the stored user-data, in this case, our roles
                        string userData = ticket.UserData;
                        string[] roles = userData.Split(',');
                        HttpContext.Current.User = new GenericPrincipal(id, roles);
                    }
                }
            }

Open in new window

0
Docker-Compose to Simplify Multi-Container Builds

Our veteran DevOps Author takes you through how to build a multi-container environment, managed with a single utility in order to simplify your deployments.

 
LVL 36

Expert Comment

by:Miguel Oz
ID: 40508321
Please post the logout code as well and any other event related to logout in Global.asax
0
 
LVL 2

Author Comment

by:José Perez
ID: 40517134
In page_Load it is writen the logout:
FormsAuthentication.SignOut();

Open in new window


by the way, nothing else in Global.Asax
0
 
LVL 36

Accepted Solution

by:
Miguel Oz earned 2000 total points
ID: 40518147
As per my previous post you have to clear session, sign out and redirect:
 Session.Clear();
 FormsAuthentication.SignOut();
 FormsAuthentication.RedirectToLoginPage();

Open in new window

Also please remove web.config line 17 (<passport redirectUrl="internal" />), Forms and passport Authentication are mutually exclusive.
0

Featured Post

Tutorial: Introduction to Managing a Linux Server

In this tutorial on systemd, we will explore:
-OS/Distro Adoption
-chkconfig and Other Legacy Commands
-Summary and Key Commands

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This video teaches users how to migrate an existing Wordpress website to a new domain.
Learn how to set-up custom confirmation messages to users who complete your Wufoo form. Include inputs from fields in your form, webpage redirects, and more with Wufoo’s confirmation options.
Suggested Courses

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question