-
Notifications
You must be signed in to change notification settings - Fork 20
/
Program.cs
279 lines (229 loc) · 12.5 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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
using BlazorSimpleSurvey.Data;
using BlazorSimpleSurvey.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
using Radzen;
using System.Linq.Dynamic.Core;
using System.Security.Claims;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<SimpleSurveyContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor()
.AddMicrosoftIdentityConsentHandler();
builder.Services.AddScoped<DialogService>();
builder.Services.AddScoped<TooltipService>();
builder.Services.AddScoped<NotificationService>();
builder.Services.AddScoped<SimpleSurveyService>();
builder.Services.AddHttpClient<ProtectedApiCallHelper>();
// This is where you wire up to events to detect when a user logs in
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(options =>
{
builder.Configuration.Bind("AzureAdB2C", options);
options.Events = new OpenIdConnectEvents
{
OnRedirectToIdentityProvider = async ctxt =>
{
// Invoked before redirecting to the identity provider to authenticate.
// This can be used to set ProtocolMessage.State
// that will be persisted through the authentication process.
// The ProtocolMessage can also be used to add or customize
// parameters sent to the identity provider.
await Task.Yield();
},
OnAuthenticationFailed = async ctxt =>
{
// They tried to log in but it failed
await Task.Yield();
},
OnTicketReceived = async ctxt =>
{
if (ctxt.Principal != null)
{
if (ctxt.Principal.Identity is ClaimsIdentity identity)
{
// Set common values
AuthClaims objAuthClaims = new AuthClaims();
var colClaims = await ctxt.Principal.Claims.ToDynamicListAsync();
objAuthClaims.IdentityProvider = colClaims.FirstOrDefault(
c => c.Type == "http://schemas.microsoft.com/identity/claims/identityprovider")?.Value;
objAuthClaims.Objectidentifier = colClaims.FirstOrDefault(
c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier")?.Value;
objAuthClaims.EmailAddress = colClaims.FirstOrDefault(
c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress")?.Value;
objAuthClaims.FirstName = colClaims.FirstOrDefault(
c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname")?.Value;
objAuthClaims.LastName = colClaims.FirstOrDefault(
c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname")?.Value;
objAuthClaims.AzureB2CFlow = colClaims.FirstOrDefault(
c => c.Type == "http://schemas.microsoft.com/claims/authnclassreference")?.Value;
objAuthClaims.auth_time = colClaims.FirstOrDefault(
c => c.Type == "auth_time")?.Value;
objAuthClaims.DisplayName = colClaims.FirstOrDefault(
c => c.Type == "name")?.Value;
objAuthClaims.idp_access_token = colClaims.FirstOrDefault(
c => c.Type == "idp_access_token")?.Value;
if (objAuthClaims.IdentityProvider != null)
{
// Google login
if (objAuthClaims.IdentityProvider.ToLower().Contains("google"))
{
objAuthClaims.AuthenticationType = "Google";
}
// Microsoft account login
if (objAuthClaims.IdentityProvider.ToLower().Contains("live"))
{
objAuthClaims.AuthenticationType = "Microsoft";
}
// Twitter login
if (objAuthClaims.IdentityProvider.ToLower().Contains("twitter"))
{
objAuthClaims.AuthenticationType = "Twitter";
}
}
// Azure Active Directory login
// But this will only work if Azure B2C Custom Policy is configured
// to pass the idp_access_token
// See \!AzureB2CConfig\TrustFrameworkExtensions.xml
// for an example that does that
if (objAuthClaims.idp_access_token != null)
{
objAuthClaims.AuthenticationType = "Azure Active Directory";
try
{
var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(objAuthClaims.idp_access_token);
objAuthClaims.EmailAddress = token.Claims.FirstOrDefault(c => c.Type == "upn")?.Value;
}
catch (System.Exception)
{
// Could not decode - do nothing
}
}
var request = ctxt.HttpContext.Request;
var host = request.Host.ToUriComponent();
// Insert into Database
var optionsBuilder = new DbContextOptionsBuilder<SimpleSurveyContext>();
optionsBuilder.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
SimpleSurveyContext _context = new SimpleSurveyContext(optionsBuilder.Options);
var ExistingUser = _context.Users
.Where(x => x.Objectidentifier == objAuthClaims.Objectidentifier)
.FirstOrDefault();
if (ExistingUser == null)
{
// New User
// Create User object
var objUser = new Users();
try
{
objUser.Objectidentifier = objAuthClaims.Objectidentifier;
objUser.AuthenticationType = objAuthClaims.AuthenticationType;
objUser.IdentityProvider = objAuthClaims.IdentityProvider;
objUser.SigninMethod = objAuthClaims.AzureB2CFlow;
objUser.DisplayName = objAuthClaims.DisplayName;
objUser.Email = objAuthClaims.EmailAddress;
objUser.FirstName = objAuthClaims.FirstName;
objUser.LastName = objAuthClaims.LastName;
objUser.LastAuthTime = Convert.ToInt32(objAuthClaims.auth_time);
objUser.LastidpAccessToken = objAuthClaims.idp_access_token;
objUser.LastIpaddress = host;
objUser.CreatedDate = DateTime.Now;
_context.Users.Add(objUser);
_context.SaveChanges();
// Write to Log
var objLogs = new Logs();
objLogs.LogType = "Login";
objLogs.LogDate = DateTime.Now;
objLogs.LogDetail = "New User";
objLogs.LogUserId = objUser.Id;
objLogs.LogIpaddress = host;
_context.Logs.Add(objLogs);
_context.SaveChanges();
}
catch (Exception ex)
{
// Write to Log
var objLogs = new Logs();
objLogs.LogType = "Login Error - New User";
objLogs.LogDate = DateTime.Now;
objLogs.LogDetail = String.Format($"User: {objUser.DisplayName} Objectidentifier: {objUser.Objectidentifier} Message: {ex.GetBaseException().Message}");
objLogs.LogIpaddress = host;
_context.Logs.Add(objLogs);
_context.SaveChanges();
}
}
else
{
// Update Existing User
try
{
ExistingUser.AuthenticationType = objAuthClaims.AuthenticationType;
ExistingUser.IdentityProvider = objAuthClaims.IdentityProvider;
ExistingUser.SigninMethod = objAuthClaims.AzureB2CFlow;
ExistingUser.DisplayName = objAuthClaims.DisplayName;
ExistingUser.Email = objAuthClaims.EmailAddress;
ExistingUser.FirstName = objAuthClaims.FirstName;
ExistingUser.LastName = objAuthClaims.LastName;
ExistingUser.LastAuthTime = Convert.ToInt32(objAuthClaims.auth_time);
ExistingUser.LastidpAccessToken = objAuthClaims.idp_access_token;
ExistingUser.LastIpaddress = host;
ExistingUser.UpdatedDate = DateTime.Now;
_context.SaveChanges();
// Write to Log
var objLogs = new Logs();
objLogs.LogType = "Login";
objLogs.LogDate = DateTime.Now;
objLogs.LogDetail = "Existing User";
objLogs.LogUserId = ExistingUser.Id;
objLogs.LogIpaddress = host;
_context.Logs.Add(objLogs);
_context.SaveChanges();
}
catch (Exception ex)
{
// Write to Log
var objLogs = new Logs();
objLogs.LogType = "Login Error - Existing User";
objLogs.LogDate = DateTime.Now;
objLogs.LogUserId = ExistingUser.Id;
objLogs.LogDetail = ex.GetBaseException().Message;
objLogs.LogIpaddress = host;
_context.Logs.Add(objLogs);
_context.SaveChanges();
}
}
}
}
await Task.Yield();
},
};
});
builder.Services.AddControllersWithViews()
.AddMicrosoftIdentityUI();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
app.Run();