Friday, October 1, 2021

Checking Authentication Without The Authorize Attribute

I wrote a post a couple of years ago about securing an endpoint with an API key that is generated dynamically. I recently came across a scenario where I wanted to use the same endpoint for authenticated requests and non-authenticated requests. That is, regardless whether someone is logged into my app or they've used a valid application to create their request, I want the same endpoint to service that request.

That set me down the path of trying to figure out how to check whether the request is authenticated without using the [Authorize] attribute on the controller class or the action method. It turned out to be pretty easy and testable, but it took me a while to find it.

We can check that User (which is the ClaimsPrincipal of the HttpContext of the controller) is not null and then - if it isn't null - we can check whether the IsAuthenticated property of the Identity property of the User is true. That's it. Just a couple of simple checks to tell us whether the request is authenticated.

if (User == null || !User.Identity.IsAuthenticated) {/*Request is not authenticated*/}

Hopefully this helps you (or future me) down the road.