· 7 years ago · Dec 13, 2018, 05:40 PM
1using System;
2using System.Text;
3using Backend.DataAccessLayer;
4using Backend.Services;
5using Microsoft.AspNetCore.Builder;
6using Microsoft.AspNetCore.Hosting;
7using Microsoft.AspNetCore.Identity;
8using Microsoft.EntityFrameworkCore;
9using Microsoft.Extensions.Configuration;
10using Microsoft.Extensions.DependencyInjection;
11using Microsoft.IdentityModel.Tokens;
12using AutoMapper;
13using Backend.Models;
14using Microsoft.AspNetCore.Authentication.JwtBearer;
15using Backend.Helpers;
16using Microsoft.Extensions.DependencyInjection.Extensions;
17using Microsoft.AspNetCore.Http;
18using Microsoft.AspNetCore.Mvc.Infrastructure;
19using System.Web.Http;
20using Swashbuckle.AspNetCore.Swagger;
21using System.Net;
22using Backend.Extensions;
23using Microsoft.AspNetCore.Diagnostics;
24
25namespace Backend
26{
27 public class Startup
28 {
29 private const string SecretKey = "iNivDmHLpUA223sqsfhqGbMRdRj1PVkH"; // todo: get this from somewhere secure
30 private readonly SymmetricSecurityKey _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));
31
32 public Startup(IConfiguration configuration)
33 {
34 Configuration = configuration;
35 }
36
37 public IConfiguration Configuration { get; }
38
39
40
41 public void ConfigureServices(IServiceCollection services)
42 {
43 services.AddIdentity<IdentityUser, IdentityRole>()
44 .AddEntityFrameworkStores<BackendContext>()
45 .AddDefaultTokenProviders();
46
47 services.AddDbContext<BackendContext>(options =>
48 options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
49 b => b.MigrationsAssembly("Backend")));
50
51 services.AddSingleton<IJwtFactory, JwtFactory>();
52
53 // Register the ConfigurationBuilder instance of FacebookAuthSettings
54 // services.Configure<FacebookAuthSettings>(Configuration.GetSection(nameof(FacebookAuthSettings)));
55
56 //services.TryAddTransient<IHttpContextAccessor, HttpContextAccessor>();
57
58 // jwt wire up
59 // Get options from app settings
60 var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));
61
62 // Configure JwtIssuerOptions
63 services.Configure<JwtIssuerOptions>(options =>
64 {
65 options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
66 options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
67 options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
68 });
69
70 var tokenValidationParameters = new TokenValidationParameters
71 {
72 ValidateIssuer = true,
73 ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],
74
75 ValidateAudience = true,
76 ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],
77
78 ValidateIssuerSigningKey = true,
79 IssuerSigningKey = _signingKey,
80
81 RequireExpirationTime = false,
82 ValidateLifetime = true,
83 ClockSkew = TimeSpan.Zero
84 };
85
86 services.AddAuthentication(options =>
87 {
88 options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
89 options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
90
91 }).AddJwtBearer(configureOptions =>
92 {
93 configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
94 configureOptions.TokenValidationParameters = tokenValidationParameters;
95 configureOptions.SaveToken = true;
96 });
97
98 // api user claim policy
99 services.AddAuthorization(options =>
100 {
101 options.AddPolicy("ApiUser", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.ApiAccess));
102 });
103
104 services.AddAuthorization(options =>
105 {
106 options.AddPolicy("Admin", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, "admin"));
107 });
108 // add identity
109 var builder = services.AddIdentityCore<AppUser>(o =>
110 {
111 // configure identity options
112 o.Password.RequireDigit = false;
113 o.Password.RequireLowercase = false;
114 o.Password.RequireUppercase = false;
115 o.Password.RequireNonAlphanumeric = false;
116 o.Password.RequiredLength = 6;
117 });
118 builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
119 builder.AddEntityFrameworkStores<BackendContext>().AddDefaultTokenProviders();
120
121 services.AddAutoMapper();
122
123 services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
124 services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
125
126 services.AddDbContext<BackendContext>(options =>
127 options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
128 b => b.MigrationsAssembly("Backend")));
129 services.AddTransient<IStoreService, StoreService>();
130 services.AddMvc();//.AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());
131 // Register the Swagger generator, defining one or more Swagger documents
132 services.AddSwaggerGen(c =>
133 {
134 c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
135 });
136 }
137
138 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
139 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
140 {
141 if (env.IsDevelopment())
142 {
143 app.UseDeveloperExceptionPage();
144 }
145
146
147
148 app.UseExceptionHandler(
149 builder =>
150 {
151 builder.Run(
152 async context =>
153 {
154 context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
155 context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
156
157
158 var error = context.Features.Get<IExceptionHandlerFeature>();
159 if (error != null)
160 {
161 context.Response.AddApplicationError(error.Error.Message);
162 await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false);
163 }
164 });
165 });
166
167 // Enable middleware to serve generated Swagger as a JSON endpoint.
168 app.UseSwagger();
169
170 // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
171 app.UseSwaggerUI(c =>
172 {
173 c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
174 });
175
176 app.UseAuthentication();
177 app.UseDefaultFiles();
178 app.UseStaticFiles();
179 AuthAppBuilderExtensions.UseAuthentication(app);
180 app.UseMvc();
181
182 }
183 }
184}