Skip to content

Commit

Permalink
New setting 'WebBrowserAuthEnabled' added + readme updated + version …
Browse files Browse the repository at this point in the history
…updated to 1.4.1
  • Loading branch information
Myster-Tee committed Jun 15, 2023
1 parent 23f6864 commit 5d29cf1
Show file tree
Hide file tree
Showing 7 changed files with 88 additions and 52 deletions.
58 changes: 29 additions & 29 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,45 +20,45 @@ No requirements but heavyweight.

## TinfoilWebServer.config.json format

```jsonc
```js
{
"ServedDirectories": ["dir1", "dir2", ...], // ex: ["C:\\SomeDir\\DirWithPackages", "D:\\AnotherDir", "."] !!! Don't forget to escape backslashes with another one !!!
"StripDirectoryNames" : <boolean>, // «true» to remove directories names in URLs of served files, «false» otherwise.
"ServeEmptyDirectories" : <boolean>, // «true» to serve empty directories, «false» otherwise (has no effect when "StripDirectoryNames" is «true»).
"AllowedExt": ["ext1", "ext2", ...], // List of file extensions to serve, ex: [ "nsp", "nsz", "xci" ].
"MessageOfTheDay": "SomeText", // The welcome message displayed when Tinfoil successfully contacts the server.
"ExtraRepositories": ["SomeRepo1", ...], // A set of extra repositories sent to Tinfoil for scanning (see https://blawar.github.io/tinfoil/custom_index/ for more information).
"CacheExpiration": {
"Enable": boolean // «true» to enable cache expiration, «false» otherwise.
"ExpirationDelay" : "<duration>", // Index cache expiration time, format is «[d'.']hh':'mm':'ss['.'fffffff]», ex: "01:30:15" for 1h30m15s.
"ServedDirectories" : string[], // ex: ["C:\\SomeDir\\DirWithPackages", "D:\\AnotherDir", "."] !!! Don't forget to escape backslashes with another one !!!
"StripDirectoryNames" : boolean, // «true» to remove directories names in URLs of served files, «false» otherwise
"ServeEmptyDirectories" : boolean, // «true» to serve empty directories, «false» otherwise (has no effect when "StripDirectoryNames" is «true»)
"AllowedExt" : string[], // List of file extensions to serve, ex: [ "nsp", "nsz", "xci" ]
"MessageOfTheDay" : string, // The welcome message displayed when Tinfoil successfully contacts the server
"ExtraRepositories" : string[], // A set of extra repositories sent to Tinfoil for scanning (see https://blawar.github.io/tinfoil/custom_index/ for more information)
"CacheExpiration" : {
"Enable" : boolean , // «true» to enable cache expiration, «false» otherwise
"ExpirationDelay" : string, // Index cache expiration time, format is «[d'.']hh':'mm':'ss['.'fffffff]», ex: "01:30:15" for 1h30m15s
},
"Kestrel": { // HTTP server configuration see «https://docs.microsoft.com/fr-fr/aspnet/core/fundamentals/servers/kestrel?view=aspnetcore-5.0#configureiconfiguration» for more information.
"Endpoints": {
"Http": {
"Url": "http://0.0.0.0:80"
"Authentication" : {
"Enabled" : boolean, // «true» to enable authentication, «false» otherwise
"WebBrowserAuthEnabled" : boolean, // «true» to enable the native Web Browser login prompt when not authenticated (has no effect when "Authentication.Enabled" is «false»)
"Users" : [ // List of allowed users (use a comma as separator for declaring multiple users)
{
"Name" : string, // The user name
"Pwd" : string, // The password
"MessageOfTheDay" : string // Custom message for the user
}
]
},
"Kestrel" : { // HTTP server configuration see «https://docs.microsoft.com/fr-fr/aspnet/core/fundamentals/servers/kestrel?view=aspnetcore-6.0#configureiconfiguration» for more information
"Endpoints" : {
"Http" : {
"Url" : string // The IP addresses or host addresses with ports and protocols that the server should listen, ex: "http://0.0.0.0:80"
}
}
},
"Logging": {
"LogLevel": {
"Default": "Information" // See «https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-5.0» for more information.
"Logging" : { // See https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-6.0 for more information
"LogLevel" : {
"Default" : string // Can be one of "Trace", "Debug", "Information", "Warning", "Error", "Critical", or "None"
}
}
"Authentication": {
"Enabled": <boolean> // «true» to enable authentication, «false» otherwise.
"Users": [ // List of allowed users.
{
"Name": "SomeUserName",
"Pwd": "SomePassword",
"MessageOfTheDay" : "Some Text" // Custom message for the user
},
...
]
}
}
```

### Default settings
- When *"Kestrel"* configuration is omitted, server listens to *http://localhost:5000/* and *https://localhost:5001*.
- When *"ServedDirectories"* is omitted, current directory is used.
- When *"ServedDirectories"* is omitted, program directory is used.
- When *"AllowedExt"* is omitted, the following extensions *["xci", "nsz", "nsp"]* are used.
29 changes: 21 additions & 8 deletions TinfoilWebServer/Services/Authentication/BasicAuthMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using TinfoilWebServer.Settings;

namespace TinfoilWebServer.Services.Authentication;
Expand Down Expand Up @@ -42,6 +43,13 @@ private void OnAuthenticationSettingsChanged(object? sender, PropertyChangedEven
else
_logger.LogWarning($"Authentication disabled.");
}
else if (e.PropertyName == nameof(IAuthenticationSettings.WebBrowserAuthEnabled))
{
if (_authenticationSettings.WebBrowserAuthEnabled)
_logger.LogInformation($"Web browser authentication enabled.");
else
_logger.LogInformation($"Web browser authentication disabled.");
}
}

private void LoadAllowedUsers(bool isReload)
Expand Down Expand Up @@ -74,8 +82,7 @@ public async Task InvokeAsync(HttpContext context, RequestDelegate next)
if (headerValue == null)
{
_logger.LogDebug("Incoming request is missing authentication header.");
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
await context.Response.CompleteAsync();
await RespondUnauthorized(context);
return;
}

Expand All @@ -84,25 +91,22 @@ public async Task InvokeAsync(HttpContext context, RequestDelegate next)
if (strings.Length != 2)
{
_logger.LogDebug("Authorization header invalid, space separator missing.");
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
await context.Response.CompleteAsync();
await RespondUnauthorized(context);
return;
}

if (!string.Equals("Basic", strings[0], StringComparison.OrdinalIgnoreCase))
{
_logger.LogDebug($"Authentication is not basic, found \"{strings[0]}\".");
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
await context.Response.CompleteAsync();
await RespondUnauthorized(context);
return;
}

var base64IncomingAccount = strings[1];
if (!_allowedBase64Accounts.TryGetValue(base64IncomingAccount, out var allowedUser))
{
_logger.LogDebug($"Login or password incorrect.");
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
await context.Response.CompleteAsync();
await RespondUnauthorized(context);
return;
}

Expand All @@ -114,4 +118,13 @@ public async Task InvokeAsync(HttpContext context, RequestDelegate next)

}

private async Task RespondUnauthorized(HttpContext context)
{
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;

if (this._authenticationSettings.WebBrowserAuthEnabled)
context.Response.Headers.WWWAuthenticate = new StringValues("Basic");

await context.Response.CompleteAsync();
}
}
8 changes: 8 additions & 0 deletions TinfoilWebServer/Settings/AppSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ private void InitializeFromModel(AppSettingsModel appSettingsModel)

var authenticationSettings = appSettingsModel.Authentication;
_authenticationSettings.Enabled = authenticationSettings?.Enabled ?? false;
_authenticationSettings.WebBrowserAuthEnabled = authenticationSettings?.WebBrowserAuthEnabled ?? false;
_authenticationSettings.Users = (authenticationSettings?.Users ?? Array.Empty<AllowedUserModel>()).Select(model =>
new AllowedUser
{
Expand Down Expand Up @@ -114,13 +115,20 @@ private class AuthenticationSettings : NotifyPropertyChangedBase, IAuthenticatio
{
private bool _enabled;
private IReadOnlyList<IAllowedUser> _users = new List<IAllowedUser>();
private bool _webBrowserAuthEnabled;

public bool Enabled
{
get => _enabled;
set => SetField(ref _enabled, value);
}

public bool WebBrowserAuthEnabled
{
get => _webBrowserAuthEnabled;
set => SetField(ref _webBrowserAuthEnabled, value);
}

public IReadOnlyList<IAllowedUser> Users
{
get => _users;
Expand Down
2 changes: 2 additions & 0 deletions TinfoilWebServer/Settings/ConfigModels/AppSettingsModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ public class AuthenticationSettingsModel

public bool? Enabled { get; set; } = true;

public bool WebBrowserAuthEnabled { get; set; } = false;

public AllowedUserModel[]? Users { get; set; }

}
Expand Down
12 changes: 12 additions & 0 deletions TinfoilWebServer/Settings/IAppSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,20 @@ public interface ICacheExpirationSettings : INotifyPropertyChanged

public interface IAuthenticationSettings : INotifyPropertyChanged
{
/// <summary>
/// True to enable authentication, false otherwise
/// </summary>
public bool Enabled { get; }

/// <summary>
/// When true, a native web browser authentication popup is displayed when the user is not authenticated.
/// Only effective if <see cref="Enabled"/> is true.
/// </summary>
public bool WebBrowserAuthEnabled { get; }

/// <summary>
/// The list of allowed users
/// </summary>
public IReadOnlyList<IAllowedUser> Users { get; }
}

Expand Down
29 changes: 15 additions & 14 deletions TinfoilWebServer/TinfoilWebServer.config.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,21 @@
"AllowedExt": [ "nsp", "nsz", "xci" ],
"MessageOfTheDay": "Hello World!",
"ExtraRepositories": [],
"CacheExpiration": {
"Enabled": true,
"ExpirationDelay": "01:00:00"
},
"Authentication": {
"Enabled": false,
"WebBrowserAuthEnabled": true,
"Users": [
{
"Name": "JohnDoe",
"Pwd": "123456",
"MessageOfTheDay": "Hello JohnDoe!"
}
]
},
"Kestrel": {
"Endpoints": {
"Http": {
Expand All @@ -23,19 +38,5 @@
"FileSizeLimitBytes": 1000000,
"MaxRollingFiles": 10
}
},
"CacheExpiration": {
"Enabled": true,
"ExpirationDelay": "01:00:00"
},
"Authentication": {
"Enabled": false,
"Users": [
{
"Name": "JohnDoe",
"Pwd": "123456",
"MessageOfTheDay": "Hello JohnDoe!"
}
]
}
}
2 changes: 1 addition & 1 deletion TinfoilWebServer/TinfoilWebServer.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<UserSecretsId>437ef1a7-7fbd-490e-9580-9a3cf8c175d5</UserSecretsId>
<ApplicationIcon>Resources\Icon.ico</ApplicationIcon>
<StartupObject>TinfoilWebServer.Program</StartupObject>
<Version>1.4.0</Version>
<Version>1.4.1</Version>
</PropertyGroup>

<ItemGroup>
Expand Down

0 comments on commit 5d29cf1

Please sign in to comment.