-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
157 lines (131 loc) · 4.35 KB
/
Program.cs
File metadata and controls
157 lines (131 loc) · 4.35 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
using FogelFormedlingenAB.Controllers;
using FogelFormedlingenAB.Data;
using FogelFormedlingenAB.Models;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using System.Security.Claims;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = "Google";
})
.AddCookie(options =>
{
// When a user logs in to Google for the first time, create a local account for that user in our database.
options.Events.OnValidatePrincipal += async context =>
{
var serviceProvider = context.HttpContext.RequestServices;
using var db = new AppDbContext(serviceProvider.GetRequiredService<DbContextOptions<AppDbContext>>());
string subject = context.Principal.FindFirstValue(ClaimTypes.NameIdentifier);
string issuer = context.Principal.FindFirst(ClaimTypes.NameIdentifier).Issuer;
string name = context.Principal.FindFirst(ClaimTypes.Name)?.Value;
if (name.IsNullOrEmpty())
{
name = context.Principal.FindFirst("name").Value;
}
var account = db.Accounts
.FirstOrDefault(p => p.OpenIDIssuer == issuer && p.OpenIDSubject == subject);
if (account == null)
{
account = new Account
{
OpenIDIssuer = issuer,
OpenIDSubject = subject,
Name = name,
Phonenumber = " ",
Email = " "
};
db.Accounts.Add(account);
}
else
{
// If the account already exists, just update the name in case it has changed. asdasd
account.Name = name;
}
await db.SaveChangesAsync();
};
})
.AddOpenIdConnect("Google", options =>
{
options.Authority = "https://accounts.google.com";
/*
These two values (client ID and client secret) must be created in the Google Cloud Platform Console:
https://support.google.com/cloud/answer/6158849?hl=en
They must then be added to the project's "user secrets": right-click the project in Visual Studio and select "Manage User Secrets" and write the following JSON:
{
"Authentication": {
"Google": {
"ClientId": "...",
"ClientSecret": "..."
}
}
}
*/
options.ClientId = builder.Configuration["Authentication:Google:ClientId"];
options.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"];
options.ResponseType = OpenIdConnectResponseType.Code;
options.CallbackPath = "/signin-oidc-google";
options.SignedOutCallbackPath = "/signout-callback-oidc-google";
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("email");
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.Events.OnSignedOutCallbackRedirect = context =>
{
context.Response.Redirect("/Index");
context.HandleResponse();
return Task.CompletedTask;
};
});
builder.Services.AddAuthorization(options =>
{
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
});
builder.Services.AddRazorPages().AddRazorRuntimeCompilation();
builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<AccessControl>();
builder.Services.AddScoped<APIController>();
builder.Services.AddLogging(logging =>
{
logging.AddConsole();
});
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages();
app.MapControllers();
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
var context = services.GetRequiredService<AppDbContext>();
SampleData.CreateCategorys(context);
SampleData.CreateAccounts(context);
// Method to automatically load SampleData when we run our application
var apiController = services.GetRequiredService<APIController>();
await apiController.AddSampleData();
}
app.Run();