【问题标题】:ASP.Net Web API with Digest Authentication具有摘要式身份验证的 ASP.Net Web API
【发布时间】:2015-01-14 06:19:40
【问题描述】:

我已经编写了一堆 ASP.Net Web API,我想对其中的一些 API 进行身份验证。我已经从 here 开始使用 Digest Authentication 实现

我还参考了here的演示代码

我对代码有所了解,但我不知道在哪里以及如何连接现有数据库以从客户表中获取数据。如果有人知道如何实现这一点,请分享。

以下是一些认证方法:

DigestAuthorizationFilterAttributeBase.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;
    }

【问题讨论】:

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


    【解决方案1】:

    一个例子是下面的方法:

    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;
        }
    }
    

    您还需要检查密码是否有效。但你明白了。

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2017-03-02
      • 1970-01-01
      • 1970-01-01
      • 2015-03-22
      • 2012-06-16
      • 2017-10-22
      • 1970-01-01
      • 1970-01-01
      • 2011-07-09
      相关资源
      最近更新 更多