-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add api key authentication schame for aspnet
- Loading branch information
Showing
23 changed files
with
827 additions
and
13 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
using Microsoft.AspNetCore.Authorization; | ||
using Microsoft.AspNetCore.Mvc; | ||
|
||
namespace SampleWeb.Controllers; | ||
|
||
[Route("api/values")] | ||
public class ValuesController : ControllerBase | ||
{ | ||
[HttpGet] | ||
public IActionResult Get() | ||
{ | ||
return Ok(new[] { "value1", "value2" }); | ||
} | ||
|
||
[HttpGet("auth")] | ||
[Authorize] | ||
public IActionResult Authorization() | ||
{ | ||
return Ok(new | ||
{ | ||
User.Identity.Name, | ||
User.Identity.AuthenticationType, | ||
Claims = User.Claims.Select(x => new { x.Type, x.Value }) | ||
}); | ||
} | ||
} |
3 changes: 1 addition & 2 deletions
3
samples/SampleWeb/Data/Migrations/00000000000000_CreateIdentitySchema.cs
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 |
---|---|---|
@@ -1,5 +1,7 @@ | ||
using System.Security.Claims; | ||
using Microsoft.AspNetCore.Identity; | ||
using Microsoft.EntityFrameworkCore; | ||
using Passingwind.AspNetCore.Authentication.ApiKey; | ||
using SampleWeb.Data; | ||
|
||
var builder = WebApplication.CreateBuilder(args); | ||
|
@@ -10,12 +12,37 @@ | |
options.UseSqlServer(connectionString)); | ||
builder.Services.AddDatabaseDeveloperPageExceptionFilter(); | ||
|
||
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) | ||
builder.Services.AddDefaultIdentity<IdentityUser>() | ||
.AddEntityFrameworkStores<ApplicationDbContext>(); | ||
builder.Services.AddRazorPages(); | ||
builder.Services.AddControllers(); | ||
|
||
builder.Services | ||
.AddAuthentication() | ||
.AddApiKey<TestApiKeyProvider>(); | ||
|
||
builder.Services.ConfigureApplicationCookie(options => | ||
{ | ||
options.ForwardDefaultSelector = (s) => | ||
{ | ||
var authorization = (string?)s.Request.Headers.Authorization; | ||
if (authorization?.StartsWith(ApiKeyDefaults.AuthenticationSchemeName) == true) | ||
return ApiKeyDefaults.AuthenticationScheme; | ||
|
||
return IdentityConstants.ApplicationScheme; | ||
}; | ||
}); | ||
|
||
var app = builder.Build(); | ||
|
||
using var scope = app.Services.CreateScope(); | ||
|
||
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<IdentityUser>>(); | ||
if (await userManager.FindByNameAsync("bob") == null) | ||
{ | ||
await userManager.CreateAsync(new IdentityUser("bob") { Email = "[email protected]", EmailConfirmed = true, Id = Guid.NewGuid().ToString(), }); | ||
} | ||
|
||
// Configure the HTTP request pipeline. | ||
if (app.Environment.IsDevelopment()) | ||
{ | ||
|
@@ -35,6 +62,34 @@ | |
|
||
app.UseAuthorization(); | ||
|
||
app.MapDefaultControllerRoute(); | ||
app.MapRazorPages(); | ||
|
||
app.Run(); | ||
|
||
|
||
public class TestApiKeyProvider : IApiKeyProvider | ||
{ | ||
private readonly UserManager<IdentityUser> _userManager; | ||
private readonly SignInManager<IdentityUser> _signInManager; | ||
|
||
public TestApiKeyProvider(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager) | ||
{ | ||
_userManager = userManager; | ||
_signInManager = signInManager; | ||
} | ||
|
||
public async Task<ApiKeyValidationResult> ValidateAsync(string apiKey, CancellationToken cancellationToken = default) | ||
{ | ||
if (apiKey == "1234567890") | ||
{ | ||
var user = await _userManager.FindByNameAsync("bob"); | ||
|
||
var principal = await _signInManager.ClaimsFactory.CreateAsync(user!); | ||
|
||
return ApiKeyValidationResult.Success(new ClaimsIdentity(principal.Identity)); | ||
} | ||
|
||
return ApiKeyValidationResult.Failed(new Exception("invalid api key")); | ||
} | ||
} |
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,45 @@ | ||
# AspNetCore.Authentication.ApiKey | ||
|
||
ASP.NET Core authentication handler for the ApiKey protocol | ||
|
||
## Quickstart | ||
|
||
``` cs | ||
builder.Services | ||
.AddAuthentication() | ||
// api ApiKey scheme | ||
.AddApiKey<TestApiKeyProvider>(); | ||
|
||
// configure this if you default scheme is not 'ApiKey' | ||
// builder.Services.ConfigureApplicationCookie(options => | ||
// { | ||
// options.ForwardDefaultSelector = (s) => | ||
// { | ||
// var authorization = (string?)s.Request.Headers.Authorization; | ||
// if (authorization?.StartsWith(ApiKeyDefaults.AuthenticationSchemeName) == true) | ||
// return ApiKeyDefaults.AuthenticationScheme; | ||
// | ||
// // you default scheme | ||
// return IdentityConstants.ApplicationScheme; | ||
// }; | ||
// }); | ||
``` | ||
|
||
TestApiKeyProvider.cs | ||
|
||
```cs | ||
public class TestApiKeyProvider : IApiKeyProvider | ||
{ | ||
public async Task<ApiKeyValidationResult> ValidateAsync(string apiKey, CancellationToken cancellationToken = default) | ||
{ | ||
// verification apiKey | ||
... | ||
|
||
// if success | ||
return ApiKeyValidationResult.Success(...); | ||
|
||
// if fail | ||
return ApiKeyValidationResult.Failed(new Exception("invalid api key")); | ||
} | ||
} | ||
``` |
28 changes: 28 additions & 0 deletions
28
src/Authentication.ApiKey/source/ApiKeyAuthenticationFailedContext.cs
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,28 @@ | ||
using System; | ||
using Microsoft.AspNetCore.Authentication; | ||
using Microsoft.AspNetCore.Http; | ||
|
||
namespace Passingwind.AspNetCore.Authentication.ApiKey; | ||
|
||
/// <summary> | ||
/// A <see cref="ResultContext{TOptions}"/> when authentication has failed. | ||
/// </summary> | ||
public class ApiKeyAuthenticationFailedContext : ResultContext<ApiKeyOptions> | ||
{ | ||
/// <summary> | ||
/// Initializes a new instance of <see cref="ApiKeyAuthenticationFailedContext"/>. | ||
/// </summary> | ||
/// <inheritdoc /> | ||
public ApiKeyAuthenticationFailedContext( | ||
HttpContext context, | ||
AuthenticationScheme scheme, | ||
ApiKeyOptions options) | ||
: base(context, scheme, options) | ||
{ | ||
} | ||
|
||
/// <summary> | ||
/// Gets or sets the exception associated with the authentication failure. | ||
/// </summary> | ||
public Exception Exception { get; set; } = default!; | ||
} |
40 changes: 40 additions & 0 deletions
40
src/Authentication.ApiKey/source/ApiKeyChallengeContext.cs
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,40 @@ | ||
using System; | ||
using Microsoft.AspNetCore.Authentication; | ||
using Microsoft.AspNetCore.Http; | ||
|
||
namespace Passingwind.AspNetCore.Authentication.ApiKey; | ||
|
||
/// <summary> | ||
/// A <see cref="PropertiesContext{TOptions}"/> when access to a resource authenticated using ApiKey is challenged. | ||
/// </summary> | ||
public class ApiKeyChallengeContext : PropertiesContext<ApiKeyOptions> | ||
{ | ||
/// <summary> | ||
/// Initializes a new instance of <see cref="ApiKeyChallengeContext"/>. | ||
/// </summary> | ||
/// <inheritdoc /> | ||
public ApiKeyChallengeContext(HttpContext context, AuthenticationScheme scheme, ApiKeyOptions options, AuthenticationProperties? properties) : base(context, scheme, options, properties) | ||
{ | ||
} | ||
|
||
/// <summary> | ||
/// Any failures encountered during the authentication process. | ||
/// </summary> | ||
public Exception? AuthenticateFailure { get; set; } | ||
|
||
/// <summary> | ||
/// Gets or sets the "error" value returned to the caller as part | ||
/// of the WWW-Authenticate header. | ||
/// </summary> | ||
public string? Error { get; set; } | ||
|
||
/// <summary> | ||
/// If true, will skip any default logic for this challenge. | ||
/// </summary> | ||
public bool Handled { get; private set; } | ||
|
||
/// <summary> | ||
/// Skips any default logic for this challenge. | ||
/// </summary> | ||
public void HandleResponse() => Handled = true; | ||
} |
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 @@ | ||
namespace Passingwind.AspNetCore.Authentication.ApiKey; | ||
|
||
/// <summary> | ||
/// Default value for ApiKey authentication | ||
/// </summary> | ||
public static class ApiKeyDefaults | ||
{ | ||
/// <summary> | ||
/// Default value for AuthenticationScheme | ||
/// </summary> | ||
public const string AuthenticationScheme = "ApiKey"; | ||
|
||
/// <summary> | ||
/// | ||
/// </summary> | ||
public const string HeaderName = "X-ApiKey"; | ||
|
||
/// <summary> | ||
/// | ||
/// </summary> | ||
public const string QueryStringName = "x-apikey"; | ||
|
||
/// <summary> | ||
/// | ||
/// </summary> | ||
public const string AuthenticationSchemeName = "ApiKey"; | ||
} |
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,53 @@ | ||
using System; | ||
using System.Threading.Tasks; | ||
|
||
namespace Passingwind.AspNetCore.Authentication.ApiKey; | ||
|
||
/// <summary> | ||
/// Specifies events which the <see cref="ApiKeyHandler"/> invokes to enable developer control over the authentication process. | ||
/// </summary> | ||
public class ApiKeyEvents | ||
{ | ||
/// <summary> | ||
/// | ||
/// </summary> | ||
public Func<ApiKeyMessageReceivedContext, Task> OnMessageReceived { get; set; } = context => Task.CompletedTask; | ||
/// <summary> | ||
/// | ||
/// </summary> | ||
public Func<ApiKeyTokenValidatedContext, Task> OnTokenValidated { get; set; } = context => Task.CompletedTask; | ||
/// <summary> | ||
/// | ||
/// </summary> | ||
public Func<ApiKeyAuthenticationFailedContext, Task> OnAuthenticationFailed { get; set; } = context => Task.CompletedTask; | ||
/// <summary> | ||
/// | ||
/// </summary> | ||
public Func<ApiKeyChallengeContext, Task> OnChallenge { get; set; } = context => Task.CompletedTask; | ||
/// <summary> | ||
/// | ||
/// </summary> | ||
public Func<ApiKeyForbiddenContext, Task> OnForbidden { get; set; } = context => Task.CompletedTask; | ||
|
||
|
||
/// <summary> | ||
/// Invoked when a protocol message is first received. | ||
/// </summary> | ||
public virtual Task MessageReceivedAsync(ApiKeyMessageReceivedContext context) => OnMessageReceived(context); | ||
/// <summary> | ||
/// Invoked after the security token has passed validation and a ClaimsIdentity has been generated. | ||
/// </summary> | ||
public virtual Task TokenValidatedAsync(ApiKeyTokenValidatedContext context) => OnTokenValidated(context); | ||
/// <summary> | ||
/// Invoked if exceptions are thrown during request processing. The exceptions will be re-thrown after this event unless suppressed. | ||
/// </summary> | ||
public virtual Task AuthenticationFailedAsync(ApiKeyAuthenticationFailedContext context) => OnAuthenticationFailed(context); | ||
/// <summary> | ||
/// Invoked before a challenge is sent back to the caller. | ||
/// </summary> | ||
public virtual Task ChallengeAsync(ApiKeyChallengeContext context) => OnChallenge(context); | ||
/// <summary> | ||
/// Invoked if Authorization fails and results in a Forbidden response | ||
/// </summary> | ||
public virtual Task ForbiddenAsync(ApiKeyForbiddenContext context) => OnForbidden(context); | ||
} |
Oops, something went wrong.