aspnet/DataProtection

Is it good way for protecting the form model using Protect/Unprotect in MVC

Closed this issue · 2 comments

Jenan commented

Hello,

I have tried create the Asp.Net Core MVC app where I want to protect the form model especially Id.

I have found the posibility with DataProtection with method - Protect and Unprotect string.

I've used this implementation:

    public class HomeController : Controller
        {
            readonly IDataProtector _protector;
            private readonly IUserRepository _userRepository;
    
            public HomeController(IDataProtectionProvider provider, IUserRepository userRepository)
            {
                _protector = provider.CreateProtector("DataProtectionDemo.Controllers.HomeController");
                _userRepository = userRepository;
            }
    
            [HttpGet]
            public async Task<IActionResult> Index(int id)
            {
                var user = await _userRepository.GetUserDetail(id);
    
                user.Id = _protector.Protect(user.Id);
    
                return View(user);
            }
    
            [HttpPost]
            public async Task<IActionResult> Index(UserViewModel model)
            {
                try
                {
                    model.Id = _protector.Unprotect(model.Id);
    
                    await _userRepository.SaveUser(model);
    
                    return RedirectToAction(nameof(Index));
                }
                catch (Exception e)
                {
                    model.Error = e.Message;
    
                    return View(model);
                }
            }

In this case I want to protect UserId in hidden field with encrypted string, but I don't know if this using of Dataprotection is correct way. I know of posibilities around Authorization Policy and it might be next step check user permission but I am wondering about this additional way as create better protection.

Is it good way how protect the form model?

Thank you for any suggestions.

It'd work just fine :)

Jenan commented

OK, it works fine but I didn't know if this use case with encrypting string in mvc it's correct way how do that :)
Thank you