基本http授权中的服务器错误

时间:2013-10-03 09:54:10

标签: c# asp.net-web-api

我有基本的http authorizaton的WebApi项目。我之前需要授权用户,他去安全页面。当我进入安全页面“Books / get”时,我看到“/'应用程序中的服务器错误”错误。为什么页面有错误? 在root中:

public class BasicAuthHttpModule : IHttpModule
{
    private const string Realm = "My Realm";

    public void Init(HttpApplication 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 bool AuthenticateUser(string credentials)
    {
        bool validated = false;
        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);

            validated = CheckPassword(name, password);
            if (validated)
            {
                var identity = new GenericIdentity(name);
                SetPrincipal(new GenericPrincipal(identity, null));
            }
        }
        catch (FormatException)
        {
            // Credentials were not formatted correctly.
            validated = false;

        }
        return validated;
    }

    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 class ItemModel
{
    public int ItemID { get; set; }
    public string ItemName { get; set; }
    public double ItemValue { get; set; }
}

网络配置的一部分:

  <system.webServer>
  <modules>
    <add name="BasicAuthHttpModule"  type="WebHostBasicAuth.Modules.BasicAuthHttpModule, BasicAuth"/>
  </modules>

书籍管理员:

    [Authorize]
public class BooksController : ApiController
{
    [Authorize]
    public IEnumerable<ItemModel> Get()
    {
        return new List<ItemModel> 
        {
            new ItemModel() { ItemID = 1, ItemName = "Item1", ItemValue = 100 },
        };
    }

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题。尝试不带BasicAuth的web.config部分

<add name="BasicAuthHttpModule"  type="WebHostBasicAuth.Modules.BasicAuthHttpModule"/>