Implementation of Authentication and JWT based authorization using .NET core and mongoDB
Available implementations that I could find were outdated and there was no clear documentation on using the most recent MongoDB C# driver for ASP .NET core 2.0. If you've landed here looking for an implementation that works I hope this helps you.
- Install MongoDB
- Install .NET core 2.0 SDK
- This project was developed using VS 2017
- The Documentation incorrectly defines usage for
Collection.Update
method. It expects a LINQ functor but the docs say that a Mongo Filter is needed.
var result = _users.UpdateOne<User>(u => u.UserName == userName, update);
- Code samples in Shawn Wildermuth's blog inject
IConfigurationRoot
into controllers to access properties. The appropriate way suggested by Microsoft docs is usingIOptions
classes that allow for strongly typed options objects on top of all available configuration inappsettings.json
.
//Startup.cs -> ConfigureServices
services.Configure<TokenOptions>(Configuration.GetSection("Tokens"));
//LoginController
private TokenOptions _tokenOptions;
public LoginController(IOptions<TokenOptions> tokenOptionsAccessor)
{
_tokenOptions = tokenOptionsAccessor.Value;
}
- .NET core 2.0 has deprecated
app.Use<AuthenticationType>
and authentication needs to be added as a service that is called only once in the configured pipeline.
public void ConfigureServices(IServiceCollection services)
{
...
services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = tokenValidationParameters;
});
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
app.UseAuthentication();
...
}
Mongoose, an object modeling library for MongoDB in NodeJS exposes a very useful feature PreSaveHooks
. This allows for controlling fields like passwords and how they are persisted in the DB. The C# Driver for MongoDB does not have any similar features and it would be interesting to investigate if somethign like this can be introduced here.