I am trying to configure basic authentication on MVC in an ASP.NET Core 1.1 application. I would like to point out that the service requires basic Authentincation by adding an attribute to the service action (instead of allowing the basic broadcast application). After some reading, it seems like a suitable way to do this is to use Middleware Filter.
The most comprehensive guide I found on Middleware filters is here
The above post indicates that I need to create a Pipeline class as follows
public class MyPipeline { public void Configure(IApplicationBuilder applicationBuilder) { var options =
I also need a middleware class. I changed and the example from here
public class AuthenticationMiddleware { private readonly RequestDelegate _next; public AuthenticationMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { string authHeader = context.Request.Headers["Authorization"]; if (authHeader != null && authHeader.StartsWith("Basic")) { //Extract credentials string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim(); Encoding encoding = Encoding.GetEncoding("iso-8859-1"); string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword)); int seperatorIndex = usernamePassword.IndexOf(':'); var username = usernamePassword.Substring(0, seperatorIndex); var password = usernamePassword.Substring(seperatorIndex + 1); //Here is the tricky bit DBAuth authenticator = new DBAuth(ConnectionString); if(authenticator.IsAuthorized(username, password)) { await _next.Invoke(context); } else { context.Response.StatusCode = 401; //Unauthorized return; } } else { // no authorization header context.Response.StatusCode = 401; //Unauthorized return; } } } }
Question: How do I pass the connection string to the AuthenticationMiddleware class so that I can verify the username and password in the database? I really want to do this with an injection, not with Configuration.GetConnectionString () inside the Middleware class.
From the code in the sample pipeline example, it seems that the parameters can be passed to the middleware class, but I'm not sure how to change the AuthenticationMiddleware class to accept the parameters or what the class’s parameters actually are
PS: I know that basic authentication is bad, but this is a requirement that I was given
source share