如何在WebApi中使用AuthorizationFilterAttribute和WebClient库?

时间:2014-04-28 08:33:06

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

我使用以下代码进行授权(我在互联网上找到它并将其更改为供我使用)

当我打电话给我的网址似乎授权有效 enter image description here

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class ClientAuthorizationAttribute : AuthorizationFilterAttribute
    {
        private bool _active = true;

        public ClientAuthorizationAttribute()
        {

        }

        public ClientAuthorizationAttribute(bool active)
        {
            _active = active;
        }

        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (_active)
            {
                var identity = ParseAuthorizationHeader(actionContext);
                if (identity == null)
                {
                    Challenge(actionContext);
                    return;
                }


                if (!OnAuthorizeUser(identity.Name, identity.Password, actionContext))
                {
                    Challenge(actionContext);
                    return;
                }

                var principal = new GenericPrincipal(identity, null);

                Thread.CurrentPrincipal = principal;
                base.OnAuthorization(actionContext);
            }
        }

        protected virtual bool OnAuthorizeUser(string clientId, string authId, HttpActionContext actionContext)
        {
            return false;
        }
        protected virtual ClientAuthenticationIdentity ParseAuthorizationHeader(HttpActionContext actionContext)
        {
            string authHeader = null;
            var auth = actionContext.Request.Headers.Authorization;
            if (auth != null && auth.Scheme == "Basic")
                authHeader = auth.Parameter;

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

            authHeader = Encoding.UTF8.GetString(Convert.FromBase64String(authHeader));

            var tokens = authHeader.Split(':');
            if (tokens.Length < 2)
                return null;

            return new ClientAuthenticationIdentity(tokens[0], tokens[1]);
        }

        void Challenge(HttpActionContext actionContext)
        {
            var host = actionContext.Request.RequestUri.DnsSafeHost;
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
            actionContext.Response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", host));
        }
    }

    public class ClientAuthenticationIdentity : GenericIdentity
    {
        public ClientAuthenticationIdentity(string name, string password)
            : base(name, "Basic")
        {
            Password = password;
        }
        public string Password { get; set; }
    }

    public class BasicAuthorizationAttribute : ClientAuthorizationAttribute
    {

        public BasicAuthorizationAttribute()
        { }

        public BasicAuthorizationAttribute(bool active)
            : base(active)
        { }


        protected override bool OnAuthorizeUser(string clientId, string authId, HttpActionContext actionContext)
        {
            var businness = new WebServiceAuthBusiness();
            return businness.Count(x => x.ClientID == clientId && x.AuthenticateID == authId) > 0;
        }
    }
}
客户端中的

我使用 WebClient 获取应用程序数据(不起作用)

    [BasicAuthorization]
    public IList<Application> Get()
    {
        using (var client = new WebClient())
        {

            client.BaseAddress = _baseAddress;
            client.Encoding = Encoding.UTF8;
            client.UseDefaultCredentials = true; ???
            client.Credentials = new NetworkCredential(clientId, authId); ???
            var str = client.DownloadString("api/application/get");
            return JsonConvert.DeserializeObject<List<Application>>(str);
        }
    }

如何使用webClient为AuthorizationFilter发送用户名和密码???

3 个答案:

答案 0 :(得分:5)

c# corner所述:

在解决方案中添加BasicAuthenticationAttribute.cs类。

使用以下代码

internalKey

在AuthsController.cs(实体框架)

添加

public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
{
    public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        try
        {
            if (actionContext.Request.Headers.Authorization == null)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
            }
            else
            {
                // Gets header parameters  
                string authenticationString = actionContext.Request.Headers.Authorization.Parameter;
                string originalString = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationString));

                // Gets username and password  
                string usrename = originalString.Split(':')[0];
                string password = originalString.Split(':')[1];

                AuthsController auth = new AuthsController();
                // Validate username and password  
                if (!auth.ValidateUser(usrename, password))
                {
                    // returns unauthorized error  
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                }
            }

            base.OnAuthorization(actionContext);
        }
        // Handling Authorize: Basic <base64(username:password)> format.
        catch(Exception e)
        {
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
        }
    }
}

在WebApiConfig.cs

添加

[NonAction]
    public bool ValidateUser(string userName, string password)
    {
        // Check if it is valid credential  
        var queryable = db.Auths
                        .Where(x => x.Name == userName)
                        .Where(x => x.Password == password);
        if (queryable != null)
        { 
            return true;
        }
        else
        {
            return false;
        }
    }

在需要基本授权的控制器中。

添加

config.Filters.Add(new BasicAuthenticationAttribute());

答案 1 :(得分:1)

基本身份验证需要Authorization header to be set

using (var client = new WebClient())
{    
    var credential = String.Format("{0}:{1}", userName, password);
    var encodedCredential = Convert.ToBase64String(Encoding.UTF8.GetBytes(credential))    
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", encodedCredential);

    // ...
}

答案 2 :(得分:0)

您应该能够将用户名和加密的密码作为GET api网址的一部分发送。

/api/application/Get?user=''&pw=''

您的AuthorizationFilter应该能够从RequestUri解析它们,但您当然不希望这样做,而是您可能需要实施OAuth Token样式access token与您的API一起发送。基本上,您的用户将使用登录面板和POST通过https登录详细信息并接收令牌,然后每次他或她发出请求时都会发送访问令牌以及该api,如下所示:

/api/application/Get?access_token=""

此访问令牌可能会在一段时间或速率限制后过期。 你可以在这里找到一个实现:

http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api