开发者

.Net Membership provider, validate user when logging in through a persistent cookie

When a user logs in into my website I have a custom membership provider that overrides ValidateUser and verifies that the user has sufficient rights etc.

However, when implementing a 'remember me' function through the default forms authent开发者_运维问答ication using RememberMeSet, I also want to validate a user on the first request.

Is there some hook I can attach to that triggers when a user logs in with their persistent cookie?


All you need to do is call Membership.GetUser() that returns the MembershipUser instance of currently logged in User. If your user logged in with "Remember Me" last time causing a persistent auth. cookie on client, Your MembershipProvider will automatically tell you if the user is logged in[from persistent cookie]. There's no extra effort required to authenticate a user from a persistent auth cookie.

You can work-out your extra hook on MembershipUser instance returned by the method Membership.GetUser() and check if he's authorized to perform the task. If the user is not found to be logged in, the method will simply return null.


I think what you're looking for is the AuthenticateRequest event in a HttpModule. in this event handler, you can check the cookie and validate the credentials, and then set the HttpContext.Current.User to authorize the user.


Workaround:

  1. Have a session variable like UserIsVerified or something
  2. Set this variable to true when logging in through the default loginpage (or through single sign on etc.)
  3. Create the method Application_PreRequestHandlerExecute in global.asax where you verify whether the UserIsVerified prop has been set, and if not: do the appropriate checks

Why Application_PreRequestHandlerExecute?

On PreRequest both session and profile are available. .Net already has interpreted the persistent cookie, and therefore every information you can possible want is there. You can also do a Redirect when the user check fails as we are in the request cycle. It also happens right before any user code is executed, so afaik it's quite safe to do it here to prevent actions like such.

If authentication fails in the handler, I redirect to the logout page and let .Net take care of everything else.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜