Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I am new to asp.net core and trying to implement basic auth following this msdn doc
Basic Authentication in ASP.NET Web API | Microsoft Docs[^]

What I have tried:

I am using the code below. I get the following errors

Errors:

1) The type or namespace name 'IHttpModule' could not be found
2) Using the generic type 'IHttpApplication<tcontext>' requires 1 type arguments
3) 'IHeaderDictionary' does not contain a definition for 'Set' and no extension method 'Set' accepting a first argument of type 'IHeaderDictionary' could be found
4) 'HttpContext' does not contain a definition for 'Current'
5) 'IHeaderDictionary' does not contain a definition for 'Get' and the best extension method overload 'SessionExtensions.Get(ISession, string)' requires a receiver of type 'ISession'
6) No overload for method 'StartsWith' takes 2 arguments
7) 'byte[]' does not contain a definition for 'Substring' and no extension method 'Substring' accepting a first argument of type 'byte[]' could be found
8) The name '_next' does not exist in the current context

namespace BasicAuth
{
        public class BasicAuthHttpModule : IHttpModule
        {
            private const string Realm = "My App Name";

            public void Init(IHttpApplication context)
            {
                // Register event handlers
                context.AuthenticateRequest += OnApplicationAuthenticateRequest;
                context.EndRequest += OnApplicationEndRequest;
            }

            private static void SetPrincipal(IPrincipal principal)
            {
                Thread.CurrentPrincipal = principal;
                if (HttpContext.Current != null)
                {
                    HttpContext.Current.User = principal;
                }
            }

            // TODO: Here is where you would validate the username and password.
            private static bool CheckPassword(string username, string password)
            {
                return username == "user" && password == "password";
            }

            private static void AuthenticateUser(string credentials)
            {
                try
                {
                    var encoding = Encoding.GetEncoding("iso-8859-1");
                    credentials = encoding.GetString(Convert.FromBase64String(credentials));

                    int separator = credentials.IndexOf(':');
                    string name = credentials.Substring(0, separator);
                    string password = credentials.Substring(separator + 1);

                    if (CheckPassword(name, password))
                    {
                        var identity = new GenericIdentity(name);
                        SetPrincipal(new GenericPrincipal(identity, null));
                    }
                    else
                    {
                        // Invalid username or password.
                        HttpContext.Current.Response.StatusCode = 401;
                    }
                }
                catch (FormatException)
                {
                    // Credentials were not formatted correctly.
                    HttpContext.Current.Response.StatusCode = 401;
                }
            }

            private static void OnApplicationAuthenticateRequest(object sender, EventArgs e)
            {
                var request = HttpContext.Current.Request;
                var authHeader = request.Headers["Authorization"];
                if (authHeader != null)
                {
                    var authHeaderVal = AuthenticationHeaderValue.Parse(authHeader);

                    // RFC 2617 sec 1.2, "scheme" name is case-insensitive
                    if (authHeaderVal.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase) &&
                        authHeaderVal.Parameter != null)
                    {
                        AuthenticateUser(authHeaderVal.Parameter);
                    }
                }
            }

            // If the request was unauthorized, add the WWW-Authenticate header 
            // to the response.
            private static void OnApplicationEndRequest(object sender, EventArgs e)
            {
                var response = HttpContext.Current.Response;
                if (response.StatusCode == 401)
                {
                    response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", Realm));
                }
            }

            public void Dispose()
            {
            }

            public async Task Invoke(HttpContext context)
            {
                var authHeader = context.Request.Headers.Get("Authorization");
                if (authHeader != null && authHeader.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
                {
                    var token = authHeader.Substring("Basic ".Length).Trim();
                    System.Console.WriteLine(token);
                    var credentialstring = Encoding.UTF8.GetString(Convert.FromBase64String(token));
                    var credentials = credentialstring.Split(':');
                    if (credentials[0] == "admin" && credentials[1] == "admin")
                    {
                        var claims = new[] { new Claim("name", credentials[0]), new Claim(ClaimTypes.Role, "Admin") };
                        var identity = new ClaimsIdentity(claims, "Basic");
                        context.User = new ClaimsPrincipal(identity);
                    }
                }
                else
                {
                    context.Response.StatusCode = 401;
                    context.Response.Headers.Set("WWW-Authenticate", "Basic realm=\"dotnetthoughts.net\"");
                }
                await _next(context);
            }
        }
}


Thank you in advance.
Posted
Updated 17-Jul-18 5:49am
v2

You need to add the relevant "using" statements at the top of the page. If you right click on IHttpModule you should see a "Refactor" menu in the context menu and that will give you the option of adding the appropriate "using". Failing that if you use resharper or something that has a way of doing this too. Failing those options you can add the using yourself, but that requires you to just know what namespace the class is in. If you google or search MSDN you'll find this out.

IHttpModule Interface (System.Web)[^]

"Namespace: System.Web"

So you need to add

using System.Web;


to the top of the page. Do the same with the other unidentified types. Note this implies you have the relevant assembly referenced in your project too.
 
Share this answer
 
The documentation you're following is for ASP.NET Web API, not ASP.NET Core. Despite the confusingly-similar names, they are effectively completely different frameworks.

You need to follow the instructions for ASP.NET Core instead:
Configure Windows authentication in ASP.NET Core | Microsoft Docs[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900