Skip to content

Commit

Permalink
Merge pull request #10 from mihirdilip/6.0.1
Browse files Browse the repository at this point in the history
- net6.0 support added
  • Loading branch information
mihirdilip authored Jan 7, 2022
2 parents ce690a6 + 76cb7a3 commit b0fadfd
Show file tree
Hide file tree
Showing 13 changed files with 413 additions and 20 deletions.
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) 2021 Mihir Dilip
Copyright (c) 2022 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: net5.0; netcoreapp3.1; netcoreapp3.0; netstandard2.0; net461
Multi targeted: 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 |
|---------|-------|
|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> |
|5.0.0 | <ul><li>Net 5.0 target framework added</li><li>IgnoreAuthenticationIfAllowAnonymous added to the BasicOptions from netcoreapp3.0 onwards</li></ul> |
|3.1.1 | <ul><li>Fixed issue with resolving of IBasicUserValidationService implementation when using multiple schemes</li></ul> |
Expand Down
127 changes: 127 additions & 0 deletions samples/BasicSamplesClient.postman_collection.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
{
"info": {
"_postman_id": "0d733eba-f9ef-4512-aacc-a10711586767",
"name": "BasicSamplesClient",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "Get Values No Auth",
"request": {
"auth": {
"type": "noauth"
},
"method": "GET",
"header": [],
"url": {
"raw": "{{base_url}}/api/values",
"host": [
"{{base_url}}"
],
"path": [
"api",
"values"
]
}
},
"response": []
},
{
"name": "Get Values",
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "{{base_url}}/api/values",
"host": [
"{{base_url}}"
],
"path": [
"api",
"values"
]
}
},
"response": []
},
{
"name": "Claims",
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "{{base_url}}/api/values/claims",
"host": [
"{{base_url}}"
],
"path": [
"api",
"values",
"claims"
]
}
},
"response": []
},
{
"name": "Forbid",
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "{{base_url}}/api/values/forbid",
"host": [
"{{base_url}}"
],
"path": [
"api",
"values",
"forbid"
]
}
},
"response": []
}
],
"auth": {
"type": "basic",
"basic": [
{
"key": "password",
"value": "1234",
"type": "string"
},
{
"key": "username",
"value": "TestUser1",
"type": "string"
}
]
},
"event": [
{
"listen": "prerequest",
"script": {
"type": "text/javascript",
"exec": [
""
]
}
},
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
""
]
}
}
],
"variable": [
{
"key": "base_url",
"value": "https://localhost:44304/"
}
]
}
34 changes: 34 additions & 0 deletions samples/SampleWebApi_6_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_6_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_6_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.AddAuthorization(options =>
{
options.FallbackPolicy = 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_6_0/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"$schema": "https://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"
}
}
}
}
18 changes: 18 additions & 0 deletions samples/SampleWebApi_6_0/SampleWebApi_6_0.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

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

<ItemGroup>
<PackageReference Include="AspNetCore.Authentication.Basic" Version="6.0.1" />
</ItemGroup>

<!--<ItemGroup>
<ProjectReference Include="..\..\src\AspNetCore.Authentication.Basic\AspNetCore.Authentication.Basic.csproj" />
</ItemGroup>-->
</Project>
8 changes: 8 additions & 0 deletions samples/SampleWebApi_6_0/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
Loading

0 comments on commit b0fadfd

Please sign in to comment.