Skip to content

Commit e04025f

Browse files
authored
8.0.0 (#18)
- net8.0 support added - Sample project for net8.0 added - BasicSamplesClient.http file added for testing sample projects - Readme updated - Updated codeqa-analysis.xml
1 parent e261423 commit e04025f

29 files changed

+496
-125
lines changed

.github/workflows/codeql-analysis.yml

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,11 @@ jobs:
3535
- name: Setup .NET Core SDK
3636
uses: actions/setup-dotnet@v1.9.0
3737
with:
38-
dotnet-version: 7.0.100
38+
dotnet-version: 8.x.x
3939

4040
# Initializes the CodeQL tools for scanning.
4141
- name: Initialize CodeQL
42-
uses: github/codeql-action/init@v1
42+
uses: github/codeql-action/init@v2
4343
with:
4444
languages: ${{ matrix.language }}
4545
# If you wish to specify custom queries, you can do so here or in a config file.
@@ -50,7 +50,7 @@ jobs:
5050
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
5151
# If this step fails, then you should remove it and run the build manually (see below)
5252
- name: Autobuild
53-
uses: github/codeql-action/autobuild@v1
53+
uses: github/codeql-action/autobuild@v2
5454

5555
# ℹ️ Command-line programs to run using the OS shell.
5656
# 📚 https://git.io/JvXDl
@@ -64,4 +64,4 @@ jobs:
6464
# make release
6565

6666
- name: Perform CodeQL Analysis
67-
uses: github/codeql-action/analyze@v1
67+
uses: github/codeql-action/analyze@v2

LICENSE.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
MIT License
22

3-
Copyright (c) 2022 Mihir Dilip
3+
Copyright (c) 2024 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

Lines changed: 2 additions & 1 deletion
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: net7.0; net6.0; net5.0; netcoreapp3.1; netcoreapp3.0; netstandard2.0; net461
10+
Multi targeted: 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+
|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> |
303304
|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> |
304305
|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> |
305306
|5.1.0 | <ul><li>Visibility of the handler changed to public</li><li>Tests added</li><li>Readme updated</li><li>Copyright year updated on License</li></ul> |

samples/BasicSamplesClient.http

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
@HostAddress = https://localhost:44304
2+
@BasicHash = VGVzdFVzZXIxOjEyMzQ=
3+
4+
# Get Values No Auth
5+
GET {{HostAddress}}/api/values
6+
Accept: application/json
7+
8+
###
9+
10+
# Get Values
11+
GET {{HostAddress}}/api/values
12+
Accept: application/json
13+
Authorization: Basic {{BasicHash}}
14+
15+
###
16+
17+
# Claims
18+
GET {{HostAddress}}/api/values/claims
19+
Accept: application/json
20+
Authorization: Basic {{BasicHash}}
21+
22+
###
23+
24+
# Forbid
25+
GET {{HostAddress}}/api/values/forbid
26+
Accept: application/json
27+
Authorization: Basic {{BasicHash}}
Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
1-
namespace SampleWebApi.Models
1+
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
2+
namespace SampleWebApi.Models
23
{
34
/// <summary>
45
/// NOTE: DO NOT USE THIS IMPLEMENTATION. THIS IS FOR DEMO PURPOSE ONLY
56
/// </summary>
67
public class User
78
{
9+
810
public string Username { get; set; }
911
public string Password { get; set; }
1012
}
1113
}
14+
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.

samples/SampleWebApi.Shared/Repositories/InMemoryUserRepository.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
using System.Collections.Generic;
1+
#pragma warning disable CS8619 // Nullability of reference types in value doesn't match target type.
2+
using System.Collections.Generic;
23
using System.Linq;
34
using System.Threading.Tasks;
45
using SampleWebApi.Models;
@@ -10,7 +11,7 @@ namespace SampleWebApi.Repositories
1011
/// </summary>
1112
public class InMemoryUserRepository : IUserRepository
1213
{
13-
private List<User> _users = new List<User>
14+
private readonly List<User> _users = new List<User>
1415
{
1516
new User { Username = "TestUser1", Password = "1234" },
1617
new User { Username = "TestUser2", Password = "1234" },
@@ -30,3 +31,4 @@ public Task<IEnumerable<User>> GetUsers()
3031
}
3132
}
3233
}
34+
#pragma warning restore CS8619 // Nullability of reference types in value doesn't match target type.

samples/SampleWebApi_2_0/SampleWebApi_2_0.csproj

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
<PropertyGroup>
44
<TargetFramework>netcoreapp2.0</TargetFramework>
5+
<CheckEolTargetFramework>false</CheckEolTargetFramework>
6+
<NuGetAudit>false</NuGetAudit>
57
</PropertyGroup>
68

79
<ItemGroup>

samples/SampleWebApi_2_2/SampleWebApi_2_2.csproj

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
<PropertyGroup>
44
<TargetFramework>netcoreapp2.2</TargetFramework>
55
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
6+
<CheckEolTargetFramework>false</CheckEolTargetFramework>
7+
<NuGetAudit>false</NuGetAudit>
68
</PropertyGroup>
79

810
<ItemGroup>

samples/SampleWebApi_3_1/SampleWebApi_3_1.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
<PropertyGroup>
44
<TargetFramework>netcoreapp3.1</TargetFramework>
5+
<CheckEolTargetFramework>false</CheckEolTargetFramework>
56
</PropertyGroup>
67

78
<Import Project="..\SampleWebApi.Shared\SampleWebApi.Shared.projitems" Label="Shared" />

samples/SampleWebApi_5_0/SampleWebApi_5_0.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
<PropertyGroup>
44
<TargetFramework>net5.0</TargetFramework>
5+
<CheckEolTargetFramework>false</CheckEolTargetFramework>
56
</PropertyGroup>
67

78
<Import Project="..\SampleWebApi.Shared\SampleWebApi.Shared.projitems" Label="Shared" />
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
// This file is used by Code Analysis to maintain SuppressMessage
2+
// attributes that are applied to this project.
3+
// Project-level suppressions either have no target or are given
4+
// a specific target and scoped to a namespace, type, member, etc.
5+
6+
using System.Diagnostics.CodeAnalysis;
7+
8+
[assembly: SuppressMessage("Style", "IDE0090:Use 'new(...)'", Justification = "<Pending>", Scope = "member", Target = "~F:SampleWebApi.Repositories.InMemoryUserRepository._users")]
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_8_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_8_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": "http://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+
}

0 commit comments

Comments
 (0)