Another quick tip on working with ASP.NET Core API today. When you use ASP.NET Core Identity framework for user authentication, you probably use [Authorize] attribute in your controllers too. For those of you who don’t know it, you can add it to a method in the controller if you want this method to be accessible only by users who have successfully logged in:
By default, when unauthenticated user tries to access this route, ASP will redirect him to ‘/Account/Login’, which is a default login route. You can change this route in the Startup class, in the identity options:
This is great for a routes returning views. However, Authorize attribute behaves the same way also in the API methods returning JSON responses:
Generally, in the API, you don’t want that. What you want is to return a HTTP Status - in this case ‘401 Unauthorized’ message.
I have found two ways to accomplish that. One is through Middleware, but I have also found another, in my opinion, nicer solution, which overrides Identity behaviour, which is exactly what we want to do here.
Identity options, apart from setting LoginPath, allows to modify few events. One of these events is called OnRedirectToLogin:
If you liked this post and are interested in ASP.NET Core, I will be posting more of such tips in future - follow me on Twitter or Facebook not to miss them!