-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- 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
1 parent
e261423
commit e04025f
Showing
29 changed files
with
496 additions
and
125 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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")] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | ||
} | ||
} | ||
} | ||
} |
Oops, something went wrong.