Tuesday, 23 February 2010

Programmatically log in a user, or emulate a user logging in

If you need to log a user on programmatically, that is with no input of password, you can do the following just using their user name:
FormsAuthentication.SetAuthCookie(UserName, True)
Response.Redirect("/somewhere_suitable")
I recently used this to allow a system administrator to login to any user's account as that user by clicking on a button from a list of users. This must be a pretty common thing to do so here's the whole bit of code for the button event:
Protected Sub UsersList_ButtonPress(ByVal sender As Object, ByVal e As ListViewCommandEventArgs) Handles UsersList.ItemCommand

  If e.CommandName = "Login" Then

      Dim userID As Guid = New Guid(e.CommandArgument.ToString)

      Dim user As MembershipUser = Membership.GetUser(userID)
      FormsAuthentication.SetAuthCookie(user.UserName, True)

      Response.Redirect("/somewhere_suitable")

  End If
End Sub
And here's the designer code for the button in the itemtemplate of the listview:
<td>
 <asp:Button ID="LoginButton" runat="server" CommandArgument='<%# Eval("UserID")%>' CommandName="Login" Text="Login" OnClientClick="return confirm('Are you sure you want to login as this user?');" />
</td>
You could of course just send the username as an argument directly from the list, but I didn't do this as the userID just suited some other stuff I've got going on there too!

No comments:

Post a Comment

Comments are moderated, so you'll have to wait a little bit before they appear!