Authentication Walkthrough - adamfoneil/CloudObjects GitHub Wiki

Here's how I setup JWT authentication:

  1. Add a token generator on startup as scoped service. See TokenGenerator. My example uses a special database dependency via Dapper.CX, but this is unique to my project, not something generally needed. The important thing is here it receives a secret value used for encrypting claims, and it generates claims for an authenticated user.

  2. Configure authentication at startup via this extension method AddCloudObjectsAuthentication. This uses the JWT secret used in step 1. The only reason for using an extension method is to keep the startup code simpler, hiding the configuration details.

  3. Added the Authorize attribute to my base controller used in a couple places in this app (ObjectsController and AccountController). Note how the CommonController reads claims in the constructor to get some user info needed by other controllers, namely the user's AccountId. I'm not exactly sure why I used ControllerBase as the base class instead of simply Controller.

To test the authentication, I use Swagger. I did a video walkthrough of this project here, but the auth-related content begins around 4:20.