Skip to content

Commit 09aa6a3

Browse files
committed
sample project for net9.0 added
1 parent ba59794 commit 09aa6a3

File tree

8 files changed

+257
-1
lines changed

8 files changed

+257
-1
lines changed
Lines changed: 34 additions & 0 deletions
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

Lines changed: 157 additions & 0 deletions
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();
Lines changed: 21 additions & 0 deletions
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+
}
Lines changed: 19 additions & 0 deletions
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>
Lines changed: 8 additions & 0 deletions
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+
}
Lines changed: 9 additions & 0 deletions
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+
}

src/AspNetCore.Authentication.Basic.sln

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SampleWebApi_7_0", "..\samp
3838
EndProject
3939
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SampleWebApi_8_0", "..\samples\SampleWebApi_8_0\SampleWebApi_8_0.csproj", "{548DBE4A-0C06-4FB3-BEA6-6AB4A0386EEF}"
4040
EndProject
41+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SampleWebApi_9_0", "..\samples\SampleWebApi_9_0\SampleWebApi_9_0.csproj", "{53DBA160-9C57-4A01-A189-34FD4D052CD1}"
42+
EndProject
4143
Global
4244
GlobalSection(SolutionConfigurationPlatforms) = preSolution
4345
Debug|Any CPU = Debug|Any CPU
@@ -80,6 +82,10 @@ Global
8082
{548DBE4A-0C06-4FB3-BEA6-6AB4A0386EEF}.Debug|Any CPU.Build.0 = Debug|Any CPU
8183
{548DBE4A-0C06-4FB3-BEA6-6AB4A0386EEF}.Release|Any CPU.ActiveCfg = Release|Any CPU
8284
{548DBE4A-0C06-4FB3-BEA6-6AB4A0386EEF}.Release|Any CPU.Build.0 = Release|Any CPU
85+
{53DBA160-9C57-4A01-A189-34FD4D052CD1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
86+
{53DBA160-9C57-4A01-A189-34FD4D052CD1}.Debug|Any CPU.Build.0 = Debug|Any CPU
87+
{53DBA160-9C57-4A01-A189-34FD4D052CD1}.Release|Any CPU.ActiveCfg = Release|Any CPU
88+
{53DBA160-9C57-4A01-A189-34FD4D052CD1}.Release|Any CPU.Build.0 = Release|Any CPU
8389
EndGlobalSection
8490
GlobalSection(SolutionProperties) = preSolution
8591
HideSolutionNode = FALSE
@@ -94,13 +100,15 @@ Global
94100
{9232DA41-CA69-4FE3-B0C9-D8D85FEC272A} = {CF13271D-BF3F-4167-BEBA-DD02D33992F2}
95101
{D5C8BCC5-C997-475E-9E71-5BF807294BB6} = {CF13271D-BF3F-4167-BEBA-DD02D33992F2}
96102
{548DBE4A-0C06-4FB3-BEA6-6AB4A0386EEF} = {CF13271D-BF3F-4167-BEBA-DD02D33992F2}
103+
{53DBA160-9C57-4A01-A189-34FD4D052CD1} = {CF13271D-BF3F-4167-BEBA-DD02D33992F2}
97104
EndGlobalSection
98105
GlobalSection(ExtensibilityGlobals) = postSolution
99106
SolutionGuid = {70815049-1680-480A-BF5A-00536D6C9C20}
100107
EndGlobalSection
101108
GlobalSection(SharedMSBuildProjectFiles) = preSolution
102109
..\samples\SampleWebApi.Shared\SampleWebApi.Shared.projitems*{0801aed9-ea38-4e7e-af4d-26e9b67e5254}*SharedItemsImports = 5
103110
..\samples\SampleWebApi.Shared\SampleWebApi.Shared.projitems*{2705db4c-3bce-4cfc-9a30-b4bfd1f28c56}*SharedItemsImports = 5
111+
..\samples\SampleWebApi.Shared\SampleWebApi.Shared.projitems*{53dba160-9c57-4a01-a189-34fd4d052cd1}*SharedItemsImports = 5
104112
..\samples\SampleWebApi.Shared\SampleWebApi.Shared.projitems*{548dbe4a-0c06-4fb3-bea6-6ab4a0386eef}*SharedItemsImports = 5
105113
..\samples\SampleWebApi.Shared\SampleWebApi.Shared.projitems*{897e5c9c-8c0a-4fb6-960c-4d11aafd4491}*SharedItemsImports = 5
106114
..\samples\SampleWebApi.Shared\SampleWebApi.Shared.projitems*{9232da41-ca69-4fe3-b0c9-d8d85fec272a}*SharedItemsImports = 5

src/AspNetCore.Authentication.Basic/AspNetCore.Authentication.Basic.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<Project Sdk="Microsoft.NET.Sdk">
22

33
<PropertyGroup>
4-
<TargetFrameworks>net8.0;net8.0;net7.0;net6.0;net5.0;netcoreapp3.1;netcoreapp3.0;netstandard2.0;net461</TargetFrameworks>
4+
<TargetFrameworks>net9.0;net8.0;net7.0;net6.0;net5.0;netcoreapp3.1;netcoreapp3.0;netstandard2.0;net461</TargetFrameworks>
55
<Version>9.0.0</Version>
66
<RepositoryUrl>https://github.com/mihirdilip/aspnetcore-authentication-basic/tree/$(Version)</RepositoryUrl>
77
<PackageProjectUrl>https://github.com/mihirdilip/aspnetcore-authentication-basic/tree/$(Version)</PackageProjectUrl>

0 commit comments

Comments
 (0)