Search code examples
authenticationcontrollerroutesasp.net-identityasp.net-core-2.1

How to make a route available only after login in asp.net core 2.1?


I am not sure how to ask this but here it goes. I am trying to make a route or URL from a controller will be only available to access after login of the user. I don't know to find these code in asp.net core 2.1. I know how to do it for its view part.

@if (SignInManager.IsSignedIn(User)){ //authorized section }

But I am not sure about the controller/route parts. So, I need your help to make learn this properly.

Thank you.


Solution

  • I'm not sure exactly what you're asking. If your question is how you can make the route not exist at all, that is impossible. If it's exposed, it's exposed. However, you can force a user to be authorized to access it, which brings me to the next possible interpretation: how do you force a user to be authorized in order to access a particular route. That is simple; you just decorate the action with the Authorize attribute:

    [Authorize]
    public IActionResult OnlyForAuthenticateUsers()
    

    You can also decorate the controller class, instead, which will protect every action in the controller:

    [Authorize]
    public class MyController
    

    If you just need one or so actions to be open, such as a "signin" action in a controller that otherwise has actions only available to authenticated users, then you can utilize the AllowAnonymous attribute:

    [AllowAnonymous]
    public IActionResult SignIn()
    

    Finally, the Authorize attribute also lets you specify roles and/or policies that must be satisfied in addition to being authenticated. For example, to lock down a particular action to only "Admin" users, you might do something like [Authorize(Roles = "Admin")].