-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStartup.cs
More file actions
216 lines (184 loc) · 8.56 KB
/
Startup.cs
File metadata and controls
216 lines (184 loc) · 8.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
using System;
using Forms.Models;
using Forms.FormModels;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Text.Json.Serialization;
using System.Text.Json;
using Forms.Pages;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
using Microsoft.AspNetCore.Mvc.Authorization;
//using Microsoft.AspNetCore.HttpsPolicy;
using Forms.HRModels;
using System.Linq;
using Hangfire;
using Hangfire.SqlServer;
namespace Forms
{
public class Startup
{
public IWebHostEnvironment Environment { get; }
// public cgformsContext _context;
public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
Configuration = configuration;
Environment = env;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
string[] initialScopes = Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
.AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
.AddInMemoryTokenCaches();
services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
services.AddRazorPages(o =>
{
o.Conventions.AllowAnonymousToPage("/index");
o.Conventions.AllowAnonymousToFolder("/NoAuth");
o.Conventions.AllowAnonymousToFolder("/NoAuth/RSVP");
o.Conventions.AllowAnonymousToPage("/Account");
}).AddMvcOptions(o => { })
.AddMicrosoftIdentityUI()
.AddRazorRuntimeCompilation();
string connectionForms = Configuration.GetConnectionString("formsDB");
string connectionHR = Configuration.GetConnectionString("hrDB");
services.AddDbContext<cgformsContext>(options => options.UseSqlServer(connectionForms, b => b.UseRowNumberForPaging()));
services.AddDbContext<employeeContext>(options => options.UseSqlServer(connectionHR, b => b.UseRowNumberForPaging()));
services.AddHttpContextAccessor();
var context = services.BuildServiceProvider().GetService<cgformsContext>();
var permission = context.Auth.Select(i => i.authname).ToArray();
services.AddAuthorization(options =>
{
// Configure the default policy
options.DefaultPolicy = new AuthorizationPolicyBuilder()
.RequireClaim("preferred_username", permission)
.Build();
// ...other policy configuration
});
services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = null;
options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
options.JsonSerializerOptions.Converters.Add(new IntToStringConverter());
options.JsonSerializerOptions.Converters.Add(new BoolConverter());
});
services.AddResponsiveFileManager(options =>
{
//
options.MaxSizeUpload = 32;
});
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(10);//client side timeout set on _LoginPartial.cshtml
options.Cookie.HttpOnly = true;
});
services.AddHangfire(configuration => configuration
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseSqlServerStorage(Configuration.GetConnectionString("formsDB"), new SqlServerStorageOptions
{
CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
QueuePollInterval = TimeSpan.Zero,
UseRecommendedIsolationLevel = true,
DisableGlobalLocks = true,
})
.WithJobExpirationTimeout(TimeSpan.FromHours(24))
);
services.AddHangfireServer();
}
public class DateTimeConverter : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return DateTime.Parse(reader.GetString());
}
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToUniversalTime().ToString("dd MMMM yyyy hh:mm tt"));
}
}
public class BoolConverter : System.Text.Json.Serialization.JsonConverter<bool>
{
public override void Write(Utf8JsonWriter writer, bool value, JsonSerializerOptions options) =>
writer.WriteBooleanValue(value);
public override bool Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
reader.TokenType switch
{
JsonTokenType.True => true,
JsonTokenType.False => false,
JsonTokenType.String => bool.TryParse(reader.GetString(), out var b) ? b : throw new JsonException(),
JsonTokenType.Number => reader.TryGetInt64(out long l) ? Convert.ToBoolean(l) : reader.TryGetDouble(out double d) ? Convert.ToBoolean(d) : false,
_ => throw new JsonException(),
};
}
public class Int32Converter : System.Text.Json.Serialization.JsonConverter<int>
{
public override int Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.String)
{
string stringValue = reader.GetString();
if (int.TryParse(stringValue, out int value))
{
return value;
}
}
else if (reader.TokenType == JsonTokenType.Number)
{
return reader.GetInt32();
}
throw new System.Text.Json.JsonException();
}
public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options)
{
writer.WriteNumberValue(value);
}
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseSession();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseResponsiveFileManager();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UsePathBase("/Forms");
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages()
.RequireAuthorization();//https://andrewlock.net/setting-global-authorization-policies-using-the-defaultpolicy-and-the-fallbackpolicy-in-aspnet-core-3/;
endpoints.MapControllers();
endpoints.MapHangfireDashboard();
endpoints.MapFallbackToFile("index.html");
});
}
}
}