-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
197 lines (169 loc) · 5.38 KB
/
Program.cs
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
using Microsoft.EntityFrameworkCore;
using WatchListV2.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Net.Http.Headers;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using WatchListV2.Data;
using WatchListV2.Attribute;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using WatchListV2.Constants;
using WatchListV2.Controllers;
using Microsoft.AspNetCore.Authentication.Cookies;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers(opts =>
{
opts.CacheProfiles.Add("NoCache", new CacheProfile() {
NoStore = true
});
opts.CacheProfiles.Add("Any-60", new CacheProfile() {
Location = ResponseCacheLocation.Any,
Duration = 60
});
});
builder.Services.AddControllersWithViews();
builder.Services.AddHttpClient("ApiClient", client =>
{
var apiBaseUrl = builder.Configuration["ApiBaseUrl"];
client.BaseAddress = new Uri(apiBaseUrl);
});
builder.Services.AddRazorPages();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(opts =>
{
//Add Authorization and test endpoints for client side
opts.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Description = "Please enter token",
Name = "Authorization",
Type = SecuritySchemeType.Http,
BearerFormat = "JWT",
Scheme = "bearer"
});
//Change this later for cleaner view
opts.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference{ Type = ReferenceType.SecurityScheme, Id = "Bearer"}
},
Array.Empty<string>()
}
});
opts.EnableAnnotations();
});
builder.Services.AddDistributedSqlServerCache(opts =>
{
opts.ConnectionString = builder.Configuration.GetConnectionString("DefaultConnection");
opts.SchemaName = "dbo";
opts.TableName = "AppCache";
});
builder.Services.AddDbContext<ApplicationDbContext>(opts =>
{
opts.UseSqlServer(builder.Configuration["ConnectionStrings:DefaultConnection"]);
});
//Configuration for password requirements
builder.Services.AddIdentity<ApiUsers, IdentityRole>(opts =>
{
opts.Password.RequireDigit = true;
opts.Password.RequireLowercase = true;
opts.Password.RequireUppercase = true;
opts.Password.RequireNonAlphanumeric = true;
opts.Password.RequiredLength = 10;
}).AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultUI();
//This helps reduce forgery tokens in third party attacks
builder.Services.AddAuthentication(opts =>
{
opts.DefaultAuthenticateScheme =
opts.DefaultChallengeScheme =
opts.DefaultForbidScheme =
opts.DefaultScheme =
opts.DefaultSignInScheme =
opts.DefaultSignOutScheme =
JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(opts =>
{
opts.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = builder.Configuration["JWT:Issuer"],
ValidateAudience = true,
ValidAudience = builder.Configuration["JWT:Audience"],
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(
System.Text.Encoding.UTF8.GetBytes(builder.Configuration["JWT:SigningKey"]))
};
});
builder.Services.AddSession(opts =>
{
opts.IdleTimeout = TimeSpan.FromMinutes(30); // Set the session timeout
opts.Cookie.HttpOnly = true;
opts.Cookie.IsEssential = true;
});
builder.Services.AddAuthorization();
builder.Services.AddScoped<IUserService,EUserService>();
builder.Services.AddScoped<ISeriesService,ESeriesService>();
builder.Services.AddScoped<IAdminSeriesService,EAdminSeriesService>();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
app.MapGet("/auth/test/1",
[Authorize]
[ResponseCache(NoStore = true)]
() =>
{
return Results.Ok("You are authorized!");
});
app.MapGet("/auth/test/rbac",
[ResponseCache(CacheProfileName = "NoCache")]
[Authorize]
(HttpContext httpContext) =>
{
var user = httpContext.User;
if (user.IsInRole(RoleNames.Administrator))
{
return Results.Ok("You are Authorized as Admin!");
}
else if (user.IsInRole(RoleNames.User))
{
return Results.Ok("You are not an Admin! Go back!");
}
return Results.Forbid();
});
}
app.UseSession();
app.UseRouting();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.Use((context, next) =>
{
context.Response.Headers["cache-control"] = "no-cache, no-store";
return next.Invoke();
});
app.UseStaticFiles();
app.MapDefaultControllerRoute();
app.MapControllers();
app.MapGet("/", () => "Hello World");
await SeedData.EnsurePopulated(app);
app.Run();
/*
* Notes:
* Added EF core
* Added EF Core Identity
* Added Swashbuckle
* Added JWT
* Added Swashbuckle Annotations 6.4.0
* Added OpenAPIAnalyzers
* Added SQL Server Cache
* Added SQL server tool : dotnet tool install --global dotnet-sql-cache -version 6.0.11 (for creating AppCache DB Table)
* Added Dynamic LINQ for SeriesController on Query = query.order
*/