Skip to content

Commit 0107cf6

Browse files
authored
Merge pull request #19 from mihirdilip/net9.0
9.0.0
2 parents e04025f + 8a387ad commit 0107cf6

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+653
-140
lines changed

.github/workflows/codeql-analysis.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ jobs:
3535
- name: Setup .NET Core SDK
3636
uses: actions/[email protected]
3737
with:
38-
dotnet-version: 8.x.x
38+
dotnet-version: 9.x.x
3939

4040
# Initializes the CodeQL tools for scanning.
4141
- name: Initialize CodeQL

LICENSE.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
MIT License
22

3-
Copyright (c) 2024 Mihir Dilip
3+
Copyright (c) 2025 Mihir Dilip
44

55
Permission is hereby granted, free of charge, to any person obtaining a copy
66
of this software and associated documentation files (the "Software"), to deal

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ Easy to use and very light weight Microsoft style Basic Scheme Authentication Im
77

88
## .NET (Core) Frameworks Supported
99
.NET Framework 4.6.1 and/or NetStandard 2.0 onwards
10-
Multi targeted: net8.0; net7.0; net6.0; net5.0; netcoreapp3.1; netcoreapp3.0; netstandard2.0; net461
10+
Multi targeted: net9.0; net8.0; net7.0; net6.0; net5.0; netcoreapp3.1; netcoreapp3.0; netstandard2.0; net461
1111

1212
<br/>
1313

@@ -300,6 +300,7 @@ public void ConfigureServices(IServiceCollection services)
300300
## Release Notes
301301
| Version | &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Notes |
302302
|---------|-------|
303+
|9.0.0 | <ul><li>net9.0 support added</li><li>Sample project for net9.0 added</li><li>Readme updated</li><li>Nullable reference types enabled</li><li>Language version set to latest</li><li>Implicit usings enabled</li><li>AOT support added</li></ul> |
303304
|8.0.0 | <ul><li>net8.0 support added</li><li>Sample project for net8.0 added</li><li>BasicSamplesClient.http file added for testing sample projects</li><li>Readme updated</li></ul> |
304305
|7.0.0 | <ul><li>net7.0 support added</li><li>Information log on handler is changed to Debug log when Authorization header is not found on the request</li><li>Added package validations</li><li>Sample project for net7.0 added</li><li>Readme updated</li><li>Readme added to package</li></ul> |
305306
|6.0.1 | <ul><li>net6.0 support added</li><li>Information log on handler is changed to Debug log when IgnoreAuthenticationIfAllowAnonymous is enabled [#9](https://github.com/mihirdilip/aspnetcore-authentication-basic/issues/9)</li><li>Sample project added</li><li>Readme updated</li><li>Copyright year updated on License</li></ul> |

samples/SampleWebApi_7_0/SampleWebApi_7_0.csproj

+1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
<TargetFramework>net7.0</TargetFramework>
55
<Nullable>enable</Nullable>
66
<ImplicitUsings>enable</ImplicitUsings>
7+
<CheckEolTargetFramework>false</CheckEolTargetFramework>
78
</PropertyGroup>
89

910
<Import Project="..\SampleWebApi.Shared\SampleWebApi.Shared.projitems" Label="Shared" />
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
using Microsoft.AspNetCore.Mvc;
2+
using System.Text;
3+
4+
namespace SampleWebApi_9_0.Controllers
5+
{
6+
[Route("api/[controller]")]
7+
[ApiController]
8+
public class ValuesController : ControllerBase
9+
{
10+
// GET api/values
11+
[HttpGet]
12+
public ActionResult<IEnumerable<string>> Get()
13+
{
14+
return new string[] { "value1", "value2" };
15+
}
16+
17+
[HttpGet("claims")]
18+
public ActionResult<string> Claims()
19+
{
20+
var sb = new StringBuilder();
21+
foreach (var claim in User.Claims)
22+
{
23+
sb.AppendLine($"{claim.Type}: {claim.Value}");
24+
}
25+
return sb.ToString();
26+
}
27+
28+
[HttpGet("forbid")]
29+
public new IActionResult Forbid()
30+
{
31+
return base.Forbid();
32+
}
33+
}
34+
}

samples/SampleWebApi_9_0/Program.cs

+157
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
using AspNetCore.Authentication.Basic;
2+
using Microsoft.AspNetCore.Authorization;
3+
using SampleWebApi.Repositories;
4+
using SampleWebApi.Services;
5+
6+
var builder = WebApplication.CreateBuilder(args);
7+
8+
// Add User repository to the dependency container.
9+
builder.Services.AddTransient<IUserRepository, InMemoryUserRepository>();
10+
11+
// Add the Basic scheme authentication here..
12+
// It requires Realm to be set in the options if SuppressWWWAuthenticateHeader is not set.
13+
// If an implementation of IBasicUserValidationService interface is registered in the dependency register as well as OnValidateCredentials delegete on options.Events is also set then this delegate will be used instead of an implementation of IBasicUserValidationService.
14+
builder.Services.AddAuthentication(BasicDefaults.AuthenticationScheme)
15+
16+
// The below AddBasic without type parameter will require OnValidateCredentials delegete on options.Events to be set unless an implementation of IBasicUserValidationService interface is registered in the dependency register.
17+
// Please note if both the delgate and validation server are set then the delegate will be used instead of BasicUserValidationService.
18+
//.AddBasic(options =>
19+
20+
// The below AddBasic with type parameter will add the BasicUserValidationService to the dependency register.
21+
// Please note if OnValidateCredentials delegete on options.Events is also set then this delegate will be used instead of BasicUserValidationService.
22+
.AddBasic<BasicUserValidationService>(options =>
23+
{
24+
options.Realm = "Sample Web API";
25+
26+
//// Optional option to suppress the browser login dialog for ajax calls.
27+
//options.SuppressWWWAuthenticateHeader = true;
28+
29+
//// Optional option to ignore authentication if AllowAnonumous metadata/filter attribute is added to an endpoint.
30+
//options.IgnoreAuthenticationIfAllowAnonymous = true;
31+
32+
//// Optional events to override the basic original logic with custom logic.
33+
//// Only use this if you know what you are doing at your own risk. Any of the events can be assigned.
34+
options.Events = new BasicEvents
35+
{
36+
37+
//// A delegate assigned to this property will be invoked just before validating credentials.
38+
//OnValidateCredentials = async (context) =>
39+
//{
40+
// // custom code to handle credentials, create principal and call Success method on context.
41+
// var userRepository = context.HttpContext.RequestServices.GetRequiredService<IUserRepository>();
42+
// var user = await userRepository.GetUserByUsername(context.Username);
43+
// var isValid = user != null && user.Password == context.Password;
44+
// if (isValid)
45+
// {
46+
// context.Response.Headers.Add("ValidationCustomHeader", "From OnValidateCredentials");
47+
// var claims = new[]
48+
// {
49+
// new Claim(ClaimTypes.NameIdentifier, context.Username, ClaimValueTypes.String, context.Options.ClaimsIssuer),
50+
// new Claim(ClaimTypes.Name, context.Username, ClaimValueTypes.String, context.Options.ClaimsIssuer),
51+
// new Claim("CustomClaimType", "Custom Claim Value - from OnValidateCredentials")
52+
// };
53+
// context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));
54+
// context.Success();
55+
// }
56+
// else
57+
// {
58+
// context.NoResult();
59+
// }
60+
//},
61+
62+
//// A delegate assigned to this property will be invoked just before validating credentials.
63+
//// NOTE: Same as above delegate but slightly different implementation which will give same result.
64+
//OnValidateCredentials = async (context) =>
65+
//{
66+
// // custom code to handle credentials, create principal and call Success method on context.
67+
// var userRepository = context.HttpContext.RequestServices.GetRequiredService<IUserRepository>();
68+
// var user = await userRepository.GetUserByUsername(context.Username);
69+
// var isValid = user != null && user.Password == context.Password;
70+
// if (isValid)
71+
// {
72+
// context.Response.Headers.Add("ValidationCustomHeader", "From OnValidateCredentials");
73+
// var claims = new[]
74+
// {
75+
// new Claim("CustomClaimType", "Custom Claim Value - from OnValidateCredentials")
76+
// };
77+
// context.ValidationSucceeded(claims); // claims are optional
78+
// }
79+
// else
80+
// {
81+
// context.ValidationFailed();
82+
// }
83+
//},
84+
85+
//// A delegate assigned to this property will be invoked before a challenge is sent back to the caller when handling unauthorized response.
86+
//OnHandleChallenge = async (context) =>
87+
//{
88+
// // custom code to handle authentication challenge unauthorized response.
89+
// context.Response.StatusCode = StatusCodes.Status401Unauthorized;
90+
// context.Response.Headers.Add("ChallengeCustomHeader", "From OnHandleChallenge");
91+
// await context.Response.WriteAsync("{\"CustomBody\":\"From OnHandleChallenge\"}");
92+
// context.Handled(); // important! do not forget to call this method at the end.
93+
//},
94+
95+
//// A delegate assigned to this property will be invoked if Authorization fails and results in a Forbidden response.
96+
//OnHandleForbidden = async (context) =>
97+
//{
98+
// // custom code to handle forbidden response.
99+
// context.Response.StatusCode = StatusCodes.Status403Forbidden;
100+
// context.Response.Headers.Add("ForbidCustomHeader", "From OnHandleForbidden");
101+
// await context.Response.WriteAsync("{\"CustomBody\":\"From OnHandleForbidden\"}");
102+
// context.Handled(); // important! do not forget to call this method at the end.
103+
//},
104+
105+
//// A delegate assigned to this property will be invoked when the authentication succeeds. It will not be called if OnValidateCredentials delegate is assigned.
106+
//// It can be used for adding claims, headers, etc to the response.
107+
//OnAuthenticationSucceeded = (context) =>
108+
//{
109+
// //custom code to add extra bits to the success response.
110+
// context.Response.Headers.Add("SuccessCustomHeader", "From OnAuthenticationSucceeded");
111+
// var customClaims = new List<Claim>
112+
// {
113+
// new Claim("CustomClaimType", "Custom Claim Value - from OnAuthenticationSucceeded")
114+
// };
115+
// context.AddClaims(customClaims);
116+
// //or can add like this - context.Principal.AddIdentity(new ClaimsIdentity(customClaims));
117+
// return Task.CompletedTask;
118+
//},
119+
120+
//// A delegate assigned to this property will be invoked when the authentication fails.
121+
//OnAuthenticationFailed = (context) =>
122+
//{
123+
// // custom code to handle failed authentication.
124+
// context.Fail("Failed to authenticate");
125+
// return Task.CompletedTask;
126+
//}
127+
128+
};
129+
});
130+
131+
builder.Services.AddControllers(options =>
132+
{
133+
// ALWAYS USE HTTPS (SSL) protocol in production when using ApiKey authentication.
134+
//options.Filters.Add<RequireHttpsAttribute>();
135+
136+
}); //.AddXmlSerializerFormatters() // To enable XML along with JSON;
137+
138+
// All the requests will need to be authorized.
139+
// Alternatively, add [Authorize] attribute to Controller or Action Method where necessary.
140+
builder.Services.AddAuthorizationBuilder()
141+
.SetFallbackPolicy(
142+
new AuthorizationPolicyBuilder()
143+
.RequireAuthenticatedUser()
144+
.Build()
145+
);
146+
147+
var app = builder.Build();
148+
149+
app.UseHttpsRedirection();
150+
151+
app.UseAuthentication(); // NOTE: DEFAULT TEMPLATE DOES NOT HAVE THIS, THIS LINE IS REQUIRED AND HAS TO BE ADDED!!!
152+
153+
app.UseAuthorization();
154+
155+
app.MapControllers();
156+
157+
app.Run();
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
{
2+
"$schema": "https://json.schemastore.org/launchsettings.json",
3+
"iisSettings": {
4+
"windowsAuthentication": false,
5+
"anonymousAuthentication": true,
6+
"iisExpress": {
7+
"applicationUrl": "http://localhost:3920",
8+
"sslPort": 44304
9+
}
10+
},
11+
"profiles": {
12+
"IIS Express": {
13+
"commandName": "IISExpress",
14+
"launchBrowser": true,
15+
"launchUrl": "api/values",
16+
"environmentVariables": {
17+
"ASPNETCORE_ENVIRONMENT": "Development"
18+
}
19+
}
20+
}
21+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<Project Sdk="Microsoft.NET.Sdk.Web">
2+
3+
<PropertyGroup>
4+
<TargetFramework>net9.0</TargetFramework>
5+
<Nullable>enable</Nullable>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
</PropertyGroup>
8+
9+
<Import Project="..\SampleWebApi.Shared\SampleWebApi.Shared.projitems" Label="Shared" />
10+
11+
<ItemGroup>
12+
<PackageReference Include="AspNetCore.Authentication.Basic" Version="9.0.0" />
13+
</ItemGroup>
14+
15+
<!--<ItemGroup>
16+
<ProjectReference Include="..\..\src\AspNetCore.Authentication.Basic\AspNetCore.Authentication.Basic.csproj" />
17+
</ItemGroup>-->
18+
19+
</Project>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"Logging": {
3+
"LogLevel": {
4+
"Default": "Information",
5+
"Microsoft.AspNetCore": "Warning"
6+
}
7+
}
8+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"Logging": {
3+
"LogLevel": {
4+
"Default": "Information",
5+
"Microsoft.AspNetCore": "Warning"
6+
}
7+
},
8+
"AllowedHosts": "*"
9+
}

0 commit comments

Comments
 (0)