简体   繁体   中英

ASP.NET MVC - Allow Users to only modify their own data

I have a UserProfile model which has a one-to-(one or zero) relationship with AspNetUser.

UserProfile:

public class UserProfile
{
    public int Id { get; set; }

    public virtual ApplicationUser ApplicationUser { get; set; }

    [Required]
    [Display(Name = "Full Name")]
    public string FullName { get; set; }
}

How do I verify that the UserProfile being modified is the users own data? I have placed an [Authorize] attribute on my POST and GET methods for Edit, but I still have to verify that a user is editing their own data.

Can this be done using another Attribute so I don't have to repeat code in my methods, if so how do I code it?

They usually use Autorize attribute it in general principles.

To make sure that the operation is legal according to the input, the simplest way is to check in the method controller (ActionResult function) whether the current user is equal to the user to whom the editing is performed:

[HttpPost]
public ActionResult Edit(UserProfile model)
{
    if(User.Identity.GetUserId() != model.ApplicationUser.Id)
        return new HttpUnauthorizedResult();

    ...
}

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