簡體   English   中英

ASP.NET Core MVC加密/解密QueryString值

[英]ASP.NET Core MVC Encrypt/Decrypt QueryString Values

我正在使用ASP.NET Core 2.0 MVC,C#,Entity Framework Core Code First和SQL Server 2016。

我創建了一個Web表單,並且我所有的CRUD操作都工作正常。 但是,我需要一些有關加密/解密傳遞給確認,編輯和刪除視圖的查詢字符串值的幫助。

當用戶將鼠標懸停在那些操作方法的“編輯”和“刪除”鏈接上時,我還想在“索引”頁面上加密EmployeeID。 我不希望它們在索引頁面上可見。

請在下面查看我的代碼。

楷模

public class Employee
{
    public int EmployeeID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public int DepartmentID { get; set; }
    public Department Department { get; set; }

    public int AppointmentID { get; set; }
    public Appointment Appointment { get; set; }
}

public class Department
{
    public int DepartmentID { get; set; }
    public string Name { get; set; }

    public ICollection<Employee> Employees { get; set; }
}

public class Appointment
{
    public int AppointmentID { get; set; }
    public string TimeSlot { get; set; }

    public ICollection<Employee> Employees { get; set; }
}

DbContext

public class WinTenDbContext : DbContext
{
    public WinTenDbContext(DbContextOptions<WinTenDbContext> options) : base(options)
    { }

    public DbSet<Employee> Employees { get; set; }
    public DbSet<Department> Departments { get; set; }
    public DbSet<Appointment> Appointments { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Employee>()
            .HasKey(e => e.EmployeeID);

        modelBuilder.Entity<Employee>()
            .Property(e => e.FirstName)
            .HasColumnType("varchar(50)")
            .HasMaxLength(50)
            .IsRequired();

        modelBuilder.Entity<Employee>()
            .Property(e => e.LastName)
            .HasColumnType("varchar(50)")
            .HasMaxLength(50)
            .IsRequired();

        modelBuilder.Entity<Department>()
            .HasKey(d => d.DepartmentID);

        modelBuilder.Entity<Department>()
            .Property(d => d.Name)
            .HasColumnType("varchar(50)")
            .HasMaxLength(50);

        modelBuilder.Entity<Appointment>()
            .HasKey(a => a.AppointmentID);

        modelBuilder.Entity<Appointment>()
            .Property(a => a.TimeSlot)
            .HasColumnType("varchar(50)")
            .HasMaxLength(50);
    }
}

視圖模型

public class EmployeeFormVM
{
    public int EmployeeID { get; set; }

    [Required(ErrorMessage = "Please enter your First Name")]
    [Display(Name = "First Name")]
    [StringLength(50)]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Please enter your Last Name")]
    [Display(Name = "Last Name")]
    [StringLength(50)]
    public string LastName { get; set; }

    [Required(ErrorMessage = "Please select your Department")]
    [Display(Name = "Department")]
    public int DepartmentID { get; set; }

    public IEnumerable<Department> Departments { get; set; }

    [Required(ErrorMessage = "Please select your Appointment")]
    [Display(Name = "Appointment")]
    public int AppointmentID { get; set; }

    public IEnumerable<Appointment> Appointments { get; set; }
}

EmployeesController

public class EmployeesController : Controller
{
    private readonly WinTenDbContext _context;

    public EmployeesController(WinTenDbContext context)
    {
        _context = context;
    }

    //// GET: Employees
    //public async Task<IActionResult> Index()
    //{
    //    var winTenDbContext = _context.Employees.Include(e => e.Appointment).Include(e => e.Department);
    //    return View(await winTenDbContext.ToListAsync());
    //}

    public async Task<IActionResult> Index(string sortOrder, string currentFilter, string searchString, int? page)
    {
        ViewData["CurrentSort"] = sortOrder;
        ViewData["FirstNameSortParm"] = sortOrder == "fname" ? "fname_desc" : "fname";
        ViewData["LastNameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "lname_desc" : "";
        ViewData["DeptNameSortParm"] = sortOrder == "deptname" ? "deptname_desc" : "deptname";
        ViewData["DateSortParm"] = sortOrder == "time_slot" ? "time_slot_desc" : "time_slot";

        if (searchString != null)
        {
            page = 1;
        }
        else
        {
            searchString = currentFilter;
        }

        ViewData["CurrentFilter"] = searchString;

        var employees = from s in _context.Employees.Include(e => e.Appointment).Include(e => e.Department)
                        select s;

        if (!String.IsNullOrEmpty(searchString))
        {
            employees = employees.Where(s => s.LastName.Contains(searchString)
                                   || s.FirstName.Contains(searchString));
        }

        switch (sortOrder)
        {
            case "fname":
                employees = employees.OrderBy(s => s.FirstName);
                break;
            case "fname_desc":
                employees = employees.OrderByDescending(s => s.FirstName);
                break;
            case "lname_desc":
                employees = employees.OrderByDescending(s => s.LastName);
                break;
            case "deptname":
                employees = employees.OrderBy(s => s.Department.Name);
                break;
            case "deptname_desc":
                employees = employees.OrderByDescending(s => s.Department.Name);
                break;
            case "time_slot":
                employees = employees.OrderBy(s => s.Appointment.AppointmentID);
                break;
            case "time_slot_desc":
                employees = employees.OrderByDescending(s => s.Appointment.AppointmentID);
                break;
            default:
                employees = employees.OrderBy(s => s.LastName);
                break;
        }

        int pageSize = 10;
        return View(await PaginatedList<Employee>.CreateAsync(employees.AsNoTracking(), page ?? 1, pageSize));
    }

    // GET: Employees/Details/5
    public async Task<IActionResult> Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var employee = await _context.Employees
            .Include(e => e.Appointment)
            .Include(e => e.Department)
            .SingleOrDefaultAsync(m => m.EmployeeID == id);
        if (employee == null)
        {
            return NotFound();
        }

        return View(employee);
    }

    // GET: Employees/Confirmation/5
    public async Task<IActionResult> Confirmation(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var employee = await _context.Employees.Include(d => d.Department).Include(a => a.Appointment)
            .SingleOrDefaultAsync(m => m.EmployeeID == id);

        if (employee == null)
        {
            return NotFound();
        }

        return View(employee);
    }

    // GET: Employees/Create
    public IActionResult Create()
    {
        var departments = _context.Departments.ToList();
        var appointments = _context.Appointments.Include(x => x.Employees).Where(x => !x.Em‌​ployees.Any()).ToLis‌​t();

        var viewModel = new EmployeeFormVM
        {
            Departments = departments,
            Appointments = appointments
        };

        return View(viewModel);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(EmployeeFormVM employee)
    {
        if (ModelState.IsValid)
        {
            var emp = new Employee();
            {
                emp.FirstName = employee.FirstName;
                emp.LastName = employee.LastName;
                emp.DepartmentID = employee.DepartmentID;
                emp.AppointmentID = employee.AppointmentID;
            }

            // Query DB to check if Employee exists with same First/Last Name
            Employee existingEmployee = await _context.Employees.SingleOrDefaultAsync(m => m.FirstName == employee.FirstName && m.LastName == employee.LastName);
            if (existingEmployee != null)
            {
                // Display Error if duplicate employee
                ModelState.AddModelError(string.Empty, "An employee with this name has already registered. Please contact the Service Desk for any scheduling conflicts.");
                employee.Departments = _context.Departments.ToList();
                //employee.Appointments = _context.Appointments.ToList();
                employee.Appointments = _context.Appointments.ToList();
                return View(employee);
            }

            // Query DB to check if appointment has already been assigned to an employee
            Employee existingAppointment = await _context.Employees.SingleOrDefaultAsync(m => m.AppointmentID == employee.AppointmentID);
            if (existingAppointment != null)
            {
                // Display error if the appointment was already chosen
                ModelState.AddModelError(string.Empty, "This appointment has already been taken. Please select another timeslot.");
                employee.Departments = _context.Departments.ToList();
                //employee.Appointments = _context.Appointments.ToList();
                employee.Appointments = _context.Appointments.ToList();
                return View(employee);
            }

            _context.Add(emp);
            await _context.SaveChangesAsync();
            //return RedirectToAction(nameof(Index));

            var newlyCreatedId = emp.EmployeeID;
            return RedirectToAction(nameof(Confirmation), new { id = newlyCreatedId });
        }
        return View(employee);
    }

    // GET: Employees/Edit/5
    public async Task<IActionResult> Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var employeevm = new EmployeeFormVM();
        {
            Employee employee = await _context.Employees.SingleOrDefaultAsync(m => m.EmployeeID == id);

            if (employee == null)
            {
                return NotFound();
            }

            employeevm.EmployeeID = employee.EmployeeID;
            employeevm.FirstName = employee.FirstName;
            employeevm.LastName = employee.LastName;

            // Retrieve list of Departments
            var departments = _context.Departments.ToList();
            employeevm.Departments = departments;
            // Set the selected department
            employeevm.DepartmentID = employee.DepartmentID;

            // Retrieve list of Appointments
            var appointments = _context.Appointments.ToList();
            employeevm.Appointments = appointments;
            // Set the selected department
            employeevm.AppointmentID = employee.AppointmentID;
        }
        return View(employeevm);
    }

    // POST: Employees/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(EmployeeFormVM vmEdit)
    {
        if (ModelState.IsValid)
        {
            Employee employee = _context.Employees.SingleOrDefault(e => e.EmployeeID == vmEdit.EmployeeID);

            if (employee == null)
            {
                return NotFound();
            }

            employee.FirstName = vmEdit.FirstName;
            employee.LastName = vmEdit.LastName;
            employee.DepartmentID = vmEdit.DepartmentID;
            employee.AppointmentID = vmEdit.AppointmentID;

            try
            {
                _context.Update(employee);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!EmployeeExists(vmEdit.EmployeeID))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction(nameof(Index));
        }
        return View(vmEdit);
    }

    // GET: Employees/Delete/5
    public async Task<IActionResult> Delete(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var employee = await _context.Employees
            .Include(e => e.Appointment)
            .Include(e => e.Department)
            .SingleOrDefaultAsync(m => m.EmployeeID == id);
        if (employee == null)
        {
            return NotFound();
        }

        return View(employee);
    }

    // POST: Employees/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> DeleteConfirmed(int id)
    {
        var employee = await _context.Employees.SingleOrDefaultAsync(m => m.EmployeeID == id);
        _context.Employees.Remove(employee);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    private bool EmployeeExists(int id)
    {
        return _context.Employees.Any(e => e.EmployeeID == id);
    }
}

建立檢視

@using (Html.BeginForm("Create", "Employees"))
    {
        @Html.ValidationSummary(true, "", new { @class = "validation-summary-errors" })

        <div class="form-group">
            @Html.LabelFor(e => e.FirstName)
            @Html.TextBoxFor(e => e.FirstName, new { @class = "form-control" })
            @Html.ValidationMessageFor(e => e.FirstName)
        </div>

        <div class="form-group">
            @Html.LabelFor(e => e.LastName)
            @Html.TextBoxFor(e => e.LastName, new { @class = "form-control" })
            @Html.ValidationMessageFor(e => e.LastName)
        </div>

        <div class="form-group">
            @Html.LabelFor(d => d.DepartmentID)
            @Html.DropDownListFor(d => d.DepartmentID, new SelectList(Model.Departments, "DepartmentID", "Name"), "", new { @class = "form-control" })
            @Html.ValidationMessageFor(d => d.DepartmentID)
        </div>

        <div class="form-group">
            @Html.LabelFor(a => a.AppointmentID)
            @Html.DropDownListFor(a => a.AppointmentID, new SelectList(Model.Appointments, "AppointmentID", "TimeSlot"), "", new { @class = "form-control" })
            @Html.ValidationMessageFor(a => a.AppointmentID)
        </div>

        <div class="form-group">
            <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    }

編輯視圖

@using (Html.BeginForm("Edit", "Employees"))
    {
        <div class="form-group">
            @Html.LabelFor(e => e.FirstName)
            @Html.TextBoxFor(e => e.FirstName, new { @class = "form-control" })
            @Html.ValidationMessageFor(e => e.FirstName)
        </div>

        <div class="form-group">
            @Html.LabelFor(e => e.LastName)
            @Html.TextBoxFor(e => e.LastName, new { @class = "form-control" })
            @Html.ValidationMessageFor(e => e.LastName)
        </div>

        <div class="form-group">
            @Html.LabelFor(d => d.DepartmentID)
            @Html.DropDownListFor(d => d.DepartmentID, new SelectList(Model.Departments, "DepartmentID", "Name"), "", new { @class = "form-control" })
            @Html.ValidationMessageFor(d => d.DepartmentID)
        </div>

        <div class="form-group">
            @Html.LabelFor(a => a.AppointmentID)
            @Html.DropDownListFor(a => a.AppointmentID, new SelectList(Model.Appointments, "AppointmentID", "TimeSlot"), "", new { @class = "form-control" })
            @Html.ValidationMessageFor(a => a.AppointmentID)
        </div>

        @Html.HiddenFor(e => e.EmployeeID)

        <div class="form-group">
            <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    }

確認視圖

<div class="col-md-12">
    <img src="~/images/confirm.png" />
    <h2>Thank you @Html.DisplayFor(model => model.FirstName) @Html.DisplayFor(model => model.LastName)!</h2>    
    <p>Your <b>@Html.DisplayFor(model => model.Appointment.TimeSlot)</b> appointment has been booked. If you need to reschedule this appointment, please call the Service Desk at x1380.</p>
</div>

@Max是正確的。 IDataProtectionProvider是您要查看的內容。

IDataProtectionProvider可以在Windows或UNIX上使用。

的確,它不能用作客戶端javascript庫,但仍有多種方法可以利用它。

最簡單的方法是先加密ID,然后再將視圖的html發送到瀏覽器,然后將加密的ID包含在html data-attribute等屬性中,在這種情況下,您的客戶端javascript可以訪問該ID以回發(或在查詢字符串中使用您可以選擇)和修改或刪除請求。

以下是如何在控制器中使用IDataProtectionProvider加密和解密ID的示例。

 public class HomeController : Controller{
     IDataProtector dataProtector;

     public HomeController(IDataProtectionProvider provider){
         dataProtector = provider.CreateProtector(GetType().FullName);
     }

    [HttpGet]
    public IActionResult Get() {
        int id = 1234;

        string encryptedId = dataProtector.Protect(id.ToString());

        int decryptedId = 0;
        if(int.TryParse(dataProtector.Unprotect(encryptedId), out decryptedId) == false){
            throw new Exception("Invalid cypher text");
        }

        //at this point decryptedId contains the decrypted value.

   }

請注意,在上面創建此dataProtector時,它將使用GetType().FullName作為加密“用途”。 這是.net核心框架代碼中常見的一種做法。 “目的”在進行加密時用作附加的上下文數據,並且本質上用於派生用於加密/解密數據的特定於目的的子密鑰。 在這種情況下,由於我將其設置為GetType().FullName因此它將是控制器的標准名稱。 如果您要使用同一控制器進行加密和解密,那就太好了,它將沒有問題。 但是 ,如果要在一個控制器中加密,而在另一個控制器(或與此相關的任何其他類)中解密, dataProtector = provider.CreateProtector(purpose);知道的重要一點是,在此行中傳遞的目的字符串為dataProtector = provider.CreateProtector(purpose); 用於解密的dataProtector必須與用於加密的dataProtector相同。 (即,如果用於解密的類不同於用於加密的類,則不能是該類的名稱)。

此外,這是一篇您可能會發現有用的文章: https : //www.mikesdotnetting.com/Article/295/encryption-and-decryption-in-asp-net-core

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM