· 5 years ago · May 21, 2020, 06:58 PM
1using System;
2using System.Text;
3using Microsoft.AspNetCore.Authentication.JwtBearer;
4using Microsoft.AspNetCore.Builder;
5using Microsoft.AspNetCore.Hosting;
6using Microsoft.AspNetCore.Identity;
7using Microsoft.AspNetCore.Mvc.Authorization;
8using Microsoft.EntityFrameworkCore;
9using Microsoft.Extensions.Configuration;
10using Microsoft.Extensions.DependencyInjection;
11using Microsoft.Extensions.Hosting;
12using Microsoft.IdentityModel.Tokens;
13using Microsoft.OpenApi.Models;
14using ZoundAPI.Data;
15using ZoundAPI.Data.Interfaces;
16using ZoundAPI.Data.ServiceInstances;
17using ZoundAPI.Options;
18
19namespace ZoundAPI
20{
21 public class Startup
22 {
23 public Startup(IConfiguration configuration)
24 {
25 Configuration = configuration;
26 }
27
28 public IConfiguration Configuration { get; }
29
30 // This method gets called by the runtime. Use this method to add services to the container.
31 public void ConfigureServices(IServiceCollection services)
32 {
33 services.AddControllers(o => o.Filters.Add(new AuthorizeFilter()))
34 .AddNewtonsoftJson(options =>
35 options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
36 );
37 services.AddSwaggerGen(x =>
38 {
39 x.SwaggerDoc("v1", new OpenApiInfo { Title = "Zound API", Version = "v1" });
40 });
41 services.AddScoped<IUserService, UserService>();
42
43 services.AddScoped<IArtistService, ArtistService>();
44 services.AddScoped<IMusicRoomService, MusicRoomService>();
45 services.AddScoped<ISongService, SongService>();
46 services.AddScoped<ZoundDataInit>();
47 services.AddIdentity<IdentityUser, IdentityRole>(o =>
48 {
49 o.Password.RequireDigit = false;
50 o.Password.RequireUppercase = false;
51 o.Password.RequiredLength = 6;
52 o.Password.RequireLowercase = false;
53 o.Password.RequireNonAlphanumeric = false;
54 o.User.RequireUniqueEmail = true;
55 }).AddEntityFrameworkStores<ZoundContext>();
56
57 services.ConfigureApplicationCookie(options =>
58 {
59 // Cookie settings
60 options.Cookie.HttpOnly = true;
61 options.ExpireTimeSpan = TimeSpan.FromDays(30);
62
63 options.LoginPath = "/api/Account/Login";
64 options.AccessDeniedPath = "/api/Account/AccessDenied";
65 options.SlidingExpiration = true;
66 });
67
68 //You can add the launchsettings to gitignore to hide keys, won't do it otherwise app doesn't work and can't be cloned.
69 services.AddDbContext<ZoundContext>(options =>
70 options.UseSqlServer(
71 Environment.GetEnvironmentVariable("ConnectionStringVariable") ?? throw new ArgumentNullException(nameof(services))
72 ));
73 var key = Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("SignInKey") ?? throw new ArgumentNullException(nameof(services)));
74
75 services.AddAuthentication(x =>
76 {
77 x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
78 x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
79 x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
80 }).AddJwtBearer(x =>
81 {
82 x.RequireHttpsMetadata = false;
83 x.SaveToken = false;
84 x.TokenValidationParameters = new TokenValidationParameters
85 {
86 ValidateIssuerSigningKey = true,
87 IssuerSigningKey = new SymmetricSecurityKey(key),
88 ValidateIssuer = false,
89 ValidateAudience = false,
90 ClockSkew = TimeSpan.Zero
91 };
92 });
93
94 // services.AddAuthentication(x =>
95 // {
96 // x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
97 // x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
98 // }).AddJwtBearer(x => {
99 // x.RequireHttpsMetadata = false;
100 // x.SaveToken = true;
101 // x.TokenValidationParameters = new TokenValidationParameters
102 // {
103 // ValidateIssuerSigningKey = true,
104 // IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"])),
105 // ValidateIssuer = false,
106 // ValidateAudience = false
107 // };
108 // });
109 }
110
111 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
112 public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ZoundDataInit datainit)
113 {
114 if (env.IsDevelopment())
115 {
116 app.UseDeveloperExceptionPage();
117 }
118 else
119 {
120 app.UseStatusCodePages();
121 }
122
123 var swaggerOptions = new SwaggerOptions();
124 Configuration.GetSection(nameof(SwaggerOptions)).Bind(swaggerOptions);
125
126 app.UseSwagger();
127 app.UseSwaggerUI(option =>
128 {
129 option.SwaggerEndpoint(swaggerOptions.UiEndpoint, swaggerOptions.Description);
130 });
131
132 app.UseHttpsRedirection();
133 var webSocketOptions = new WebSocketOptions()
134 {
135 KeepAliveInterval = TimeSpan.FromDays(1),
136 ReceiveBufferSize = 4 * 1024
137 };
138 app.UseWebSockets(webSocketOptions);
139
140 app.UseRouting();
141
142
143 app.UseAuthentication();
144 app.UseAuthorization();
145
146 app.UseEndpoints(endpoints =>
147 {
148 endpoints.MapControllers();
149 });
150
151 datainit.InitAsync().Wait();
152
153 }
154 }
155}