MFramework.WebApi.Authenticator.Configurator 1.0.1

dotnet add package MFramework.WebApi.Authenticator.Configurator --version 1.0.1                
NuGet\Install-Package MFramework.WebApi.Authenticator.Configurator -Version 1.0.1                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="MFramework.WebApi.Authenticator.Configurator" Version="1.0.1" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add MFramework.WebApi.Authenticator.Configurator --version 1.0.1                
#r "nuget: MFramework.WebApi.Authenticator.Configurator, 1.0.1"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install MFramework.WebApi.Authenticator.Configurator as a Cake Addin
#addin nuget:?package=MFramework.WebApi.Authenticator.Configurator&version=1.0.1

// Install MFramework.WebApi.Authenticator.Configurator as a Cake Tool
#tool nuget:?package=MFramework.WebApi.Authenticator.Configurator&version=1.0.1                

MFramework.WebApi.Authenticator.Configurator

It is a library that facilitates the settings that need to be made for .NET Web API Core. This package especially includes the library where you can easily make the configuration codes in the program.cs file.

  • Basic Authentication Configurator & Validator
  • Bearer Authentication Configurator
  • SwaggerGen Configurator for Basic and Bearer Auth
  • Token Generator

Basic Database EF CodeFirst Setup

Don't forget the EntityFrameworkCore... nuget packages. Don't forget the Add Migration and Update-Database attribute setting.

    public class DatabaseContext : DbContext
    {
        public DatabaseContext(DbContextOptions options) : base(options)
        {
        }

        public DbSet<User> Users { get; set; }


    }

    [Table("Users")]
    public class User
    {
        [Key]
        public int Id { get; set; }

        [StringLength(30)]
        public string Username { get; set; }

        [StringLength(30)]
        public string Password { get; set; }

        [StringLength(30)]
        public string Role { get; set; } = "user";
    }

Basic Authentication

Program.cs

Don't forget the app.UseAuthentication(); setting.

    builder.Services.AddSwaggerGen(opts =>
                    SwaggerGenBootstrapper.BasicAuthenticationSwaggerSetupAction(opts, "Enter your username and password information here."));
    
    builder.Services.AddScoped<IBasicAuthenticationHandlerOptions<User>, MyBasicAuthOptions>();
    
    builder.Services.AddAuthentication(BasicAuthenticationDefaults.Schema)
        .AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler<User>>(BasicAuthenticationDefaults.Schema, null);

MyBasicAuthOptions.cs

public class MyBasicAuthOptions : IBasicAuthenticationHandlerOptions<User>
    {
        public Func<BasicAuthenticationModel, User> AuthenticateExpression => (authModel) =>
        {
            return _databaseContext.Users.SingleOrDefault(
                x => x.Username == authModel.Username && x.Password == authModel.Password);
        };

        public Func<User, List<Claim>> ClaimsFunction => (user) =>
        {
            List<Claim> claims = new List<Claim>
                {
                    new Claim(ClaimTypes.NameIdentifier,user.Id.ToString()),
                    new Claim(ClaimTypes.Name, user.Username),
                    new Claim(ClaimTypes.Role, user.Role)
                };

            return claims;
        };

        public string FailMessage => "Username or password is incorrect!";

        private readonly DatabaseContext _databaseContext;

        public MyBasicAuthOptions(DatabaseContext databaseContext)
        {
            _databaseContext = databaseContext;
        }
    }

WeatherForecastController.cs

Don't forget the [Authorize] attribute setting.

    [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild"
        };

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }

Bearer Authentication(JWT)

appsettings.json

{
  "Token": {
    "Secret": "aGVsbG8gd29ybGQh"
  },
  ...
  "AllowedHosts": "*"
}

Program.cs

Don't forget the app.UseAuthentication(); setting.

    builder.Services.AddSwaggerGen(opts =>
        SwaggerGenBootstrapper.BearerAuthenticationSwaggerSetupAction(opts, "Enter your jwt token information here.(example; HJkasd6HAS6...)"));

    builder.Services.AddScoped<ITokenHandler, webapi_authenticator_helper.BearerAuthentication.TokenHandler>();
    builder.Services.AddScoped<IMyBearerAuth, MyBearerAuth>();
            
    builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(opts =>
    {
        string secret = builder.Configuration.GetValue<string>("Token:Secret");
        ITokenHandler tokenHandler = new webapi_authenticator_helper.BearerAuthentication.TokenHandler();
        TokenValidationParameters validationParameters = BearerAuthenticationHandler.CreateTokenValidationParameters();

        BearerAuthenticationHandler.Configure(secret, tokenHandler, validationParameters, opts);
    });

MyBearerAuth.cs

    public interface IMyBearerAuth
    {
        string Authenticate(string username, string password);
    }

    public class MyBearerAuth : IMyBearerAuth
    {
        private readonly DatabaseContext _databaseContext;
        private readonly IConfiguration _configuration;
        private readonly ITokenHandler _tokenHandler;

        public MyBearerAuth(DatabaseContext databaseContext, IConfiguration configuration, ITokenHandler tokenHandler)
        {
            _databaseContext = databaseContext;
            _configuration = configuration;
            _tokenHandler = tokenHandler;
        }

        public string Authenticate(string username, string password)
        {
            User user = _databaseContext.Users.SingleOrDefault(x => x.Username == username && x.Password == password);

            if (user != null)
            {
                string secret = _configuration.GetValue<string>("Token:Secret");

                List<Claim> claims = new List<Claim>
                {
                    new Claim(ClaimTypes.NameIdentifier,user.Id.ToString()),
                    new Claim(ClaimTypes.Name, user.Username),
                    new Claim(ClaimTypes.Role, user.Role)
                };

                return _tokenHandler.GenerateToken(secret: secret, claims: claims, expires: DateTime.Now.AddMinutes(5));
            }
            else
            {
                return null;
            }
        }
    }

WeatherForecastController.cs

Don't forget the [Authorize] attribute setting. Don't forget the [AllowAnonymous] attribute setting for Authenticate method.

    [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild"
        };

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }
        
        [AllowAnonymous]
        [HttpPost]
        public IActionResult Authenticate(BasicAuthenticationModel model, [FromServices] IMyBearerAuth myBearerAuth)
        {
            string token = myBearerAuth.Authenticate(model.Username, model.Password);

            if (string.IsNullOrEmpty(token) != false)
            {
                return Ok(token);
            }
            else
            {
                return Unauthorized();
            }
        }
    }
Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.0.1 279 10/12/2022
1.0.0 237 10/12/2022