Solved

WebForms Asp.Net Authentication

Posted on 2014-12-17
6
101 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
  • 3
  • 2
6 Comments
 
LVL 35

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 79

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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 35

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 35

Accepted Solution

by:
Miguel Oz earned 500 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

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

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

These days, all we hear about hacktivists took down so and so websites and retrieved thousands of user’s data. One of the techniques to get unauthorized access to database is by performing SQL injection. This article is quite lengthy which gives bas…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
This video teaches users how to migrate an existing Wordpress website to a new domain.
Wufoo.com provides powerful tools for surveying targeted groups, and utilizing data from completed surveys to find trends, discover areas of demand or customer expectation, and make business decisions on products or services.

777 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