Using FormsAuthentication

2019-05-30 15:32发布

I have a Razor site I made with full login/registration and Admin roles with WebMatrix. And a requirement is for the administrator to be able to "Login as an existing user" in order to be able to add to, edit, cancel and or confirm new orders for that particular user he is logged in as.

I know this is not the most common way of approaching this, but I have seen it done alot. I currently own a domain reselling business and my supplier uses this type of feature where it lets me login as a user to credit their account ETC..

So, I've been told that FormsAuthentication would work good for this in C#. So I checked out:

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

Which leads me to ask:

What?

And...

By "username", they mean the e-mail address that's created when that user registered? Or do they mean the UserId, which is an INT?

And, is it really as simple as doing this?:

@{
  if(Roles.IsUserInRole("Administrator"))
  {
    SetAuthCookie(
      "ClientsUserNameHere,
      true
    );
  }
  else
  {
    Response.Redirect("~/Account/SignIn");
  }
}
<DOCTYPE! HTML>
<html>
  <head></head>
  <body>
    <p>Hello, Administrator, you are currently Signed In as [insert client name here].</p>
  </body>
</html>

1条回答
Summer. ? 凉城
2楼-- · 2019-05-30 16:04

And, is it really as simple as doing this?

Yes, it is really that simple. Well, actually for this to take effect you need to redirect because the page will use the request cookie which still indicates an administrator:

if(Roles.IsUserInRole("Administrator")) {
    FormsAuthentication.SetAuthCookie(
        "ClientsUserNameHere",
        false // <-- set to true only if you want persistent cookies
    );
    Response.Redirect("~/Home/SomeUserPage");
}

In addition you could store some info into the session indicating that this is an administrator acting as a normal user (if you ever needed to know it) and not the normal user.

You might also take a look at the following article for a more advanced impersonation scenario.

查看更多
登录 后发表回答