Asp.net FormsAuthentication.RedirectFromLoginPage到自定义页面

Asp.net FormsAuthentication.RedirectFromLoginPage到自定义页面,asp.net,Asp.net,您好,我正在使用FormsAuthentication.RedirectFromLoginPage进行用户登录和重定向到default.aspx页面。 我希望如果一个名为admin do的用户登录时被重定向到admin.aspx页面 是否可能?如果您使用的是ASP.NET MembershipProvider登录控件,则可以在 protected void OnLoggedIn(对象发送方,事件参数e) { if(Roles.IsUserInRole(User.Identity.Name,“A

您好,我正在使用FormsAuthentication.RedirectFromLoginPage进行用户登录和重定向到default.aspx页面。 我希望如果一个名为admin do的用户登录时被重定向到admin.aspx页面


是否可能?

如果您使用的是ASP.NET MembershipProvider登录控件,则可以在


protected void OnLoggedIn(对象发送方,事件参数e)
{
if(Roles.IsUserInRole(User.Identity.Name,“Administrators”))
{
//重定向到管理页面
重定向(“~/Admin.aspx”);
}
}

别忘了在admin.aspx页面上设置一些保护,如果有人直接键入url,默认行为是重定向到最初请求的资源,因此如果用户试图访问“admin.aspx”但未通过身份验证,则会将用户发送到登录页面。成功验证后,用户将被发送到最初请求的url(admin.aspx)

用户->admin.aspx->noauth->login->“admin.aspx”

因此,与手动尝试将用户发送到某个地方不同,使用这种默认行为对您不起作用吗?默认行为实际上是“健壮的”(它可以是“admin2.aspx”、“admin3.aspx”等等……您可以拥有任意数量的“受保护的资源”,内置进程处理所有这些资源……)

验证用户

假设您已经阅读了我前面提到的文章,您就有了一个登录页面。现在,当用户单击登录按钮
Authenticate
method激发时,让我们看看该方法的代码

protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
    string userName = Login1.UserName;
    string password = Login1.Password;
    bool rememberUserName = Login1.RememberMeSet;

    // for this demo purpose, I am storing user details into xml file
    string dataPath = Server.MapPath("~/App_Data/UserInformation.xml");
    DataSet dSet = new DataSet();
    dSet.ReadXml(dataPath);
    DataRow[] rows = dSet.Tables[0].Select(" UserName = '" + userName + "' AND Password = '" + password + "'");
    // record validated
    if (rows.Length > 0)
    {
        // get the role now
        string roles = rows[0]["Roles"].ToString();
        // Create forms authentication ticket
        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
        1, // Ticket version
        userName, // Username to be associated with this ticket
        DateTime.Now, // Date/time ticket was issued
        DateTime.Now.AddMinutes(50), // Date and time the cookie will expire
        rememberUserName, // if user has chcked rememebr me then create persistent cookie
        roles, // store the user data, in this case roles of the user 
        FormsAuthentication.FormsCookiePath); // Cookie path specified in the web.config file in <Forms> tag if any.

        // To give more security it is suggested to hash it
        string hashCookies = FormsAuthentication.Encrypt(ticket);
        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies); // Hashed ticket

        // Add the cookie to the response, user browser
        Response.Cookies.Add(cookie);                // Get the requested page from the url
        string returnUrl = Request.QueryString["ReturnUrl"];

        // check if it exists, if not then redirect to default page
        if (returnUrl == null) returnUrl = "~/Default.aspx";
        Response.Redirect(returnUrl);
    }
    else // wrong username and password
    {
        // do nothing, Login control will automatically show the failure message
        // if you are not using Login control, show the failure message explicitely
    }
} 
并将用户角色设置为:

user.Role
在此过程中,您在Global.asax文件中做了一些更改 到目前为止,我们已经在cookie中设置了表单身份验证票证,其中包含所需的详细信息,甚至包括用户角色,现在如何在每个请求中检索该信息,并找到来自哪个角色类型的请求?为此,我们需要使用Global.asx文件的Application_AuthenticateRequest事件。请参阅下面的代码

protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {

        // look if any security information exists for this request

        if (HttpContext.Current.User != null)
        {

            // see if this user is authenticated, any authenticated cookie (ticket) exists for this user

            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {

                // see if the authentication is done using FormsAuthentication

                if (HttpContext.Current.User.Identity is FormsIdentity)
                {

                    // Get the roles stored for this request from the ticket

                    // get the identity of the user

                    FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;

                    // get the forms authetication ticket of the user

                    FormsAuthenticationTicket ticket = identity.Ticket;

                    // get the roles stored as UserData into the ticket

                    string[] roles = ticket.UserData.Split(',');

                    // create generic principal and assign it to the current request

                    HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(identity, roles);

                }

            }

        }

    }
在这种情况下,即使在检查用户是否存在后,他/她已通过身份验证,并且该用户的身份类型为FormSidenty,我仍将获取该用户的当前身份,并获取我在进行身份验证时设置的票证。一旦我有了经过身份验证的票据,我就从票据中获取了UserData,并将其拆分为角色(记住,我们将角色存储为逗号分隔的值)。现在,我们有了当前用户角色,因此我们可以将当前用户的角色与当前标识一起传递到GenericPrincipal对象,并将其分配给当前用户对象。这将使我们能够使用IsInRole方法来检查特定用户是否属于特定角色

如何检查用户是否具有特定角色

要检查用户是否属于特定角色,请使用以下代码。如果当前记录来自经过身份验证且具有管理员角色的用户,则此代码将返回true

HttpContext.Current.User.IsInRole( "admin" )
如何检查用户是否经过身份验证

要检查用户是否经过身份验证,请使用以下代码

HttpContext.Current.User.Identity.IsAuthenticated
获取经过身份验证的用户的用户名

HttpContext.Current.User.Identity.Name
记住一件事。。此代码需要在表单标记中进行一些webconfig设置,如下所示:

在下的web.config文件中添加以下身份验证设置

<authentication mode="Forms">

    <forms defaultUrl="default.aspx" loginUrl="~/login.aspx" slidingExpiration="true" timeout="20" ></forms>

</authentication>

对于每个用户,如果要保护特定文件夹,可以将其设置放在该文件夹的父web.config文件(根文件夹)或web.config文件中

为根web.config文件中的文件夹指定角色设置(在本例中为Admin)


在根目录的web.config文件中的标记外但在标记下编写此代码。在这里,我指定如果路径包含文件夹Admin的名称,那么只允许具有“Admin”角色的用户,而拒绝所有其他用户

在特定于文件夹的web.config文件中指定文件夹的角色设置(在本例中为用户)


将此代码写入web.config文件用户文件夹。您也可以在root的web.config文件中为用户指定设置,就像我为上面的管理员所做的那样。这只是指定设置的另一种方式。此设置应放在标记下

指定已验证用户的设置

<system.web>

    <authorization>

        <deny users="?"/>

    </authorization>

</system.web>

将此代码写入安全文件夹的web.config文件。这指定拒绝此文件夹的所有匿名用户,并且只允许经过身份验证的用户,而不管其角色如何

希望这能给你一些解决问题的想法。这对我来说很好。
希望您也能解决您的问题。

试试这个,我想这是一个最简单的解决方案:

FormsAuthentication.SetAuthCookie(username, true);
Response.Redirect("mypage.aspx"); 
<location path="Admin">

    <system.web>

        <authorization>

            <allow roles="admin"/>

            <deny users="*"/>

        </authorization>

    </system.web>

</location>
<system.web>

    <authorization>

        <allow roles="User"/>

        <deny users="*"/>

    </authorization>

</system.web>
<system.web>

    <authorization>

        <deny users="?"/>

    </authorization>

</system.web>
FormsAuthentication.SetAuthCookie(username, true);
Response.Redirect("mypage.aspx");