· 5 years ago · Dec 11, 2020, 06:38 AM
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Threading.Tasks;
5using Microsoft.AspNetCore.Builder;
6using Microsoft.AspNetCore.Hosting;
7using Microsoft.Extensions.Configuration;
8using Microsoft.Extensions.DependencyInjection;
9using Microsoft.Extensions.Logging;
10using Swashbuckle.AspNetCore.Swagger;
11using AndalLinkageMobile.Common.Data.Model.DbProvider;
12using AndalLinkageMobile.Common.Data.Model;
13using Microsoft.EntityFrameworkCore;
14using Serilog;
15using Serilog.Extensions.Logging;
16using Microsoft.Extensions.DependencyModel;
17using AndalLinkageMobile.Common.Data.Model.Utils;
18using System.Web.Security;
19using Microsoft.AspNetCore.Mvc.ApplicationParts;
20using System.IO;
21using Microsoft.IdentityModel.Tokens;
22using Microsoft.AspNetCore.Authentication.JwtBearer;
23using Microsoft.AspNetCore.Authentication.Cookies;
24using AndalLinkageMobile.ApiCore.Authentication;
25using Microsoft.AspNetCore.Authorization;
26using System.Text;
27
28namespace AndalLinkageMobile.ApiCore
29{
30 public partial class Startup
31 {
32 Microsoft.Extensions.Logging.ILogger _logger;
33
34 private readonly string buildVersionFile = "build-id.txt";
35 private const string ApiVersion = "v1";
36 private string ApiFullVersion => $"{ApiVersion}.0.{(File.Exists(buildVersionFile) ? File.ReadAllText(buildVersionFile) : "0")}";
37
38 public Startup(ILoggerFactory loggerFactory, IHostingEnvironment env)
39 {
40 var builder = new ConfigurationBuilder()
41 .SetBasePath(env.ContentRootPath)
42 .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
43 .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
44 .AddEnvironmentVariables();
45 Configuration = builder.Build();
46
47 // logger configuration
48 Log.Logger = new LoggerConfiguration()
49 .ReadFrom.Configuration(Configuration)
50 .Enrich.FromLogContext()
51 .CreateLogger();
52
53 _logger = loggerFactory.CreateLogger<Startup>();
54 }
55
56 public IConfigurationRoot Configuration { get; }
57
58 // This method gets called by the runtime. Use this method to add services to the container.
59 public void ConfigureServices(IServiceCollection services)
60 {
61
62 var manager = new ApplicationPartManager();
63 manager.ApplicationParts.Add(new AssemblyPart(typeof(Startup).Assembly));
64
65 services.AddSingleton(manager);
66
67 // Add framework services.
68 services.AddMvc();
69 services.AddAntiforgery();
70
71 // Add SQL Server connection as services
72 var dbConnString = Configuration.GetConnectionString("DBConnString");
73 services.AddDbContext<EFCoreContext>(options =>
74 {
75 options.UseSqlServer(dbConnString);
76 options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
77 });
78
79 //Add by Lisa, 11 Agu 2017 - ambil connection string dari appsetting.json
80 services.Configure<AppSettingModel>(Configuration.GetSection("ConnectionStrings"));
81 services.AddOptions();
82
83 // Add Swagger UI for API documentation
84 services.AddSwaggerGen(c =>
85 {
86 c.SwaggerDoc("v1", new Info { Title = "ANDAL API", Version = ApiFullVersion });
87 c.AddSecurityDefinition("Bearer", new ApiKeyScheme
88 {
89 Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
90 Name = "Authorization",
91 In = "header",
92 Type = "apiKey"
93 });
94 });
95
96 //
97
98 var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection("TokenAuthentication:SecretKey").Value));
99
100 // Use TimeSpan constructor to specify:
101 // ... Days, hours, minutes, seconds, milliseconds.
102 // ... The TimeSpan returned has those values.
103 TimeSpan spanExpiration = new TimeSpan(365, 0, 0, 0, 0);
104
105 var tokenProviderOptions = new TokenProviderOptions
106 {
107 Path = Configuration.GetSection("TokenAuthentication:TokenPath").Value,
108 Audience = Configuration.GetSection("TokenAuthentication:Audience").Value,
109 Issuer = Configuration.GetSection("TokenAuthentication:Issuer").Value,
110 SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
111 IdentityResolver = GetIdentity,
112 Expiration = spanExpiration
113 };
114
115 var tokenValidationParameters = new TokenValidationParameters
116 {
117 // the signing key must match!
118 ValidateIssuerSigningKey = true,
119 IssuerSigningKey = signingKey,
120
121 // validate the JWT Issuer (iss) claim
122 ValidateIssuer = true,
123 ValidIssuer = Configuration.GetSection("TokenAuthentication:Issuer").Value,
124
125 // validate JWT Audience
126 ValidateAudience = true,
127 ValidAudience = Configuration.GetSection("TokenAuthentication:Audience").Value,
128
129 // validate the token expired
130 ValidateLifetime = true,
131
132 // If you want to allow a certain amount of clock drift, set that here:
133 ClockSkew = TimeSpan.Zero
134 };
135
136 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
137 .AddJwtBearer(options =>
138 {
139 options.TokenValidationParameters = tokenValidationParameters;
140 options.SaveToken = true;
141
142 });
143 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
144 .AddCookie(options =>
145 {
146 options.ExpireTimeSpan = TimeSpan.MaxValue;
147 });
148 //
149
150 }
151
152 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
153 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifeTime)
154 {
155 //loggerFactory.AddConsole(Configuration.GetSection("Logging"));
156 //loggerFactory.AddDebug();
157
158 loggerFactory.AddSerilog();
159 // ensure any buffered events are sent at shutdown
160 appLifeTime.ApplicationStopped.Register(Log.CloseAndFlush);
161
162 ConfigureAuth(app);
163 app.UseMiddleware<ExceptionMiddleware>();
164 app.UseMvc();
165
166 app.UseSwagger(c =>
167 {
168 c.PreSerializeFilters.Add((swaggerDoc, httpReq) => swaggerDoc.Host = httpReq.Host.Value);
169 });
170
171 //Edit by Lisa, 04 Agu 2017 -> spy bisa ambil nama Application dari WebSite di IIS
172 app.UseSwaggerUI(c =>
173 {
174 //string basePath = Environment.GetEnvironmentVariable("ASPNETCORE_APPL_PATH");
175 //if (basePath == null) basePath = "/";
176 //c.SwaggerEndpoint($"{basePath}/swagger/v1/swagger.json", "ANDAL API V1.0.26.0");
177
178 string basePath = Environment.GetEnvironmentVariable("ASPNETCORE_APPL_PATH");
179 if (basePath == null) basePath = string.IsNullOrWhiteSpace(c.RoutePrefix) ? "." : "..";
180 // c.SwaggerEndpoint(Configuration["AppSettings:VirtualDirectory"] + "/swagger/v1/swagger.json", "ANDAL API V1.0.33.1");
181 c.SwaggerEndpoint($"{basePath}/swagger/v1/swagger.json", "ANDAL API V1.0.41.2");
182
183 //c.SwaggerEndpoint(Configuration["AppSettings:VirtualDirectory"] + "/swagger/v1/swagger.json", "ANDAL API V1.0.0.19");
184 //c.SwaggerEndpoint("/swagger/v1/swagger.json", "ANDAL API V1.0.0.19");
185 });
186
187 /*
188 * Untuk cara Configuration["AppSettings:VirtualDirectory"] -> Add di appsettings.json :
189 "AppSettings": {
190 "VirtualDirectory": "/Api"
191 }
192 * */
193 }
194 }
195}
196