首页 > 解决方案 > 如何检查和验证令牌的标头?

问题描述

我正在尝试在我的搜索功能中使用令牌。当我使用token搜索时,它只会检查token的header来识别请求应该全部通过。如果错误,则取消请求并返回。

请求 JSON

{ 
"header": { 
"Token": "558fedce-a84e-4a9a-8698-5cd27d5af3ed"
},
"body": { 
"WarehouseCode": "W001", 
"CompanyCode": "C001"
}
}

索引.cshtml

<div class="row">
    <div class="col-md-4">
        @using (Html.BeginForm("Index", "Home", FormMethod.Post))
        {
        @Html.TextArea("track") <input type="submit" value="Track"/>
        }
    </div>
</div>

模型.cs

   public class GetInvBalReq
    {
        public class GetData
        {
            public Header header { get; set; }
            public Body body { get; set; }
        }

        public class Header
        {
            public string Token { get; set; }
        }

        public class Body
        {
            public string WarehouseCode { get; set; }
            public string CompanyCode { get; set; }
        }
    }

家庭控制器.cs

这是搜索功能的控制器

   [System.Web.Mvc.HttpPost]
        public ActionResult Index(string track)
        {

            UploadToBCSSoftSCM b = new UploadToBCSSoftSCM();
                string response = b.GetInvBal(track);
                var data = JsonConvert.DeserializeObject<Rootobject>(response);

            return View(data);
        }

标签: c#jsonasp.net-web-api

解决方案


public class TokenAuthorize: ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        //gettting token from headers
        IEnumerable<string> values;
        if (!actionContext.Request.Headers.TryGetValues("Token", out values) || values.Count() > 1)
        {
         //if no token header found in rquest
        actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
        }
        else
        {
        //here is logic to validate your token
        //if token is not proper than you can set response as unauthorized as above
        }
    }
}

然后在上述方法上添加属性,如:

[TokenAuthorize]
    public ActionResult Index(string track)
    {

        UploadToBCSSoftSCM b = new UploadToBCSSoftSCM();
            string response = b.GetInvBal(track);
            var data = JsonConvert.DeserializeObject<Rootobject>(response);

        return View(data);
    }

推荐阅读