ASP.NET Core 2.2 & 3 REST API #19 — Restricting endpoints with Authorization handlers

Theodoros Ntakouris
2 min readJul 24, 2019

--

Up Next: Domain to Contract Mapping with AutoMapper

This is about the same subject, authorization. We’ve already tackled claims and roles. Such handlers are needed to tackle more complex requirements, such as ‘being member of this website for at least _ time period’.

Start by removing all of the previous authorization methods we did set up on the previous episode, ending up with just authentication.

We’ll just create a directory Authorization and a new class WorksForCompanyRequirement . We’ve decided to check if a user works for a specific company by checking the domain of his email address. If for example someone’s email ends with chapsas.com , we can assume that he works for Mr. Chapsas, who happens to be the creator of the video series.

“Parameters” for our authorization handler

We will also create a WorksForCompanyHandler: AuthorizationHandler<WorksForCompanyRequirement> and implement the missing methods.

We’ve got a AuthorizationHandlerContext which supplies us with all the information we need.

Just look into the email claim and flag the context as successful or fail.

You can complicate this even more and integrate more services as you wish.

Final step would be to register this policy with our auth options, on the MvcInstaller:

Then, we can secure anything with the [Authorize(Policy = “MustWorkForChapsas”)] attribute.

Up Next: Domain to Contract Mapping with AutoMapper

Code is available on Github and the instructional videos are located on YouTube.

Keep Coding

--

--

No responses yet