Lean token extensions for issuing/validating tokens, automatically creating a private key and creating password salts. Compatible with Asp.Net Core 2.1.
Install the NuGet package
Buzzytom.Extensions.Authentication
Add using statements to get the extensions.
usingExtensions.Authentication;usingExtensions.Authentication.JwtBearer;In the ConfigureServices of your application (or equivalent) add the following calls to register the required services and middleware.
publicvoidConfigureServices(IServiceCollectionservices){// Register other services here, like entity framework// Adds a ITokenService to the dependency servicesservices.AddTokenService();// Adds a IValidatorService to the dependency servicesservices.AddValidationService();// Adds:// - JWT middleware services supporting the Authorize attribute// - Adds a ISymmetricKeyProvider to the dependency servicesservices.AddJwt();}Make sure your application is configured to use authentication.
publicvoidConfigure(IApplicationBuilderapplication){// Configure other services here// Enable authentication, JWT middleware does not work without thisapplication.UseAuthentication();// Configure other services here. E.g. services.UseMvc();}Example controller to issue authentication tokens.
[Route("/api/account")]publicclassAuthenticationController:ControllerBase{privatereadonlyITokenServicetokenService;privatereadonlyIBearerTokenServicebearerTokenService;publicAuthenticationController(ITokenServicetokenService,IBearerTokenService,bearerTokenService){this.tokenService=tokenService;this.bearerTokenService=bearerTokenService;}[HttpPost][Route("authenticate")]publicstringAuthenticate([FromBody]AuthenticateRequestrequest){// DON'T ACTUALLY DO IT LIKE THIS// THIS IS ONLY AN EXAMPLEYourUserTypeuser=GetUserFromYourPersistentStore(request.Email);stringrequestHash=tokenService.Hash(request.Password,user.Salt);if(requestHash==user.PasswordHash)returnbearerTokenService.CreateAuthenticationToken(newClaim(ClaimTypes.Email,request.Email.ToLower()));elsereturnnull;}}Example registration controller
[Route("/api/account")]publicclassRegisterController:ControllerBase{privatereadonlyITokenServiceservice;publicAuthenticationController(ITokenServiceservice){this.service=service;}[HttpPost][Route("register")]publicvoidRegister([FromBody]RegisterRequestrequest){// DON'T ACTUALLY DO IT LIKE THIS// THIS IS ONLY AN EXAMPLE// Perform request validation checksboolexists=CheckUserDoesNotExistInYourPersistentStore(request.Email);if(exists)returnfalse;// Create the passwordstringsalt=service.GenerateSalt();stringhash=service.Hash(request.Password,salt);// Create the new userCreateNewUserInYourPersistentStore(newYourUser{Email=request.Email,Salt=salt,PasswordHash=hash// Other properties});}}Raise them as an issue