gbade_
gbade_

Reputation: 349

Session returns null in site.master page

I am trying to pass a value from an asp.net login control into an entirely different site.master page. This is my login.aspx.cs page -

    protected void LoginUser_OnAuthenticate(object sender, AuthenticateEventArgs e)
    {
        Session["username"] = LoginUser.UserName;
        Security.AuthenticateUser(LoginUser.UserName, LoginUser.Password, LoginUser.RememberMeSet);
    }

This part of the code receives values from the login.aspx page -

<asp:Login ID="LoginUser" runat="server" EnableViewState="false" RenderOuterTable="false" OnAuthenticate="LoginUser_OnAuthenticate">
    <div class="form-group">
         <label>Username</label>
         <asp:TextBox ID="UserName" runat="server" AutoCompleteType="None" CssClass="textEntry ltr-dir"></asp:TextBox>
    </div>
    <div class="form-group">
         <label>Password</label>
         <asp:TextBox ID="Password" runat="server" CssClass="passwordEntry ltr-dir" TextMode="Password"></asp:TextBox>
   </div>
</asp:Login>

This is my site.master page -

var username = Session["username"].ToString();

var settings = ConfigurationManager.ConnectionStrings["BlogEngine"].ConnectionString;
SqlConnection conn = new SqlConnection(settings);

Var username is getting a null value anytime I debug. Whereas in the login.aspx.cs page, it passes the values for the username into the session.

Please how do I resolve this?

NB: Security.AuthenticateUer() method -

public static bool AuthenticateUser(string username, string password, bool rememberMe)
    {
        string un = (username ?? string.Empty).Trim();
        //string pw = (password ?? string.Empty).Trim();

        if (!string.IsNullOrWhiteSpace(un))
        {
            var user = Membership.GetUser(un);
            string res = Convert.ToString(user);
            bool isValidated = Membership.ValidateUser(res, DEFAULT_PASSWORD);
            if (isValidated)
            {
                if (BlogConfig.SingleSignOn)
                {
                    FormsAuthentication.SetAuthCookie(un, rememberMe);
                    return true;
                }

                HttpContext context = HttpContext.Current;
                DateTime expirationDate = DateTime.Now.Add(FormsAuthentication.Timeout);

                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                    1,
                    un,
                    DateTime.Now,
                    expirationDate,
                    rememberMe,
                    $"{SecurityValidationKey}{AUTH_TKT_USERDATA_DELIMITER}{Blog.CurrentInstance.Id}",
                    FormsAuthentication.FormsCookiePath
                );

                string encryptedTicket = FormsAuthentication.Encrypt(ticket);

                // setting a custom cookie name based on the current blog instance.
                // if !rememberMe, set expires to DateTime.MinValue which makes the
                // cookie a browser-session cookie expiring when the browser is closed.
                System.Web.HttpCookie cookie = new System.Web.HttpCookie(FormsAuthCookieName, encryptedTicket);
                cookie.Expires = rememberMe ? expirationDate : DateTime.MinValue;
                cookie.HttpOnly = true;
                context.Response.Cookies.Set(cookie);

                string returnUrl = context.Request.QueryString["returnUrl"];
                Console.WriteLine("Redirect To This URL :" + returnUrl);

                // ignore Return URLs not beginning with a forward slash, such as remote sites.
                if (string.IsNullOrWhiteSpace(returnUrl) || !returnUrl.StartsWith("/"))
                    returnUrl = null;

                if (!string.IsNullOrWhiteSpace(returnUrl))
                {
                    context.Response.Redirect(returnUrl);
                }
                else
                {
                    if (IsReportUser(un))
                    {
                        var reportPage = "";
                        context.Response.Redirect(reportPage);
                    };

                     context.Response.Redirect(Utils.RelativeWebRoot); 
                }

                return true;
            }
        }
        return false;
    }

Upvotes: 1

Views: 646

Answers (1)

Win
Win

Reputation: 62290

Since you are using FormAuthentication, username is real stored inside Principle object. You could just retrieve username like this -

var username = User.Identity.Name;

Upvotes: 1

Related Questions