Solved

WebForms Asp.Net Authentication

Posted on 2014-12-17
6
99 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 78

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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
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

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Foreword (May 2015) This web page has appeared at Google.  It's definitely worth considering! https://www.google.com/about/careers/students/guide-to-technical-development.html How to Know You are Making a Difference at EE In August, 2013, one …
What is Node.js? Node.js is a server side scripting language much like PHP or ASP but is used to implement the complete package of HTTP webserver and application framework. The difference is that Node.js’s execution engine is asynchronous and event…
This video teaches viewers how to create their own website using cPanel and Wordpress. Tutorial walks users through how to set up their own domain name from tools like Domain Registrar, Hosting Account, and Wordpress. More specifically, the order in…
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.

708 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now