WCF ServiceAuthorizationManager依赖注入

时间:2017-08-01 06:35:57

标签: wcf authentication dependency-injection autofac

我创建了一个继承ServiceAuthorizationManager的小类,以便在WCF REST api中实现基本的HTTP身份验证。它有效,但同时它违反了SOLID原则。有没有办法通过构造函数将依赖项注入此类?我选择的DI容器是Autofac。

完整代码:

public class RestAuthorizationManager : ServiceAuthorizationManager
{
    private readonly string _correctUserName;
    private readonly string _correctPasswordHash;

    public RestAuthorizationManager()
    {
        _correctUserName = ConfigurationManager.AppSettings["User"];
        _correctPasswordHash = ConfigurationManager.AppSettings["PasswordHash"];
    }

    protected override bool CheckAccessCore(OperationContext operationContext)
    {
        if (WebOperationContext.Current != null)
        {
            var authHeader = WebOperationContext.Current.IncomingRequest.Headers["Authorization"];
            if (!string.IsNullOrEmpty(authHeader))
            {
                var svcCredentials = Encoding.ASCII.GetString(Convert.FromBase64String(authHeader.Substring(6))).Split(':');
                var user = new { Name = svcCredentials[0], Password = svcCredentials[1] };

                if (user.Name == _correctUserName && GetHash(user.Password) == _correctPasswordHash)
                {
                    return true;
                }
                return false;
            }
        }
        if (WebOperationContext.Current != null)
        {
            WebOperationContext.Current.OutgoingResponse.Headers.Add("WWW-Authenticate: Basic realm=\"Enter your password\"");
            WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Unauthorized;
            return false;
        }
        throw new WebFaultException(HttpStatusCode.Unauthorized);
    }

    private static string GetHash(string stringToHash)
    {
        byte[] passwordBytes = Encoding.ASCII.GetBytes(stringToHash);
        using (var sha1 = new SHA1Managed())
        {
            var hash = sha1.ComputeHash(passwordBytes);
            return Convert.ToBase64String(hash);
        }
    }
}

0 个答案:

没有答案