|
| 1 | +using Microsoft.AspNetCore.Builder; |
| 2 | +using Microsoft.AspNetCore.Hosting; |
| 3 | +using Microsoft.Extensions.Configuration; |
| 4 | +using Microsoft.Extensions.DependencyInjection; |
| 5 | +using WebApi.Helpers; |
| 6 | +using WebApi.Services; |
| 7 | +using Microsoft.IdentityModel.Tokens; |
| 8 | +using System.Text; |
| 9 | +using Microsoft.AspNetCore.Authentication.JwtBearer; |
| 10 | + |
| 11 | +namespace WebApi |
| 12 | +{ |
| 13 | + public class Startup |
| 14 | + { |
| 15 | + public Startup(IConfiguration configuration) |
| 16 | + { |
| 17 | + Configuration = configuration; |
| 18 | + } |
| 19 | + |
| 20 | + public IConfiguration Configuration { get; } |
| 21 | + |
| 22 | + // This method gets called by the runtime. Use this method to add services to the container. |
| 23 | + public void ConfigureServices(IServiceCollection services) |
| 24 | + { |
| 25 | + services.AddCors(); |
| 26 | + services.AddControllers(); |
| 27 | + |
| 28 | + // configure strongly typed settings objects |
| 29 | + var appSettingsSection = Configuration.GetSection("AppSettings"); |
| 30 | + services.Configure<AppSettings>(appSettingsSection); |
| 31 | + |
| 32 | + // configure jwt authentication |
| 33 | + var appSettings = appSettingsSection.Get<AppSettings>(); |
| 34 | + var key = Encoding.ASCII.GetBytes(appSettings.Secret); |
| 35 | + services.AddAuthentication(x => |
| 36 | + { |
| 37 | + x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; |
| 38 | + x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; |
| 39 | + }) |
| 40 | + .AddJwtBearer(x => |
| 41 | + { |
| 42 | + x.RequireHttpsMetadata = false; |
| 43 | + x.SaveToken = true; |
| 44 | + x.TokenValidationParameters = new TokenValidationParameters |
| 45 | + { |
| 46 | + ValidateIssuerSigningKey = true, |
| 47 | + IssuerSigningKey = new SymmetricSecurityKey(key), |
| 48 | + ValidateIssuer = false, |
| 49 | + ValidateAudience = false |
| 50 | + }; |
| 51 | + }); |
| 52 | + |
| 53 | + // configure DI for application services |
| 54 | + services.AddScoped<IUserService, UserService>(); |
| 55 | + } |
| 56 | + |
| 57 | + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. |
| 58 | + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) |
| 59 | + { |
| 60 | + app.UseRouting(); |
| 61 | + |
| 62 | + // global cors policy |
| 63 | + app.UseCors(x => x |
| 64 | + .AllowAnyOrigin() |
| 65 | + .AllowAnyMethod() |
| 66 | + .AllowAnyHeader()); |
| 67 | + |
| 68 | + app.UseAuthentication(); |
| 69 | + app.UseAuthorization(); |
| 70 | + |
| 71 | + app.UseEndpoints(endpoints => { |
| 72 | + endpoints.MapControllers(); |
| 73 | + }); |
| 74 | + } |
| 75 | + } |
| 76 | +} |
0 commit comments