|
| 1 | +# Mihir.AspNetCore.Authentication.Basic |
| 2 | +Basic Scheme Authentication Implementation for ASP.NET Core 2.0 |
| 3 | + |
| 4 | +Setting it up is quite simple. You will need basic working knowledge of ASP.NET Core 2.0 to get started using this code. |
| 5 | + |
| 6 | + |
| 7 | +```C# |
| 8 | +using Mihir.AspNetCore.Authentication.Basic; |
| 9 | +public class Startup |
| 10 | +{ |
| 11 | + public Startup(IConfiguration configuration) |
| 12 | + { |
| 13 | + Configuration = configuration; |
| 14 | + } |
| 15 | + |
| 16 | + public IConfiguration Configuration { get; } |
| 17 | + |
| 18 | + public void ConfigureServices(IServiceCollection services) |
| 19 | + { |
| 20 | + // Add the Basic scheme authentication here.. |
| 21 | + // AddBasic extension takes an implementation of IBasicUserValidationService for validating the username and password. |
| 22 | + // It also requires Realm to be set in the options. |
| 23 | + services.AddAuthentication(BasicDefaults.AuthenticationScheme) |
| 24 | + .AddBasic<BasicUserValidationService>(options => { options.Realm = "My App"; }); |
| 25 | + |
| 26 | + services.AddMvc(); |
| 27 | + } |
| 28 | + |
| 29 | + public void Configure(IApplicationBuilder app, IHostingEnvironment env) |
| 30 | + { |
| 31 | + app.UseAuthentication(); |
| 32 | + app.UseMvc(); |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | + |
| 37 | +public class BasicUserValidationService : IBasicUserValidationService |
| 38 | +{ |
| 39 | + private readonly ILogger<BasicUserValidationService> _logger; |
| 40 | + |
| 41 | + public BasicUserValidationService(ILogger<BasicUserValidationService> logger) |
| 42 | + { |
| 43 | + _logger = logger; |
| 44 | + } |
| 45 | + |
| 46 | + public Task<bool> IsValidAsync(string username, string password) |
| 47 | + { |
| 48 | + try |
| 49 | + { |
| 50 | + // write your implementation here.. |
| 51 | + return Task.FromResult(true); |
| 52 | + } |
| 53 | + catch (Exception e) |
| 54 | + { |
| 55 | + _logger.LogError(e, e.Message); |
| 56 | + throw; |
| 57 | + } |
| 58 | + } |
| 59 | +} |
| 60 | +``` |
| 61 | + |
| 62 | + |
| 63 | + |
| 64 | +__References__ |
| 65 | +- [Creating an authentication scheme in ASP.NET Core 2.0](https://joonasw.net/view/creating-auth-scheme-in-aspnet-core-2) |
| 66 | +- [aspnet/Security](https://github.com/aspnet/Security) |
| 67 | +- [ASP.NET Core Security documentation](https://docs.microsoft.com/en-us/aspnet/core/security) |
| 68 | +- [RFC 7617: Technical spec for HTTP Basic](https://tools.ietf.org/html/rfc7617) |
0 commit comments