This project expands on the MongoDb API tutorial provided by Microsoft. The project adds user functionality through the data model ApiUser. It uses the ApiUser model to add JWT authentication. Roles are also specified on the ApiUser model, these are used with authorization to only make particular API routes accessible depending on the user's role. The entire project is supposed to be a simple take on authentication and authorization of ASP.NET Core Web APIs without having to use Azure Active Directory, Azure Active Directory B2C or IdentityServer4 (although those solutions are significantly more secure). Also no SQL database is used, only MongoDb.
- ASP.NET Core 3.1
- A local instance of MongoDb
Here is a collection of resources that were used in putting this together:
- Create a web API with ASP.NET Core and MongoDB
- ASP.NET Core 3.1 - Simple API for Authentication, Registration and User Management
- Overview of ASP.NET Core authentication
- Introduction to authorization in ASP.NET Core
- Introduction to Identity on ASP.NET Core
This controller contains all the routes for user related API queries. The definitions and routes are shown below.
// route: /api/users/register
[AllowAnonymous]
[HttpPost("register")]
public IActionResult Register([FromBody] NewApiUser newApiUser){..}
// route: /api/users/authenticate
[AllowAnonymous]
[HttpPost("authenticate")]
public IActionResult Authenticate([FromBody] LoginModel newLogin){..}
// route: /api/users
[HttpGet]
[Authorize(Policy = "LibraryTeam")]
public IActionResult Get(string? id, string? username, string? email){..}
// route: /api/users/search
[HttpGet("search")]
[Authorize(Policy = "LibraryTeam")]
public IActionResult Search(string? firstName, string? lastName, int? role){..}
// route: /api/users
[HttpDelete]
[Authorize(Roles = "LibraryAdmin")]
public IActionResult Delete(string id){..}
This controller contains all the routes for books related API queries. The definitions and routes are shown below.
// route: /api/books
[HttpGet]
public ActionResult<List<Book>> Get(){..}
// route: /api/books/{mongoDbId}
[HttpGet("{id:length(24)}", Name = "GetBook")]
public ActionResult<Book> Get(string id){..}
// route: /api/books
[HttpPost]
[Authorize(Policy = "LibraryTeam")]
public ActionResult<Book> Create(Book book){..}
// route: /api/books/{mongoDbId}
[HttpPut("{id:length(24)}")]
[Authorize(Policy = "LibraryTeam")]
public IActionResult Update(string id, Book bookIn){..}
// route: /api/books/{mongoDbId}
[HttpDelete("{id:length(24)}")]
[Authorize(Roles = "LibraryAdmin")]
public IActionResult Delete(string id){..}