Easy #Angular #Authentication and #Authorization setup using #DOTNETCORE

For the last few months I’ve been struggling to find an authentication and authorization setup that felt right for one of my projects. My requirements were basic. Have a system that I could use to limit access to my API endpoints and front-end components based on the roles of a given user. The back-end was to be written in C# using .NET Core 3.1 and the front-end in TypeScript and Angular.io. The system would also be self-contained, i.e. no external login providers.

Initially I used the default template from Visual Studio for generating an ASP.NET Core Web API project that uses a SPA framework for the front-end and IdentityServer 4 (IS4) to handle the authentication and authorization. It was a nice setup which makes it easy to tie in outside providers (i.e. Google, Microsoft, Facebook, etc) so users can signup using their login from another site. If you aren’t familiar with IS4 then reading the documentation and going through the various examples are a must. The drawbacks I saw was the complication of the system seemed greater than what my project needed and the authentication process required either a popup window, navigating away from the client site, or adding custom security headers to allow the login page to appear in a iframe.

So I went back to searching for other ways to handle authentication and authorization with .NET Core and reading up on the core concepts. Honestly reading the IS4 documentation was also a great way learn. After a few weeks I found a great write-up by Ankit Sharma titled Policy-Based Authorization In Angular Using JWT. Not only was the post well written, if you download the code from their GitHub repository it actually works!

The author goes through the process of creating a new ASP.NET Core 3.1 Web API project and a separate client app using Angular.io 8.3. The client will receive a JSON Web Token(JWT) that includes some basic information about the user, including the roles associated with the account. With this data the client can enable routes and features with basic checks and route guards.

The implementation is well thought out which makes conceptualizing how you could add new features easier. Some of the features that one might want to add are incorporating an auto-refresh of the token while the user is on the site, changing the credentials and auth data storage from in-memory to a database, adding password changes, logging out all active sessions for a user, or registering new users.

Yes, the author didn’t go over these but they did provide a solid foundation to start experimenting. Now if you do need all of these options then maybe revisiting IdentityServer 4 is a good idea since it provides a ready built framework to build a full-fledged identity management system. But for a simpler setup, the write-up by Ankit Sharma is a great starting point.