Skip to content

Commit

Permalink
8.0.0 (#18)
Browse files Browse the repository at this point in the history
- net8.0 support added
- Sample project for net8.0 added
- BasicSamplesClient.http file added for testing sample projects
- Readme updated
- Updated codeqa-analysis.xml
  • Loading branch information
mihirdilip authored Feb 12, 2024
1 parent e261423 commit e04025f
Show file tree
Hide file tree
Showing 29 changed files with 496 additions and 125 deletions.
8 changes: 4 additions & 4 deletions .github/workflows/codeql-analysis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,11 @@ jobs:
- name: Setup .NET Core SDK
uses: actions/setup-dotnet@v1.9.0
with:
dotnet-version: 7.0.100
dotnet-version: 8.x.x

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

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

- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1
uses: github/codeql-action/analyze@v2
2 changes: 1 addition & 1 deletion LICENSE.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2022 Mihir Dilip
Copyright (c) 2024 Mihir Dilip

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ Easy to use and very light weight Microsoft style Basic Scheme Authentication Im

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

<br/>

Expand Down Expand Up @@ -300,6 +300,7 @@ public void ConfigureServices(IServiceCollection services)
## Release Notes
| Version | &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Notes |
|---------|-------|
|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> |
|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> |
|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> |
|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> |
Expand Down
27 changes: 27 additions & 0 deletions samples/BasicSamplesClient.http
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
@HostAddress = https://localhost:44304
@BasicHash = VGVzdFVzZXIxOjEyMzQ=

# Get Values No Auth
GET {{HostAddress}}/api/values
Accept: application/json

###

# Get Values
GET {{HostAddress}}/api/values
Accept: application/json
Authorization: Basic {{BasicHash}}

###

# Claims
GET {{HostAddress}}/api/values/claims
Accept: application/json
Authorization: Basic {{BasicHash}}

###

# Forbid
GET {{HostAddress}}/api/values/forbid
Accept: application/json
Authorization: Basic {{BasicHash}}
5 changes: 4 additions & 1 deletion samples/SampleWebApi.Shared/Models/User.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
namespace SampleWebApi.Models
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
namespace SampleWebApi.Models
{
/// <summary>
/// NOTE: DO NOT USE THIS IMPLEMENTATION. THIS IS FOR DEMO PURPOSE ONLY
/// </summary>
public class User
{

public string Username { get; set; }
public string Password { get; set; }
}
}
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections.Generic;
#pragma warning disable CS8619 // Nullability of reference types in value doesn't match target type.
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SampleWebApi.Models;
Expand All @@ -10,7 +11,7 @@ namespace SampleWebApi.Repositories
/// </summary>
public class InMemoryUserRepository : IUserRepository
{
private List<User> _users = new List<User>
private readonly List<User> _users = new List<User>
{
new User { Username = "TestUser1", Password = "1234" },
new User { Username = "TestUser2", Password = "1234" },
Expand All @@ -30,3 +31,4 @@ public Task<IEnumerable<User>> GetUsers()
}
}
}
#pragma warning restore CS8619 // Nullability of reference types in value doesn't match target type.
2 changes: 2 additions & 0 deletions samples/SampleWebApi_2_0/SampleWebApi_2_0.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<CheckEolTargetFramework>false</CheckEolTargetFramework>
<NuGetAudit>false</NuGetAudit>
</PropertyGroup>

<ItemGroup>
Expand Down
2 changes: 2 additions & 0 deletions samples/SampleWebApi_2_2/SampleWebApi_2_2.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
<CheckEolTargetFramework>false</CheckEolTargetFramework>
<NuGetAudit>false</NuGetAudit>
</PropertyGroup>

<ItemGroup>
Expand Down
1 change: 1 addition & 0 deletions samples/SampleWebApi_3_1/SampleWebApi_3_1.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<CheckEolTargetFramework>false</CheckEolTargetFramework>
</PropertyGroup>

<Import Project="..\SampleWebApi.Shared\SampleWebApi.Shared.projitems" Label="Shared" />
Expand Down
1 change: 1 addition & 0 deletions samples/SampleWebApi_5_0/SampleWebApi_5_0.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<CheckEolTargetFramework>false</CheckEolTargetFramework>
</PropertyGroup>

<Import Project="..\SampleWebApi.Shared\SampleWebApi.Shared.projitems" Label="Shared" />
Expand Down
8 changes: 8 additions & 0 deletions samples/SampleWebApi_6_0/GlobalSuppressions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.

using System.Diagnostics.CodeAnalysis;

[assembly: SuppressMessage("Style", "IDE0090:Use 'new(...)'", Justification = "<Pending>", Scope = "member", Target = "~F:SampleWebApi.Repositories.InMemoryUserRepository._users")]
34 changes: 34 additions & 0 deletions samples/SampleWebApi_8_0/Controllers/ValuesController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using Microsoft.AspNetCore.Mvc;
using System.Text;

namespace SampleWebApi_8_0.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}

[HttpGet("claims")]
public ActionResult<string> Claims()
{
var sb = new StringBuilder();
foreach (var claim in User.Claims)
{
sb.AppendLine($"{claim.Type}: {claim.Value}");
}
return sb.ToString();
}

[HttpGet("forbid")]
public new IActionResult Forbid()
{
return base.Forbid();
}
}
}
157 changes: 157 additions & 0 deletions samples/SampleWebApi_8_0/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
using AspNetCore.Authentication.Basic;
using Microsoft.AspNetCore.Authorization;
using SampleWebApi.Repositories;
using SampleWebApi.Services;

var builder = WebApplication.CreateBuilder(args);

// Add User repository to the dependency container.
builder.Services.AddTransient<IUserRepository, InMemoryUserRepository>();

// Add the Basic scheme authentication here..
// It requires Realm to be set in the options if SuppressWWWAuthenticateHeader is not set.
// 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.
builder.Services.AddAuthentication(BasicDefaults.AuthenticationScheme)

// 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.
// Please note if both the delgate and validation server are set then the delegate will be used instead of BasicUserValidationService.
//.AddBasic(options =>

// The below AddBasic with type parameter will add the BasicUserValidationService to the dependency register.
// Please note if OnValidateCredentials delegete on options.Events is also set then this delegate will be used instead of BasicUserValidationService.
.AddBasic<BasicUserValidationService>(options =>
{
options.Realm = "Sample Web API";
//// Optional option to suppress the browser login dialog for ajax calls.
//options.SuppressWWWAuthenticateHeader = true;
//// Optional option to ignore authentication if AllowAnonumous metadata/filter attribute is added to an endpoint.
//options.IgnoreAuthenticationIfAllowAnonymous = true;
//// Optional events to override the basic original logic with custom logic.
//// Only use this if you know what you are doing at your own risk. Any of the events can be assigned.
options.Events = new BasicEvents
{
//// A delegate assigned to this property will be invoked just before validating credentials.
//OnValidateCredentials = async (context) =>
//{
// // custom code to handle credentials, create principal and call Success method on context.
// var userRepository = context.HttpContext.RequestServices.GetRequiredService<IUserRepository>();
// var user = await userRepository.GetUserByUsername(context.Username);
// var isValid = user != null && user.Password == context.Password;
// if (isValid)
// {
// context.Response.Headers.Add("ValidationCustomHeader", "From OnValidateCredentials");
// var claims = new[]
// {
// new Claim(ClaimTypes.NameIdentifier, context.Username, ClaimValueTypes.String, context.Options.ClaimsIssuer),
// new Claim(ClaimTypes.Name, context.Username, ClaimValueTypes.String, context.Options.ClaimsIssuer),
// new Claim("CustomClaimType", "Custom Claim Value - from OnValidateCredentials")
// };
// context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));
// context.Success();
// }
// else
// {
// context.NoResult();
// }
//},
//// A delegate assigned to this property will be invoked just before validating credentials.
//// NOTE: Same as above delegate but slightly different implementation which will give same result.
//OnValidateCredentials = async (context) =>
//{
// // custom code to handle credentials, create principal and call Success method on context.
// var userRepository = context.HttpContext.RequestServices.GetRequiredService<IUserRepository>();
// var user = await userRepository.GetUserByUsername(context.Username);
// var isValid = user != null && user.Password == context.Password;
// if (isValid)
// {
// context.Response.Headers.Add("ValidationCustomHeader", "From OnValidateCredentials");
// var claims = new[]
// {
// new Claim("CustomClaimType", "Custom Claim Value - from OnValidateCredentials")
// };
// context.ValidationSucceeded(claims); // claims are optional
// }
// else
// {
// context.ValidationFailed();
// }
//},
//// A delegate assigned to this property will be invoked before a challenge is sent back to the caller when handling unauthorized response.
//OnHandleChallenge = async (context) =>
//{
// // custom code to handle authentication challenge unauthorized response.
// context.Response.StatusCode = StatusCodes.Status401Unauthorized;
// context.Response.Headers.Add("ChallengeCustomHeader", "From OnHandleChallenge");
// await context.Response.WriteAsync("{\"CustomBody\":\"From OnHandleChallenge\"}");
// context.Handled(); // important! do not forget to call this method at the end.
//},
//// A delegate assigned to this property will be invoked if Authorization fails and results in a Forbidden response.
//OnHandleForbidden = async (context) =>
//{
// // custom code to handle forbidden response.
// context.Response.StatusCode = StatusCodes.Status403Forbidden;
// context.Response.Headers.Add("ForbidCustomHeader", "From OnHandleForbidden");
// await context.Response.WriteAsync("{\"CustomBody\":\"From OnHandleForbidden\"}");
// context.Handled(); // important! do not forget to call this method at the end.
//},
//// A delegate assigned to this property will be invoked when the authentication succeeds. It will not be called if OnValidateCredentials delegate is assigned.
//// It can be used for adding claims, headers, etc to the response.
//OnAuthenticationSucceeded = (context) =>
//{
// //custom code to add extra bits to the success response.
// context.Response.Headers.Add("SuccessCustomHeader", "From OnAuthenticationSucceeded");
// var customClaims = new List<Claim>
// {
// new Claim("CustomClaimType", "Custom Claim Value - from OnAuthenticationSucceeded")
// };
// context.AddClaims(customClaims);
// //or can add like this - context.Principal.AddIdentity(new ClaimsIdentity(customClaims));
// return Task.CompletedTask;
//},
//// A delegate assigned to this property will be invoked when the authentication fails.
//OnAuthenticationFailed = (context) =>
//{
// // custom code to handle failed authentication.
// context.Fail("Failed to authenticate");
// return Task.CompletedTask;
//}
};
});

builder.Services.AddControllers(options =>
{
// ALWAYS USE HTTPS (SSL) protocol in production when using ApiKey authentication.
//options.Filters.Add<RequireHttpsAttribute>();
}); //.AddXmlSerializerFormatters() // To enable XML along with JSON;

// All the requests will need to be authorized.
// Alternatively, add [Authorize] attribute to Controller or Action Method where necessary.
builder.Services.AddAuthorizationBuilder()
.SetFallbackPolicy(
new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build()
);

var app = builder.Build();

app.UseHttpsRedirection();

app.UseAuthentication(); // NOTE: DEFAULT TEMPLATE DOES NOT HAVE THIS, THIS LINE IS REQUIRED AND HAS TO BE ADDED!!!

app.UseAuthorization();

app.MapControllers();

app.Run();
21 changes: 21 additions & 0 deletions samples/SampleWebApi_8_0/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:3920",
"sslPort": 44304
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "api/values",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
Loading

0 comments on commit e04025f

Please sign in to comment.