Asp.net核心web api基本认证 [英] Asp.net core web api basic auth

查看:95
本文介绍了Asp.net核心web api基本认证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是asp.net核心的新手,并尝试在此msdn doc之后实现基本身份验证

ASP.NET Web API中的基本身份验证| Microsoft Docs [ ^ ]



我的尝试:



我正在使用下面的代码。我收到以下错误



错误:



1)类型找不到或命名空间名称'IHttpModule'

2)使用泛型类型'IHttpApplication< tcontext>'需要1个类型参数

3)'IHeaderDictionary'不包含'Set'的定义和没有扩展方法'Set'接受'IHeaderDictionary'类型的第一个参数可以找到

4)'HttpContext'不包含'Current'的定义

5)'IHeaderDictionary'不包含'Get'的定义,最好的扩展方法重载'SessionExtensions.Get(ISession,string)'需要一个'ISession'类型的接收器

)方法'StartsWith'没有重载需要2个参数

7)'byte []'不包含'Substring'的定义,没有扩展方法'Substring'接受类型的第一个参数'byte []'可以找到

8)当前上下文中不存在名称'_next'



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.

推荐答案

您需要在页面顶部添加相关的使用语句。如果右键单击IHttpModule,您应该在上下文菜单中看到Refactor菜单,这将为您提供添加适当使用的选项。如果你使用resharper或者有某种方法可以做到这一点,那就失败了。如果没有这些选项,您可以自己添加使用,但这需要您只知道该类所在的命名空间。如果您谷歌搜索或搜索MSDN,您会发现它。



IHttpModule Interface(System.Web) [ ^ ]



命名空间:System.Web



所以你需要添加



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.


您所遵循的文档适用于ASP.NET Web API,不是 ASP.NET核心。尽管名称容易混淆,但它们实际上是完全不同的框架。



您需要按照ASP.NET Core的说明进行操作:

在ASP.NET Core中配置Windows身份验证| Microsoft Docs [ ^ ]
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[^]


这篇关于Asp.net核心web api基本认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆