Skip to content

Instantly share code, notes, and snippets.

@DamienBraillard
Created October 31, 2018 14:43
Show Gist options
  • Save DamienBraillard/21a8fbef929bca52613e0f85ee61742f to your computer and use it in GitHub Desktop.
Save DamienBraillard/21a8fbef929bca52613e0f85ee61742f to your computer and use it in GitHub Desktop.
Global AD windows auth middleware for Asp .Net core
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
namespace Microsoft.AspNetCore.Builder
{
public static class WindowsAuthorizationAppBuilderExtensions
{
public static IApplicationBuilder UseWindowsAuthorization(this IApplicationBuilder builder, IEnumerable<string> authorizedAccounts)
{
return builder.UseMiddleware<WindowsAuthorizationMiddleware>(authorizedAccounts);
}
}
internal class WindowsAuthorizationMiddleware
{
private readonly RequestDelegate _next;
private readonly IEnumerable<string> _authorizedAccounts;
public WindowsAuthorizationMiddleware(RequestDelegate next, IEnumerable<string> authorizedAccounts)
{
_next = next;
_authorizedAccounts = authorizedAccounts;
}
public async Task InvokeAsync(HttpContext context)
{
var identity = context.User?.Identity;
if (identity == null || !identity.IsAuthenticated)
{
await context.ChallengeAsync();
return;
}
var isAuthorized = identity is WindowsIdentity && _authorizedAccounts.Any(context.User.IsInRole);
if (!isAuthorized)
{
context.Response.StatusCode = 403; // HttpStatusCode.Forbidden;
return;
}
await _next.Invoke(context);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment