加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – WebAPI和授权基础

发布时间:2020-12-15 22:48:01 所属栏目:百科 来源:网络整理
导读:我创建了一个WebAPI,但现在我想通过基本授权来保护它. // POST the data to the APIusing (var client = new WebClient()){ client.Headers.Add("Content-Type","application/json"); client.Headers.Add(HttpRequestHeader.Authorization,"Basic" + Convert
我创建了一个WebAPI,但现在我想通过基本授权来保护它.

// POST the data to the API
using (var client = new WebClient())
{
    client.Headers.Add("Content-Type","application/json");
    client.Headers.Add(HttpRequestHeader.Authorization,"Basic" + Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials)));
    string json = JsonConvert.SerializeObject(ex);
    string content = client.UploadString("http://myURL/v1/endpoint",json);
}

下面,我如何发布数据.现在,我想创建一个可以添加到我的控制器或我的Application_Start()的函数.它将检查:

>如果request.Headers.Authorization是!= null
>如果request.Headers.Authorization.Scheme是!=“基本”
>如果有一些参数
>获取参数并对其进行解码以创建一对(SecretId / SecretKey)
>调用服务以检查数据库中是否存在具有此对的客户端
>使用IPrincipal创建身份

问题是我不知道最好的方法是创建customAttribute或过滤器或其他东西.有很多不同的方法可以做到这一点,但我想了解其中的差异.

解决方法

在项目中创建下面提到的过滤器,并在Web API方法的顶部使用它:

**[BasicAuth]**

    /// <summary>
/// Basic Authentication Filter Class
/// </summary>
public class BasicAuthAttribute : ActionFilterAttribute
{
    /// <summary>
    /// Called when [action executing].
    /// </summary>
    /// <param name="filterContext">The filter context.</param>
    public override void OnActionExecuting(HttpActionContext filterContext)
    {
        try
        {
            if (filterContext.Request.Headers.Authorization == null)
            {
                // Client authentication failed due to invalid request.

                filterContext.Response = new System.Net.Http.HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.Unauthorized,Content = new StringContent("{"error":"invalid_client"}",Encoding.UTF8,"application/json")
                };
                filterContext.Response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Basic","realm=xxxx"));
            }
            else if (filterContext.Request.Headers.Authorization.Scheme != "Basic" ||
                string.IsNullOrEmpty(filterContext.Request.Headers.Authorization.Parameter))
            {
                // Client authentication failed due to invalid request.
                filterContext.Response = new System.Net.Http.HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.BadRequest,Content = new StringContent("{"error":"invalid_request"}","application/json")
                };
            }
            else
            {
                var authToken = filterContext.Request.Headers.Authorization.Parameter;
                Encoding encoding = Encoding.GetEncoding("iso-8859-1");
                string usernamePassword = encoding.GetString(Convert.FromBase64String(authToken));

                int seperatorIndex = usernamePassword.IndexOf(':');
                string clientId = usernamePassword.Substring(0,seperatorIndex);
                string clientSecret = usernamePassword.Substring(seperatorIndex + 1);
                if (!ValidateApiKey(clientId,clientSecret))
                {
                    // Client authentication failed due to invalid credentials
                    filterContext.Response = new System.Net.Http.HttpResponseMessage()
                    {
                        StatusCode = HttpStatusCode.Unauthorized,"application/json")
                    };
                }
                // Successfully finished HTTP basic authentication
            }
        }
        catch (Exception ex)
        {
            // Client authentication failed due to internal server error
            filterContext.Response = new System.Net.Http.HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.BadRequest,"application/json")
            };
        }
    }





    /// <summary>
    /// Validates the API key.
    /// </summary>
    /// <param name="recievedKey">The recieved key.</param>
    /// <returns></returns>
    private bool ValidateApiKey(string clientId,string clientSecret)
    {
        if (your condition satisfies)
        {
            return true;
        }
        return false;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读