-
Notifications
You must be signed in to change notification settings - Fork 43
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge branch 'master' into dependabot/npm_and_yarn/src/Serilog.Ui.Web…
…/babel/traverse-7.23.2
- Loading branch information
Showing
4 changed files
with
169 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
88 changes: 88 additions & 0 deletions
88
src/Serilog.Ui.Web/Authorization/BasicAuthenticationFilter.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
using Microsoft.AspNetCore.Http; | ||
using System; | ||
using System.Net.Http.Headers; | ||
using System.Security.Cryptography; | ||
using System.Text; | ||
|
||
namespace Serilog.Ui.Web.Authorization; | ||
|
||
public class BasicAuthenticationFilter : IUiAuthorizationFilter | ||
{ | ||
private const string AuthenticationScheme = "Basic"; | ||
internal const string AuthenticationCookieName = "SerilogAuth"; | ||
|
||
public string UserName { get; set; } | ||
|
||
public string Password { get; set; } | ||
|
||
public bool Authorize(HttpContext httpContext) | ||
{ | ||
var header = httpContext.Request.Headers["Authorization"]; | ||
var isAuthenticated = false; | ||
|
||
if (header == "null" || string.IsNullOrEmpty(header)) | ||
{ | ||
var authCookie = httpContext.Request.Cookies[AuthenticationCookieName]; | ||
if (!string.IsNullOrWhiteSpace(authCookie)) | ||
{ | ||
var hashedCredentials = EncryptCredentials(UserName, Password); | ||
isAuthenticated = authCookie.Equals(hashedCredentials, StringComparison.OrdinalIgnoreCase); | ||
} | ||
} | ||
else | ||
{ | ||
var authValues = AuthenticationHeaderValue.Parse(header); | ||
|
||
if (IsBasicAuthentication(authValues)) | ||
{ | ||
var tokens = ExtractAuthenticationTokens(authValues); | ||
|
||
if (CredentialsMatch(tokens)) | ||
{ | ||
isAuthenticated = true; | ||
var hashedCredentials = EncryptCredentials(UserName, Password); | ||
httpContext.Response.Cookies.Append(AuthenticationCookieName, hashedCredentials); | ||
} | ||
} | ||
} | ||
|
||
if (!isAuthenticated) | ||
{ | ||
SetChallengeResponse(httpContext); | ||
} | ||
|
||
return isAuthenticated; | ||
} | ||
|
||
private string EncryptCredentials(string user, string pass) | ||
{ | ||
using var sha256 = SHA256.Create(); | ||
var hashBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes($"{user}:{pass}")); | ||
var hashedCredentials = BitConverter.ToString(hashBytes).Replace("-", "").ToLower(); | ||
return hashedCredentials; | ||
} | ||
|
||
private static bool IsBasicAuthentication(AuthenticationHeaderValue authValues) | ||
{ | ||
return AuthenticationScheme.Equals(authValues.Scheme, StringComparison.InvariantCultureIgnoreCase); | ||
} | ||
|
||
private static (string, string) ExtractAuthenticationTokens(AuthenticationHeaderValue authValues) | ||
{ | ||
var parameter = Encoding.UTF8.GetString(Convert.FromBase64String(authValues.Parameter)); | ||
var parts = parameter.Split(':'); | ||
return (parts[0], parts[1]); | ||
} | ||
|
||
private bool CredentialsMatch((string Username, string Password) tokens) | ||
{ | ||
return tokens.Username == UserName && tokens.Password == Password; | ||
} | ||
|
||
private void SetChallengeResponse(HttpContext httpContext) | ||
{ | ||
httpContext.Response.StatusCode = 401; | ||
httpContext.Response.Headers.Append("WWW-Authenticate", "Basic realm=\"Serilog UI\""); | ||
httpContext.Response.WriteAsync("Authentication is required."); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
74 changes: 74 additions & 0 deletions
74
tests/Serilog.Ui.Web.Tests/Authorization/BasicAuthenticationFilterTests.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
using System.Linq; | ||
using FluentAssertions; | ||
using Microsoft.AspNetCore.Http; | ||
using Microsoft.Net.Http.Headers; | ||
using System.Threading.Tasks; | ||
using Xunit; | ||
|
||
namespace Serilog.Ui.Web.Authorization.Tests; | ||
|
||
public class BasicAuthenticationFilterTests | ||
{ | ||
[Fact] | ||
public async Task Authorize_WithValidCredentials_ShouldReturnTrue() | ||
{ | ||
// Arrange | ||
var filter = new BasicAuthenticationFilter | ||
{ | ||
UserName = "User", | ||
Password = "P@ss" | ||
}; | ||
|
||
var httpContext = new DefaultHttpContext(); | ||
httpContext.Request.Headers["Authorization"] = "Basic VXNlcjpQQHNz"; // Base64 encoded "User:P@ss" | ||
|
||
// Act | ||
var result = filter.Authorize(httpContext); | ||
var authCookie = httpContext.Response.GetTypedHeaders().SetCookie.FirstOrDefault(sc => sc.Name == BasicAuthenticationFilter.AuthenticationCookieName); | ||
|
||
// Assert | ||
result.Should().BeTrue(); | ||
authCookie.Should().NotBeNull(); | ||
} | ||
|
||
[Fact] | ||
public async Task Authorize_WithInvalidCredentials_ShouldReturnFalse() | ||
{ | ||
// Arrange | ||
var filter = new BasicAuthenticationFilter | ||
{ | ||
UserName = "User", | ||
Password = "P@ss" | ||
}; | ||
|
||
var httpContext = new DefaultHttpContext(); | ||
httpContext.Request.Headers["Authorization"] = "Basic QWRtaW46dXNlcg=="; // Base64 encoded "Admin:user" | ||
|
||
// Act | ||
var result = filter.Authorize(httpContext); | ||
|
||
// Assert | ||
result.Should().BeFalse(); | ||
} | ||
|
||
[Fact] | ||
public async Task Authorize_WithMissingAuthorizationHeader_ShouldSetChallengeResponse() | ||
{ | ||
// Arrange | ||
var filter = new BasicAuthenticationFilter | ||
{ | ||
UserName = "User", | ||
Password = "P@ss" | ||
}; | ||
|
||
var httpContext = new DefaultHttpContext(); | ||
|
||
// Act | ||
var result = filter.Authorize(httpContext); | ||
|
||
// Assert | ||
result.Should().BeFalse(); | ||
httpContext.Response.StatusCode.Should().Be(401); | ||
httpContext.Response.Headers[HeaderNames.WWWAuthenticate].Should().Contain("Basic realm=\"Serilog UI\""); | ||
} | ||
} |