Skip to content

Instantly share code, notes, and snippets.

@Bartmax
Created February 23, 2016 17:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bartmax/88d740aa50210964b30f to your computer and use it in GitHub Desktop.
Save Bartmax/88d740aa50210964b30f to your computer and use it in GitHub Desktop.
public class DevelpmentWallMiddleware
{
private readonly RequestDelegate _next;
private readonly string _password;
private readonly string _username;
public DevelpmentWallMiddleware(RequestDelegate next, string username, string password)
{
_next = next;
_username = username;
_password = password;
}
public Task Invoke(HttpContext httpContext)
{
var request = httpContext.Request;
var response = httpContext.Response;
if (request.Host.Value.StartsWith("localhost")) return _next(httpContext);
StringValues authHeader;
if (request.Headers.TryGetValue("Authorization", out authHeader) &&
authHeader.Any() &&
authHeader.First().StartsWith("Basic "))
{
try
{
string pair = Encoding.UTF8.GetString(
Convert.FromBase64String(authHeader.FirstOrDefault().Substring("Basic ".Length)));
var ix = pair.IndexOf(':');
var credentialId = pair.Substring(0, ix);
var credentialSecret = pair.Substring(ix + 1);
if (credentialId == _username && credentialSecret == _password)
{
return _next(httpContext);
}
}
catch (Exception)
{
}
}
response.StatusCode = 401;
response.Headers.AppendCommaSeparatedValues("WWW-Authenticate", $"Basic realm=basic");
return Task.FromResult<object>(null);
}
}
public static class DevelpmentWallMiddlewareExtensions
{
public static IApplicationBuilder UseDevelpmentWallMiddleware(this IApplicationBuilder builder, string username, string password)
{
return builder.UseMiddleware<DevelpmentWallMiddleware>(username, password);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment