Having trouble with authentication in asp.net web application

自古美人都是妖i 提交于 2019-12-06 11:32:32

this is my first time trying to do authentication so I'm not totally sure how to get the return value by using the breakpoint.

You want to test with hard-coded username and password before connecting to SQL server.

protected void cmdLogin_ServerClick(object sender, System.EventArgs e)
{
    if (String.Equals(txtUserName.Value, "johndoe", 
        StringComparison.InvariantCultureIgnoreCase) &&
        String.Equals(txtUserPass.Value, "123456", 
        StringComparison.InvariantCultureIgnoreCase))
    {
        var roles = new[] {"Administrators"};

        var ticket = new FormsAuthenticationTicket(1, 
            txtUserName.Value,
            DateTime.Now,
            DateTime.Now.AddMinutes(30), 
            chkPersistCookie.Checked,
            string.Join(",", roles),
            FormsAuthentication.FormsCookiePath);

        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, 
            FormsAuthentication.Encrypt(ticket));

        if (chkPersistCookie.Checked)
            cookie.Expires = ticket.Expiration;

        Response.Cookies.Add(cookie);

        string returnUrl = Request["ReturnUrl"];
        if (returnUrl == null)
            returnUrl = "default.aspx";
        Response.Redirect(returnUrl, true);
    }
    else
        Response.Redirect("1.0.0.0_LoginScreen.aspx", true);
}

How to create Principal Object

When an authenticated user is requested a page, you need to retrieve auth ticket from cookie, and create a Principal object.

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

        if (decryptedCookie != null)
        {
            FormsAuthenticationTicket ticket =
                FormsAuthentication.Decrypt(decryptedCookie.Value);

            string[] roles = ticket.UserData.Split(new[] {","}, 
                 StringSplitOptions.RemoveEmptyEntries);

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

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

Usage

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {    
        if (User.Identity.IsAuthenticated)
        {
            string username = User.Identity.Name;

            bool isAdministrator = User.IsInRole("Administrators");
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!