简体   繁体   English

模型绑定程序以解密字符串并将其转换为int

[英]Model binder to decrypt string and convert to int

I have a model which has a property id of type int . 我有一个模型,其属性idint类型。

I pass the id in the url like Detail/20 for fetching the data. 我在URL中传递了id ,例如Detail/20以获取数据。 But, now my customer says they don't want to see the id , since any one can modify and see other records. 但是,现在我的客户说他们不想看到id ,因为任何人都可以修改并查看其他记录。

Now, I've decided to encrypt and decrypt it, and assign it to another property: encId . 现在,我决定对其进行加密和解密,并将其分配给另一个属性: encId

public ActionResult List()
{
    foreach(Employee e in empList)
    {
        e.encId = MyUtil.Encrypt(id,"sessionid");    
    }

    return View(empList);
}

Finally, I make my url like Detail/WOgV16ZKsShQY4nF3REcNQ==/ . 最后,我将自己的网址设置为Detail/WOgV16ZKsShQY4nF3REcNQ==/

Now, all I need is to decrypt it back to the original form and assign it to the property id of type int . 现在,我所需要做的就是将其解密回原始形式,并将其分配给int类型的属性id

public ActionResult Detail(int id) //don't want (string id)
{

}

How can I write my model binder that decrypt and convert it to valid id ? 如何编写解密并转换为有效id模型资料夹? Also if any error/exception occurs, it has to redirect to 404 Error page. 同样,如果发生任何错误/异常,它也必须重定向到404错误页面。 It might happen when user manually edits some useless text in the url (encrypted id). 当用户手动编辑url(加密的ID)中一些无用的文本时,可能会发生这种情况。

First, this is not the way to go about securing your website and data. 首先,这不是确保网站和数据安全的方法。 Please take a look at the issues with Security Through Obscurity . 请看一下“ 通过隐蔽性实现安全性 ”问题。 You would be better off defining sets of permissions on each employee record and who can or cannot edit them. 您最好在每个员工记录上定义权限集,以及可以或不能编辑它们的权限。 Such an example could look like this: 这样的例子可能看起来像这样:

public ActionResult Detail(int id)
{
    if(MySecurityProvider.CanView(id, HttpContext.Current.User.Identity.Name){
        return View();
    }
    Return RedirectToAction("PermissionIssue", "Errors");
}

With that said, to continue on the path you are on, simply do the decryption within the action result. 话虽如此,要继续您的工作,只需在操作结果内进行解密即可。

public ActionResult Detail(string Id)
{
    int actualId;
    try{
       actualId = MyUtil.Decrypt(id);
    }catch(Exception e){
         //someone mucked with my encryption string
         RedirectToAction("SomeError", "Errors");
    }
    var employee = MyEmployeeService.GetEmployeeById(actualId);
    if(employee == null){
         //This was a bad id
         RedirectToAction("NotFound", "Errors");
    }
    Return View(employee);
}

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

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