简体   繁体   English

WebAPI和授权基础

[英]WebAPI and Authorization Basic

I created a WebAPI but now I want to secure it with Basic Authorization. 我创建了一个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);
}

Below, how I post the data. 下面是我如何发布数据。 Now, I would like to create a function that I can add to my controller or my Application_Start() . 现在,我想创建一个可以添加到控制器或Application_Start()的函数。 It will check: 它将检查:

  • if the request.Headers.Authorization is != null 如果request.Headers.Authorization为!= null
  • if the request.Headers.Authorization.Scheme is != "Basic" 如果request.Headers.Authorization.Scheme是!=“ Basic”
  • if there are some parameters 如果有一些参数
  • get the parameter and decode it to create a pair (SecretId/SecretKey) 获取参数并将其解码以创建一个对(SecretId / SecretKey)
  • call a service to check in the DB if there is a client with this pair 呼叫服务以检查数据库中是否有与此配对的客户端
  • create an identity with IPrincipal 与IPrincipal创建身份

The thing is I don't know the best way is to create a customAttribute or a filter or something else. 事情是我不知道最好的方法是创建一个customAttribute或一个过滤器或其他东西。 There is plenty of different way to do this but I would like to understand the difference. 有很多不同的方法可以做到这一点,但我想了解其中的区别。

Create the below-mentioned Filter in your project and use it at top of your web API method as : 在您的项目中创建下面提到的过滤器,并在您的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\"}", Encoding.UTF8, "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,
                        Content = new StringContent("{\"error\":\"invalid_client\"}", Encoding.UTF8, "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,
                Content = new StringContent("{\"error\":\"invalid_request\"}", Encoding.UTF8, "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;
    }
}

I found few interesting articles about handlers/filter and attribute. 我发现了一些关于处理程序/过滤器和属性的有趣文章。 I don't want to override [Authorize] so I will probably do an Authentication Filter. 我不想覆盖[授权],所以我可能会做一个身份验证过滤器。

Below some good links: 下面是一些好的链接:

@Nkosi: Cheers to confirm. @Nkosi:欢呼确认。 I'm going to change the code a little bit because I don't want to use an Attribute but rather an filter that I put in the WebApiConfig 我将对代码进行一些更改,因为我不想使用属性,而是要使用放置在WebApiConfig中的过滤器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM