简体   繁体   English

ASP.NET成员资格:如何将用户设置为已登录

[英]ASP.NET Membership: how to set the user as logged in

I am trying to get the Membership Provider to work. 我正在努力让会员提供商工作。

So far I have: 到目前为止,我有:

 <asp:Login ID="Login1" runat="server" OnAuthenticate="Login1_Authenticate">
 </asp:Login>

calling : 打电话:

protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
    if(Membership.ValidateUser(Login1.UserName, Login1.Password))
    {
        Response.Redirect("/admin/default.aspx");
        // Set the user as logged in?
    }
}

If I enter the correct login/password, the ValidateUser function returns true. 如果我输入正确的登录名/密码,ValidateUser函数将返回true。 So my question is: how do I set the user as logged in? 所以我的问题是:如何将用户设置为登录?

I am testing this in my pages doing : 我在我的网页上测试这个:

protected void Page_Load(object sender, EventArgs e)
{
    if ( Membership.GetUser()==null)
    {
        Response.Redirect("/admin/login.aspx");
    }
    // else "you are logged in, congratulations"                
}

I would have used the default functions, but it is just not working and a google search made me think that I will save time by actually recoding all that myself. 我会使用默认功能,但它只是不起作用,谷歌搜索让我觉得我会通过实际重新编码所有自己来节省时间。

Anything will help! 一切都会有所帮助!

EDIT : Regarding the accepted answer, it is the correct one for "how to set the user as logged in" and works fine. 编辑 :关于接受的答案,它是“如何设置用户登录”是正确的,并且工作正常。 It didn't fixed my specific problem but only a part of it. 它没有解决我的具体问题,只是其中的一部分。 Thought if you look thought the comments you will find interesting pointers. 如果你认为评论你会发现有趣的指针。

EDIT 2 and solution: Ok I finally worked it out thanks to all the comments. 编辑2和解决方案:好的,由于所有的评论我终于解决了。 Here is what I did, it's simpler than what I expected : 这是我做的,它比我预期的更简单:

Page that checks login state: 检查登录状态的页面:

 protected void Page_Load(object sender, EventArgs e)
 {
     if ( !Request.IsAuthenticated)
     {
         Response.Redirect("/admin/login.aspx");
     }  

Log out: 登出:

   protected void LoginStatus1_Logout(object sender, LoginCancelEventArgs e)
   {
       FormsAuthentication.SignOut();
       Response.Redirect("/admin/login.aspx");
   }
}

web.config: web.config中:

<authentication mode="Forms" />

login: 登录:

protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
    if(Membership.ValidateUser(Login1.UserName, Login1.Password))
    {
        FormsAuthentication.SetAuthCookie(Login1.UserName, true);
        Response.Redirect("/admin/default.aspx");

    }
}

在调用Response.Redirect("/admin/default.aspx");之前将其放入Login1_Authenticate Response.Redirect("/admin/default.aspx");

FormsAuthentication.SetAuthCookie("username", true);

Try moving your code and Gromer's suggestion to the LoggedIn event. 尝试将代码和Gromer的建议移至LoggedIn事件。

protected void Login1_LoggedIn(object sender, EventArgs e)
    {
        if(Membership.ValidateUser(Login1.UserName, Login1.Password))
        {
            FormsAuthentication.SetAuthCookie(Login1.UserName, true);
            Response.Redirect("/admin/default.aspx");
        }

    }

EDIT: Like Gromer said, only do this if you have to execute some business code after the user is logged in and before s/he is redirected. 编辑:像Gromer说的那样,只有在用户登录后和重定向s / he之前必须执行某些业务代码时才这样做。

EDIT EDIT: Visual Studio describes the Authenticate event as, "called to authenticate the user," which implies that the user is not authenticated before the event is called. 编辑编辑:Visual Studio将Authenticate事件描述为“调用以验证用户”,这意味着在调用事件之前未对用户进行身份验证。 Thus, you cannot confirm that the user is logged in because s/he has not been authenticated yet. 因此,您无法确认用户是否已登录,因为他/她尚未经过身份验证。

Gromer has the answer, but you can also take a look at this MSDN article to learn more: Gromer有答案,但您也可以查看这篇MSDN文章以了解更多信息:

http://msdn.microsoft.com/en-us/library/ms998347.aspx http://msdn.microsoft.com/en-us/library/ms998347.aspx

While I don't know how much help this will be, this is boilerplate code I use to discern between admin users or regular users. 虽然我不知道这会有多大帮助,但这是我用来辨别管理员用户或普通用户的样板代码。 Works great for me. 对我来说很棒。

On your login page, probably onclick create your user object and call some function with this code (UserRole is an Enum with your roles): 在您的登录页面上,可能是onclick创建您的用户对象并使用此代码调用某个函数(UserRole是一个包含您角色的枚举):

If admin Then 
            If role = UserRole.Admin Then
                RedirectFromLoginPage(username & "|" & userid, False)
                Return True
            Else
                Return False
            End If
        Else
            If String.IsNullOrEmpty(Current.Request.QueryString("ReturnUrl")) Then
                SetAuthCookie(username & "|" & userid, True)
            Else
                RedirectFromLoginPage(username & "|" & userid, True)
            End If
            Return True
        End If

In your web.config: 在你的web.config中:

<location path="admin">
    <system.web>
        <authorization>
            <allow roles="Admin"/>
            <deny users="*"/>
        </authorization>
    </system.web>
</location>
.....
<system.web>
<authentication mode="Forms">
        <forms loginUrl="/registration/login.aspx" timeout="129600"/>
    </authentication>
    <authorization>
        <allow users="*"/>
    </authorization>
</system.web>

... and if you really want, in your Global.asax page: ...如果你真的想要,请在你的Global.asax页面中:

    Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
    If Request.IsAuthenticated Then
''
'get your roles for the current user'
''
 Dim userRoles() As String = Split(roles, "|")
        'Add the roles to the User Principal'
        HttpContext.Current.User = New GenericPrincipal(User.Identity, userRoles)
    End If
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM