Created
February 23, 2016 17:01
-
-
Save Bartmax/88d740aa50210964b30f to your computer and use it in GitHub Desktop.
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
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