Basic Auth
The BasicAuthModule provides lightweight HTTP Basic Authentication for SimpleW applications.
It allows you to protect one or more URL prefixes with username/password credentials, using a single middleware in the pipeline, no matter how many times the module is configured.
How It Works
Each call to SimpleWServer.UseBasicAuthModule() adds or updates a rule for a given URL prefix.
Internally:
- All rules are stored in a shared registry
- Only one middleware is installed per
SimpleWServer - Incoming requests are matched against registered prefixes
- The longest matching prefix is selected
- Authentication is enforced only for that prefix
Basic Usage
csharp
using System;
using System.Net;
using SimpleW;
namespace Sample {
class Program {
static async Task Main() {
var server = new SimpleWServer(IPAddress.Any, 2015);
// set basic auth module
server.UseBasicAuthModule(o => {
o.Prefix = "/api/test/hello";
o.Realm = "Admin";
o.Users = new[] { new BasicAuthModuleExtension.BasicAuthOptions.BasicUser("chef", "pwd") };
})
// set another basic auth module
.UseBasicAuthModule(o => {
o.Prefix = "/metrics";
o.Realm = "Metrics";
o.CredentialValidator = (u, p) => u == "prom" && p == "scrape";
});
server.MapControllers<Controller>("/api");
Console.WriteLine("server started at http://localhost:{server.Port}/");
await server.RunAsync();
}
}
public class SomeController : Controller {
[Route("GET", "/test")]
public object SomePublicMethod() {
return new {
message = "Hello World !"
};
}
}
}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
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
WARNING
- You should never expose BasicAuth over plain HTTP, but above HTTPS !
- Credentials are Base64-encoded, not encrypted.
