简体   繁体   中英

Model binder to decrypt string and convert to int

I have a model which has a property id of type int .

I pass the id in the url like Detail/20 for fetching the data. But, now my customer says they don't want to see the id , since any one can modify and see other records.

Now, I've decided to encrypt and decrypt it, and assign it to another property: 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==/ .

Now, all I need is to decrypt it back to the original form and assign it to the property id of type int .

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 ? Also if any error/exception occurs, it has to redirect to 404 Error page. It might happen when user manually edits some useless text in the url (encrypted 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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