c# - 如何检查和验证令牌的标头?
问题描述
我正在尝试在我的搜索功能中使用令牌。当我使用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);
}
解决方案
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);
}
推荐阅读
- php - 寻找 php7 函数的 php5 等效语法
- mongodb - 我如何将在 $match 阶段内传递给 $in 运算符的每个 ID 限制为仅 4 个元素
- javascript - 如何将类重写为普通对象?
- javascript - JavaScript 等效于 Java 的 String.getBytes(StandardCharsets.UTF_8)
- forms - 当使用其他表单输入时,如何阻止谷歌地图自动完成结果消失?
- java - 为什么 java Base64 运行与 eclipse 和 jar 不同
- rest - 如何使用 ureq 发布登录请求?
- r - 在 R 中不使用 PAM 创建自己的 k-medoids 算法?
- r - 为什么我的代码会得到不同的结果?
- python - Pandas groupby 分组返回值而不是索引