| | 1 | | using System.Text; |
| | 2 | | using Hangfire.Dashboard; |
| | 3 | | using Hangfire.Annotations; |
| | 4 | | using System.Net.Http.Headers; |
| | 5 | |
|
| | 6 | | namespace Syki.Daemon; |
| | 7 | |
|
| 1 | 8 | | public class HangfireAuthFilter(string user, string password) : IDashboardAuthorizationFilter |
| | 9 | | { |
| | 10 | | public bool Authorize([NotNull] DashboardContext context) |
| | 11 | | { |
| 3 | 12 | | var authHeader = context.GetHttpContext().Request.Headers.Authorization; |
| 3 | 13 | | return CheckAuth(authHeader) || Challenge(context); |
| | 14 | | } |
| | 15 | |
|
| | 16 | | private static bool Challenge([NotNull] DashboardContext context) |
| | 17 | | { |
| 2 | 18 | | context.GetHttpContext().Response.StatusCode = 401; |
| 2 | 19 | | context.GetHttpContext().Response.Headers.Append("WWW-Authenticate", "Basic realm=\"Hangfire Dashboard\""); |
| 2 | 20 | | return false; |
| | 21 | | } |
| | 22 | |
|
| | 23 | | private bool CheckAuth(string authHeader) |
| | 24 | | { |
| 4 | 25 | | if (authHeader.IsEmpty()) return false; |
| | 26 | |
|
| 2 | 27 | | var authValues = AuthenticationHeaderValue.Parse(authHeader); |
| 2 | 28 | | if ("Basic".Equals(authValues.Scheme, StringComparison.InvariantCultureIgnoreCase)) |
| | 29 | | { |
| 2 | 30 | | var parameter = Encoding.UTF8.GetString(Convert.FromBase64String(authValues.Parameter)); |
| 2 | 31 | | var parts = parameter.Split(':'); |
| 2 | 32 | | if (parts.Length > 1) |
| | 33 | | { |
| 2 | 34 | | return parts[0] == user && parts[1] == password; |
| | 35 | | } |
| | 36 | | } |
| 0 | 37 | | return false; |
| | 38 | | } |
| | 39 | | } |