简体   繁体   中英

Check if user is logged on in ASP.NET Core

I'm new to ASP.NET Core and I'm still very uncomfortable. Anyways, I would like to know if this way is correct or if exists better solutions.

I'm checking on every page if a user is logged on. If not, I will redirect page to login page:

public IActionResult Index()
{
    if (User.Identity.IsAuthenticated)
    {
        return View();
    }
    else
    {
        return Redirect("Identity/Account/Login");
    }
}

I'm adding this in every single page.

Instead of adding User.Identity.IsAuthenticated (very un-DRY) you should check out DataAnnotations - [AllowAnonymous] and [Authorize] . You can decorate whole controllers or specific methods with these annotations to allow authentication for specific functionality.

[AllowAnonymous]
public IActionResult Index()
{
    return View();
}

[Authorize]
public IActionResult OnlyAuthenticatedUsers()
{
  return View();
}

Then you can add, in your Startup.cs, redirection rules if the user is not authenticated.

Check this out:

Use the Authorize action filter

Action filter executes before and after an action method executes. Action filter attributes can be applied to an individual action method or to a controller. When action filter applied to the controller then it will be applied to all the action methods in that controller.

For your case

[Authorize]
public IActionResult Index()
{
        return View(); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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