Share Action with Authorized and Unauthorized User

2019-07-27 23:40发布

I have an ASP.NET MVC app that with a controller. All of the actions in this controller can be accessed by anonymous users. However, if the user is authenticated, I want to do something special in the action. Currently, I've noticed that no matter what, User.Identity.IsAuthenticated is always false in the context of this action. Here is my code:

public class MyController : Controller
{
  public ActionResult GetProfile(string id)
  {
    if (User.Identity.IsAuthenticated) {
      ViewBag.ShowAuthStuff = true;
    } else {
      ViewBag.ShowAuthStuff = false;
    }
  }
}

How do I make it such that both an authenticated and an unauthenticated user can access the same action, but do different things? I can't figure out why User.Identify.IsAuthenticated is always false. I checked my cookies. When I'm logged in, there is a cookie named:

.ASPXAUTH

However, when I visit the action, that cookie is no longer available.

1条回答
Animai°情兽
2楼-- · 2019-07-28 00:13

Just use both Authorize and AllowAnonymous filters:

[Authorize]
[AllowAnonymous]
public ActionResult GetProfile(string id)
{
    if (User.Identity.IsAuthenticated) {
        ViewBag.ShowAuthStuff = true;
    } else {
        ViewBag.ShowAuthStuff = false;
    }
}

Though it doesn't make a whole lot of sense to have anonymous access to a "profile".

Also, typically, you don't want to mix authorized and unauthorized actions in the same controller. It's better to have actions that must or may require authorization in a controller together, and unauthorized actions in a separate controller. In that case, you specify the Authorize filter on the controller itself, and then AllowAnonymous on any individual actions that want to interact with authenticated users, but don't require it.

For example in an "Accounts" controller:

[Authorize]
public class AccountsController : Controller
{
    public ActionResult Profile()
    {
        // Login required to reach here
    }

    [AllowAnonymous]
    public ActionResult Login()
    {
        if (User.Identity.IsAuthenticated)
        {
            // Already logged in, redirect to profile
            return RedirectToAction("Profile");
        }

        // Show login form for anonymous user
        return View()
    }
}
查看更多
登录 后发表回答