· 4 years ago · May 17, 2021, 11:44 AM
1using Microsoft.AspNetCore.Builder;
2using Microsoft.AspNetCore.Hosting;
3using Microsoft.AspNetCore.Identity;
4using Microsoft.EntityFrameworkCore;
5using Microsoft.Extensions.Configuration;
6using Microsoft.Extensions.DependencyInjection;
7using Microsoft.Extensions.Hosting;
8using Microsoft.OpenApi.Models;
9using SmartGarage.Data;
10using SmartGarage.Data.Models;
11using System;
12using System.Text;
13using System.Collections.Generic;
14using System.IO;
15using System.Linq;
16using System.Reflection;
17using System.Threading.Tasks;
18using Microsoft.AspNetCore.Authentication.JwtBearer;
19using Microsoft.IdentityModel.Tokens;
20using SmartGarage.Service.Helpers;
21using SmartGarage.Service.Contracts;
22using SmartGarage.Service.Services;
23using SmartGarage.Service.ServiceContracts;
24using SmartGarage.Service;
25using Microsoft.AspNetCore.Authentication.Cookies;
26
27namespace SmartGarage
28{
29 public class Startup
30 {
31 public Startup(IConfiguration configuration)
32 {
33 Configuration = configuration;
34 }
35
36 public IConfiguration Configuration { get; }
37
38 // This method gets called by the runtime. Use this method to add services to the container.
39 public void ConfigureServices(IServiceCollection services)
40 {
41 services.AddDbContext<SmartGarageContext>(options =>
42 options.UseSqlServer(
43 Configuration.GetConnectionString("DefaultConnection")));
44
45 services.AddIdentity<User, Role>(options =>
46 {
47 options.SignIn.RequireConfirmedAccount = false;
48 options.Password.RequireNonAlphanumeric = false;
49
50 })
51 .AddEntityFrameworkStores<SmartGarageContext>()
52 .AddDefaultTokenProviders();
53
54 services.AddScoped<IUserService, UserService>();
55
56 services.AddControllersWithViews();
57 services.AddRazorPages();
58
59 services.AddSwaggerGen(c =>
60 {
61 c.SwaggerDoc("v1", new OpenApiInfo { Title = "SmartGarage API", Version = "v1", Description = "SmartGarage REST Api" });
62 var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
63 var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
64 c.IncludeXmlComments(xmlPath);
65
66 var securityScheme = new OpenApiSecurityScheme
67 {
68 Name = "JWT Authentication",
69 Description = "Enter JWT Bearer token **_only_**",
70 In = ParameterLocation.Header,
71 Type = SecuritySchemeType.Http,
72 Scheme = "bearer", // must be lower case
73 BearerFormat = "JWT",
74 Reference = new OpenApiReference
75 {
76 Id = JwtBearerDefaults.AuthenticationScheme,
77 Type = ReferenceType.SecurityScheme
78 }
79 };
80 c.AddSecurityDefinition(securityScheme.Reference.Id, securityScheme);
81 c.AddSecurityRequirement(new OpenApiSecurityRequirement
82 {
83 {securityScheme, new string[] { }}
84 });
85
86 });
87
88 //configure strongly typed settings objects
89 var appSettingsSection = this.Configuration.GetSection("AppSettings");
90 services.Configure<AppSettings>(appSettingsSection);
91
92 //configure jwt authentication
93 var appSettings = appSettingsSection.Get<AppSettings>();
94 var key = Encoding.ASCII.GetBytes(appSettings.Secret);
95
96 services.AddAuthentication(config =>
97 {
98 // config.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
99 // config.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
100 })
101 .AddCookie(config => config.SlidingExpiration = true)
102 .AddJwtBearer(config =>
103 {
104 config.RequireHttpsMetadata = false;
105 config.SaveToken = true;
106 config.TokenValidationParameters = new TokenValidationParameters
107 {
108 ValidateIssuerSigningKey = true,
109 IssuerSigningKey = new SymmetricSecurityKey(key),
110 ValidateIssuer = false,
111 ValidateAudience = false
112 };
113 });
114
115 services.AddTransient<IEmailsService, GmailSmtpEmailsService>();
116 }
117
118 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
119 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
120 {
121 if (env.IsDevelopment())
122 {
123 app.UseDeveloperExceptionPage();
124 app.UseDatabaseErrorPage();
125 app.UseSwagger();
126 app.UseSwaggerUI(c =>
127 {
128 c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
129 });
130 }
131 else
132 {
133 app.UseExceptionHandler("/Home/Error");
134 // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
135 app.UseHsts();
136 }
137
138 app.UseCors(x => x
139 .AllowAnyOrigin()
140 .AllowAnyMethod()
141 .AllowAnyHeader());
142
143 app.UseHttpsRedirection();
144 app.UseStaticFiles();
145
146 app.UseRouting();
147
148 app.UseAuthentication();
149 app.UseAuthorization();
150
151 app.UseEndpoints(endpoints =>
152 {
153 endpoints.MapControllerRoute(
154 name: "default",
155 pattern: "{controller=Home}/{action=Index}/{id?}");
156 endpoints.MapRazorPages();
157 });
158 }
159 }
160}
161