|
| 1 | +using Microsoft.AspNetCore.Authorization; |
| 2 | +using Microsoft.AspNetCore.Builder; |
| 3 | +using Microsoft.AspNetCore.Hosting; |
| 4 | +using Microsoft.AspNetCore.Mvc.Authorization; |
| 5 | +using Microsoft.AspNetCore.Rewrite; |
| 6 | +using Microsoft.Extensions.Configuration; |
| 7 | +using Microsoft.Extensions.DependencyInjection; |
| 8 | +using Mihir.AspNetCore.Authentication.Basic; |
| 9 | +using SampleWebApi.Repositories; |
| 10 | +using SampleWebApi.Services; |
| 11 | + |
| 12 | +namespace SampleWebApi |
| 13 | +{ |
| 14 | + public class Startup |
| 15 | + { |
| 16 | + public Startup(IConfiguration configuration) |
| 17 | + { |
| 18 | + Configuration = configuration; |
| 19 | + } |
| 20 | + |
| 21 | + public IConfiguration Configuration { get; } |
| 22 | + |
| 23 | + // This method gets called by the runtime. Use this method to add services to the container. |
| 24 | + public void ConfigureServices(IServiceCollection services) |
| 25 | + { |
| 26 | + // Add User repository to the dependency container. |
| 27 | + services.AddTransient<IUserRepository, InMemoryUserRepository>(); |
| 28 | + |
| 29 | + // Add the Basic scheme authentication here.. |
| 30 | + // AddBasic extension takes an implementation of IBasicUserValidationService for validating the username and password. |
| 31 | + // It also requires Realm to be set in the options. |
| 32 | + services.AddAuthentication(BasicDefaults.AuthenticationScheme) |
| 33 | + .AddBasic<BasicUserValidationService>(options => { options.Realm = "Sample Web API"; }); |
| 34 | + |
| 35 | + services.AddMvc(options => |
| 36 | + { |
| 37 | + // ALWAYS USE HTTPS (SSL) protocol in production when using Basic authentication. |
| 38 | + //options.Filters.Add<RequireHttpsAttribute>(); |
| 39 | + |
| 40 | + // All the requests will need to be authorized. |
| 41 | + // Alternatively, add [Authorize] attribute to Controller or Action Method where necessary. |
| 42 | + options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build())); |
| 43 | + } |
| 44 | + ).AddXmlSerializerFormatters(); // To enable XML along with JSON |
| 45 | + } |
| 46 | + |
| 47 | + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. |
| 48 | + public void Configure(IApplicationBuilder app, IHostingEnvironment env) |
| 49 | + { |
| 50 | + if (env.IsDevelopment()) |
| 51 | + { |
| 52 | + app.UseDeveloperExceptionPage(); |
| 53 | + } |
| 54 | + else |
| 55 | + { |
| 56 | + // ALWAYS USE HTTPS (SSL) protocol in production when using Basic authentication. |
| 57 | + app.UseRewriter(new RewriteOptions().AddRedirectToHttpsPermanent()); |
| 58 | + } |
| 59 | + |
| 60 | + app.UseAuthentication(); |
| 61 | + app.UseMvc(); |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments