简体   繁体   English

在MVC控制器中验证Webhook调用http:// secretkey:12345@www.example.com

[英]Authenticating a webhook call in mvc controller http://secretkey:12345@www.example.com

Creating a webhook handler in MVC 4 to handle EasyPost webhook calls. 在MVC 4中创建一个Webhook处理程序以处理EasyPost Webhook调用。 I have it all working but now want to add in some authentication. 我所有的工作正常,但现在想添加一些身份验证。

Easypost suggests a method of including a user name or secret key in the webhook handler url such as: https://username:secret@www.example.com/easypost-webhook reference . Easypost建议在Webhook处理程序URL中包括用户名或密钥的方法,例如: https://username:secret@www.example.com/easypost-webhook reference Then I presume extracting that secret key value and comparing to an expected value. 然后,我假定提取该秘密密钥值并将其与期望值进行比较。 I'm attempting to do this via regex. 我正试图通过正则表达式来做到这一点。

The problem is I cannot find how to retrieve the username:secret@ portion of the url in the controller. 问题是我找不到如何在控制器中检索URL的username:secret@部分。 Tried Request.RawUrl and searched all data in the Request Object, to no avail. 尝试了Request.RawUrl并搜索了请求对象中的所有数据,但无济于事。

My Code: 我的代码:

public class ParcelShippingWebHooksController : Controller
{
    [ValidateInput(false)]
    [HttpPost]
    public ActionResult ParcelTrackingWebHookHandler()
    {
        //Authenticate request
        string key = AppSettings.ParcelTrackingWebhookSecretKey;
        string url = Request.RawUrl; <---- how get raw url
        string strPattern = @"secretkey:(.*)\@";
        Match match = Regex.Match(url, strPattern);
        if(!match.Success) return new HttpStatusCodeResult(HttpStatusCode.Forbidden);
        if(match.Value != key) return new HttpStatusCodeResult(HttpStatusCode.Forbidden);

        //Convert request to string
        byte[] param = Request.BinaryRead(Request.ContentLength);
        string strWebHookDataRequest = Encoding.ASCII.GetString(param);

        //perform tracking updates
        var webhookAppServ = new ParcelShippingWebHooksAppServ(new InventoryMgmtContext());
        var updateTrackingResult = webhookAppServ.UpdateParcelTrackingStatusFromWebHook(strWebHookDataRequest);

        if (updateTrackingResult.WasSuccessful)
        {
            return new HttpStatusCodeResult(HttpStatusCode.OK);  // OK = 200
        }
        else
        {
            return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
        }
    }
}

The Easypost reference you are referencing is implying that you use Basic Authentication + SSL. 您正在引用的Easypost参考暗示您使用的是基本身份验证+ SSL。

You'll need to setup MVC to check for that authentication. 您需要设置MVC来检查该身份验证。 Here is a sample, taken from this article - Basic Authentication in MVC 5 : 这是从本文中获取的样本-MVC 5中的基本身份验证

BasicAuthenticationAttribute BasicAuthenticationAttribute

        public class BasicAuthenticationAttribute : ActionFilterAttribute
        {
            public string BasicRealm { get; set; }
            protected string Username { get; set; }
            protected string Password { get; set; }

            public BasicAuthenticationAttribute(string username, string password)
            {
                this.Username = username;
                this.Password = password;
            }

            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                var req = filterContext.HttpContext.Request;
                var auth = req.Headers["Authorization"];
                if (!String.IsNullOrEmpty(auth))
                {
                    var cred = System.Text.ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(auth.Substring(6))).Split(':');
                    var user = new { Name = cred[0], Pass = cred[1] };
                    if (user.Name == Username && user.Pass == Password) return;
                }
                filterContext.HttpContext.Response.AddHeader("WWW-Authenticate", String.Format("Basic realm=\"{0}\"", BasicRealm ?? "Ryadel"));
                /// thanks to eismanpat for this line: http://www.ryadel.com/en/http-basic-authentication-asp-net-mvc-using-custom-actionfilter/#comment-2507605761
                filterContext.Result = new HttpUnauthorizedResult();
            }
        }

Sample Controler 样品控制器

[BasicAuthenticationAttribute("your-username", "your-password", BasicRealm = "your-realm")]
public class HomeController : BaseController
{
   ...
}

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

相关问题 特殊控制器和动作的自定义mapRoute在MVC中如下所示:http://example.com/someValue - custom mapRoute for special controller and action to be like this in MVC: http://example.com/someValue 路线网址,例如http://www.example.com/{userId} - Route URL such as http://www.example.com/{userId} 如何将非www或非http重定向到https://www.example.com - How to redirect non www or non http to https://www.example.com 如何从http://www.example.com/images/business/113.jpg获取数字 - How to get numbers from http://www.example.com/images/business/113.jpg window.setTimeout(&#39;window.location =“ http://www.example.com”;&#39;,2000); 在后面的代码中 - window.setTimeout('window.location=“http://www.example.com”; ', 2000); in code behind 如何将www.example.com重定向到example.com? - How to redirect www.example.com to example.com? C#MVC-来自另一个项目的HTTP调用控制器 - C# MVC - HTTP call Controller from another project AspNet WebHook不使用身份验证 - AspNet WebHook Not Authenticating with Identity Http GET使用来自MVC控制器的复杂对象调用API端点 - Http GET call to API endpoint with complex object from MVC controller 如何使用 articleName=sample-article-name [MVC Core2.2] 将“www.example.com/sample-article-name”路由到 RazorPage Index.cshtmll - How to route to "www.example.com/sample-article-name" to RazorPage Index.cshtmll with articleName=sample-article-name [MVC Core2.2]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM