【问题标题】:.net application basic authentication [duplicate].net 应用程序基本身份验证 [重复]
【发布时间】:2020-09-21 07:35:51
【问题描述】:

我想在 .net 中实现基本身份验证。所以在这里我不想要一个 aspx 页面。

我只需要 web.config 文件,它应该要求我输入用户名和密码(如果我没记错的话,我们可以让浏览器要求输入用户名和密码。)

目前我有下面的代码需要我想删除的 login.aspx 页面。

<?xml version="1.0"?>
<configuration>
    <system.web>
        <customErrors mode="Off"/>
        <compilation debug="false" />
        <authentication mode="Forms">
            <forms>
                <credentials passwordFormat="Clear">
                    <user name="abc" password="abc@123" />
                </credentials>
            </forms>
        </authentication>
        <!-- Unless specified in a sub-folder's Web.config file, 
             any user can access any resource in the site -->
        <authorization>
            <deny users="?" />
        </authorization>
    </system.web>
    <system.webServer>
        <modules>
            <remove name="FormsAuthenticationModule" />
            <add name="FormsAuthenticationModule" type="System.Web.Security.FormsAuthenticationModule" />            
            <remove name="UrlAuthorization" />
            <add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule" />
        </modules>
    </system.webServer>
</configuration>

【问题讨论】:

  • @Martheen 感谢您的快速响应,但是否可以从 web.config 文件中处理?我不需要任何其他文件,我只想通过 web.config 文件完成所有内容
  • 提示输入用户名和密码需要JavaScript代码。
  • 哦,不,考虑到 this asker 最终会为它创建一个完整的 HttpModule
  • @Martheen 不能只使用 web.config 吗?

标签: c# asp.net


【解决方案1】:

这不是在您的应用程序中完成的。
这是在 IIS 中完成的,您可以在其中启用基本身份验证并禁用匿名身份验证。

但如果您坚持在代码中进行,您可以添加一个 HTTP 模块,您可以在其中自己检查基本身份验证。

例如

class SurroundingClass
{
    public void ProcessRequest(HttpContext context)
    {
        if (!Authenticate(context))
        {
            context.Response.Status = "401 Unauthorized";
            context.Response.StatusCode = 401;
            context.Response.AddHeader("WWW-Authenticate", "Basic");

            // // context.CompleteRequest(); 
            context.Response.Flush();
            context.Response.End();
            return;
        }
    } // ProcessRequest 



    private static string[] ParseAuthHeader(string authHeader)
    {
        // Check if this is a Basic Auth header 
        if (authHeader == null || authHeader.Length == 0 || !authHeader.StartsWith("Basic"))
            return null;

        // Pull out the Credentials with are seperated by ':' and Base64 encoded 
        string base64Credentials = authHeader.Substring(6);
        string[] credentials = System.Text.Encoding.ASCII.GetString(System.Convert.FromBase64String(base64Credentials)).Split(':');
        if (credentials.Length != 2 || string.IsNullOrEmpty(credentials[0]) || string.IsNullOrEmpty(credentials[0]))
            return null;

        return credentials;
    } // ParseAuthHeader



    private static bool TryGetPrincipal(string[] creds, ref System.Security.Principal.IPrincipal principal)
    {
        if (creds[0] == "Administrator" && creds[1] == "SecurePassword")
        {
            principal = new System.Security.Principal.GenericPrincipal(new System.Security.Principal.GenericIdentity("Administrator"), new string[] { "Administrator", "User" });
            return true;
        }
        else if (creds[0] == "JoeBlogs" && creds[1] == "Password")
        {
            principal = new System.Security.Principal.GenericPrincipal(new System.Security.Principal.GenericIdentity("JoeBlogs"), new string[] { "User" });
            return true;
        }
        else if (!string.IsNullOrEmpty(creds[0]) && !string.IsNullOrEmpty(creds[1]))
        {
            // GenericPrincipal(GenericIdentity identity, string[] Roles)
            principal = new System.Security.Principal.GenericPrincipal(new System.Security.Principal.GenericIdentity(creds[0]), new string[] { "Administrator", "User" });
            return true;
        }
        else
            principal = null;

        return false;
    } // TryGetPrincipal



    // http://blogs.msdn.com/b/odatateam/archive/2010/07/21/odata-and-authentication-part-6-custom-basic-authentication.aspx
    public static bool Authenticate(HttpContext context)
    {
        // DANGER: On the developer system, we need to be able to test it without SSL certificate
        // If Not context.Request.IsSecureConnection Then
        // Return False
        // End If

        string authHeader = context.Request.Headers["Authorization"];

        if (string.IsNullOrEmpty(authHeader))
            return false;


        string[] credentials = ParseAuthHeader(authHeader);
        System.Console.WriteLine(credentials);

        System.Security.Principal.IPrincipal principal = null;
        if (TryGetPrincipal(credentials, ref principal))
        {
            HttpContext.Current.User = principal;
            return true;
        }

        return false;
    } // Authenticate
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-20
    • 2014-01-26
    • 2015-08-18
    • 1970-01-01
    • 2015-09-05
    • 2019-01-14
    相关资源
    最近更新 更多