Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Authorize Attribute to Verify Identity User Logged In

I'm creating a new ASP.NET web application and I'm not planning on making use of the concept of "roles". I do, however, want to make sure a user is logged in on certain pages. Is there any existing attribute that simply checks if a user is logged in and redirects them or throws an error if they're not? Every search I've done points to using roles (such as this one).

like image 411
muttley91 Avatar asked Sep 04 '15 22:09

muttley91


1 Answers

The [Authorize] attribute will only return successfully if the user initiating the request is logged in and will only work on controllers and action methods.

It can be used to decorate a particular action:

public class FooController : Controller
{
    // only FooAction requires authentication in FooController
    [Authorize]
    public async Task<ActionResult> FooAction()
    {        

    }

    public async Task<ActionResult> BarAction()
    {

    }
}

...or an entire controller:

// all actions in FooController require authentication
[Authorize]
public class FooController : Controller
{
    public async Task<ActionResult> FooAction()
    {        

    }

    public async Task<ActionResult> BarAction()
    {

    }
}

You also have Request.IsAuthenticated which can be used on both action and non-action methods:

if (Request.IsAuthenticated) //or @if in Razor
{
    //request is authenticated 
}

...and even User.Identity.IsAuthenticated as @Darko correctly pointed out in his answer. Personally, I prefer Request.IsAuthenticated over User.Identity.IsAuthenticated as it also provides some useful null-checks for User and User.Identity. Here's how Request.IsAuthenticated looks under the hood:

public bool IsAuthenticated
{
    get
    {
        return(_context.User != null 
               && _context.User.Identity != null 
               && _context.User.Identity.IsAuthenticated);
    }
}
like image 150
trashr0x Avatar answered Nov 05 '22 07:11

trashr0x