📄
AdminAuthService.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
using System.Security.Claims; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.Extensions.Options; namespace BfiMonitor; public sealed class AdminAuthService( ILogger<AdminAuthService> logger, IOptions<AdminAuthOptions> options, TimeProvider timeProvider, IHttpContextAccessor httpContextAccessor ) { private readonly AdminAuthOptions authOptions = options.Value; public bool IsEnabled => !string.IsNullOrEmpty(authOptions.Hash); public bool ValidatePassword(string password) => BCrypt.Net.BCrypt.Verify(password, authOptions.Hash); public async Task SignInAsync() { if (httpContextAccessor.HttpContext is not { } httpContext) { logger.LogError("No HttpContext when signing in."); return; } var now = timeProvider.GetUtcNow(); var authProperties = new AuthenticationProperties { IsPersistent = true, AllowRefresh = true, IssuedUtc = now, ExpiresUtc = now + authOptions.LoginTime, }; await httpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal( new ClaimsIdentity( [new Claim(ClaimTypes.Role, "Admin")], CookieAuthenticationDefaults.AuthenticationScheme ) ), authProperties ); } public async Task SignOutAsync() { if (httpContextAccessor.HttpContext is not { } httpContext) { logger.LogError("No HttpContext when signing out."); return; } await httpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); } } public sealed class AdminAuthOptions { public string Hash { get; set; } = ""; public TimeSpan LoginTime { get; set; } = TimeSpan.FromDays(14); } public static class AdminAuthServiceCollectionExtensions { public static IServiceCollection AddAdminAuth(this IServiceCollection services, IConfiguration configuration) { services.AddOptions<AdminAuthOptions>().BindConfiguration("Admin"); services.AddHttpContextAccessor(); services.AddTransient<AdminAuthService>(); var authOptions = configuration.GetSection("Admin").Get<AdminAuthOptions>() ?? new AdminAuthOptions(); if (string.IsNullOrEmpty(authOptions.Hash)) { return services; } services .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.LoginPath = "/login.html"; options.LogoutPath = "/api/admin/logout"; options.AccessDeniedPath = "/login.html"; options.Cookie.Name = "BfiMonitor.AdminAuth"; options.SlidingExpiration = true; options.Events.OnRedirectToLogin = context => { if (context.Request.Path.Equals(LoginPath, StringComparison.OrdinalIgnoreCase)) { return Task.CompletedTask; } if (context.Request.Path.StartsWithSegments("/api")) { context.Response.StatusCode = StatusCodes.Status401Unauthorized; return Task.CompletedTask; } context.Response.Redirect(context.RedirectUri); return Task.CompletedTask; }; }); return services; } public static IApplicationBuilder UseAdminAuth(this IApplicationBuilder app) { var authOptions = app.ApplicationServices.GetRequiredService<IOptions<AdminAuthOptions>>().Value; if (string.IsNullOrEmpty(authOptions.Hash)) { return app; } app.UseAuthentication(); app.Use(RequireAdminForApi); return app; } public static IApplicationBuilder UseRequireAdminForApp(this IApplicationBuilder app) { var authOptions = app.ApplicationServices.GetRequiredService<IOptions<AdminAuthOptions>>().Value; if (string.IsNullOrEmpty(authOptions.Hash)) { return app; } app.Use(RequireAdminForAppContent); return app; } private static readonly PathString LoginPath = "/login.html"; private static bool IsPublicPath(PathString path) { if (path.Equals(LoginPath, StringComparison.OrdinalIgnoreCase)) { return true; } return path.Equals("/styles.css", StringComparison.OrdinalIgnoreCase); } private static bool IsAnonymousApiPath(PathString path) => path.StartsWithSegments("/api/auth", StringComparison.OrdinalIgnoreCase) || path.StartsWithSegments("/api/admin/login", StringComparison.OrdinalIgnoreCase) || path.StartsWithSegments("/api/admin/logout", StringComparison.OrdinalIgnoreCase); private static async Task RequireAdminForApi(HttpContext context, RequestDelegate next) { var path = context.Request.Path; if (!path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase) || IsAnonymousApiPath(path)) { await next(context); return; } if (!context.User.IsInRole("Admin")) { context.Response.StatusCode = StatusCodes.Status401Unauthorized; return; } await next(context); } private static Task RequireAdminForAppContent(HttpContext context, RequestDelegate next) { var path = context.Request.Path; if (IsPublicPath(path) || path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase)) { return next(context); } if (!context.User.IsInRole("Admin")) { context.Response.Redirect(LoginPath); return Task.CompletedTask; } return next(context); } } internal sealed record AdminLoginRequest(string Password);