C# 具有摘要身份验证的ASP.NETWebAPI

C# 具有摘要身份验证的ASP.NETWebAPI,c#,asp.net-web-api,digest-authentication,C#,Asp.net Web Api,Digest Authentication,我已经编写了一系列restful ASP.NETWebAPI,我想对其中一些API进行身份验证。我已经使用了来自的摘要身份验证实现 此外,我还参考了 我对代码有点了解,但我不知道在哪里以及如何连接现有数据库以从customer表获取数据。如果任何人有关于如何实现这一点的信息,请分享 以下是一些身份验证方法: DigestAuthorizationFilterAttribute.cs protected override string GetAuthenticatedUser(HttpAction

我已经编写了一系列restful ASP.NETWebAPI,我想对其中一些API进行身份验证。我已经使用了来自的摘要身份验证实现

此外,我还参考了

我对代码有点了解,但我不知道在哪里以及如何连接现有数据库以从customer表获取数据。如果任何人有关于如何实现这一点的信息,请分享

以下是一些身份验证方法:

DigestAuthorizationFilterAttribute.cs

protected override string GetAuthenticatedUser(HttpActionContext actionContext)
    {
        var auth = actionContext.Request.Headers.Authorization;
        if (auth == null || auth.Scheme != Scheme)
            return null;

        var header = DigestHeader.Create(
            actionContext.Request.Headers.Authorization.Parameter, 
            actionContext.Request.Method.Method);

        if (!DigestNonce.IsValid(header.Nonce, header.NounceCounter))
        { 
            return null;
        }
               var password = GetPassword(header.UserName);

            var hash1 = String.Format(
            "{0}:{1}:{2}",
            header.UserName,
            header.Realm,
            password).ToMd5Hash();

            var hash2 = String.Format(
                "{0}:{1}",
                header.Method,
                header.Uri).ToMd5Hash();

            var computedResponse = String.Format(
                "{0}:{1}:{2}:{3}:{4}:{5}",
                hash1,
                header.Nonce,
                header.NounceCounter,
                header.Cnonce,
                "auth",
                hash2).ToMd5Hash();

            return header.Response.Equals(computedResponse, StringComparison.Ordinal)
                ? header.UserName
                : null;

    }
DigestAuthorizationFilterAttribute.cs

    public DigestAuthorizationFilterAttribute(bool issueChallenge = true) : base(issueChallenge)
    {

    }

    protected override bool IsUserAuthorized(string userName)
    {
        return true;
    }

    protected override string GetPassword(string userName)
    {
        return userName;
    }

下面的方法就是一个例子:

protected override bool IsUserAuthorized(string userName)
{
    return true;
}
你可以做一些大致类似的事情:

protected override bool IsUserAuthorized(string userName)
{
    var user = db.Users.Where(u => u.username = userName);
    if(user.Any())
    {
        return true;
    }
    else
    {
        return false;
    }
}
您还需要检查密码是否有效。但你明白了

希望这有帮助