1

I have a login-page where users can log in. When they logging in with correctly details they are sent to an main admin-page. If they cant log in they are staying on the login-page. What I want to do is, if a random user, type in the URL for an admin-page when they are not logged in they are redirecting to the login-page.

I have understood that I have to do it in the masterpage or webconfig!?! I have a main admin-page and some other admin-pages.

Any tips?

I tried to insert this into my webconfig:

<authentication mode="Forms">
    <forms loginUrl="InnUtlogging.aspx" timeout="2880"/>
  </authentication>

here is my code for the "login"-button (on the login-page);

protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True");
        con.Open();
        SqlCommand cmd = new SqlCommand("select * FROM Ansatt WHERE epost='" + brukernavn.Text + "' and passord='" + passord.Text + "'");
        cmd.Connection = con;
        int OBJ = Convert.ToInt32(cmd.ExecuteScalar());

        if (OBJ > 0)

            {
            Session["name"] = brukernavn.Text;
            Response.Redirect("KunstnerAdmin.aspx");
        }
        else
            {
                melding.Text = "Feil brukernavn/passord";
            }
        if (brukernavn.Text == "")
        {
            melding.Text = "Du må fylle inn brukernavn";

        }
        if (passord.Text == "")
        {
            melding.Text = "Du må fylle inn passord";
        }
        }

The code on the "login"-page works for that page, but I actually want to check if user is logged in in the master-page. Is there something I can do in the masterpage to activate the forms authentication?

  • 1
    Rather than `Response.Redirect`, I think you should call [`FormsAuthentication.RedirectFromLoginPage`](https://msdn.microsoft.com/en-us/library/ka5ffkce(v=vs.110).aspx) – stuartd Mar 30 '17 at 13:27
  • But how should i code it in the master.cs? I dont have any code for checking!?! the code above is in my login.aspx.cs file. And that doesn't help me if a user tries to type in an admin-url without going through the login page. – Yngvild Dahl Brenna Mar 30 '17 at 13:29
  • OK, it's been a very long time, but as I remember - un-authenticated users are redirected to the login page by the framework. If they then authenticate successfully, `FormsAuthentication.RedirectFromLoginPage(…)` then sets the authentication cookie, and redirects them back to the page they came from (by default) as an authenticated user. I don't see where the master page comes into it at all? – stuartd Mar 30 '17 at 13:41

2 Answers2

5

Your code is missing a lot of pieces for FormsAuthentication.

First of all, the code is prone to SQL Injection attack. You want to consider using Parameterized Query.

Sign-In method

protected void Button1_Click(object sender, EventArgs e)
{
    // After validation successful 
    bool rememberMe = false; // Make it false for now
    FormsAuthentication.RedirectFromLoginPage(brukernavn.Text, rememberMe);
}

Global.asax.cs

You need this in order to retrieve the username from cookie, and save it in IPrincipal Object.

public class Global : HttpApplication
{
    private void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        HttpCookie decryptedCookie =
            Context.Request.Cookies[FormsAuthentication.FormsCookieName];

        FormsAuthenticationTicket ticket =
            FormsAuthentication.Decrypt(decryptedCookie.Value);

        var identity = new GenericIdentity(ticket.Name);
        var principal = new GenericPrincipal(identity, null);

        HttpContext.Current.User = principal;
        Thread.CurrentPrincipal = HttpContext.Current.User;
    }
}

web.config

<authentication mode="Forms">
   <forms loginUrl="~/InnUtlogging.aspx" />
</authentication>

Usage

protected void Page_Load(object sender, EventArgs e)
{
    if (User.Identity.IsAuthenticated)
    {
        string username = User.Identity.Name;
    }
}
Community
  • 1
  • 1
Win
  • 61,100
  • 13
  • 102
  • 181
0

Here is how you check if the user authenticated.

HttpContext.Current.User.Identity.IsAuthenticated
nPcomp
  • 8,637
  • 2
  • 54
  • 49