Search code examples
c#asp.net-mvcasp.net-identitycrud

Prevent users to not delete if not logged in


I am currently working with CRUD in identity. But I can crack this. I am trying, to make it so that you can ONLY delete if logged in.

I have tryed by adding if (User.Identity.IsAuthenticated) But that isn't working, it send me to login page AFTER you had entered the delete page. This is my controller:

public ActionResult _RemoveItems()
    {
        var Items = db.CreatePosts.ToList();

        return PartialView(Items);
    }

    [HttpPost]
    public ActionResult _RemoveItem(int Id)
    {
        if (HttpContext.User.Identity.IsAuthenticated)
        { 
            CreatePost CreatePost = db.CreatePosts.Find(Id);
            if (CreatePost != null)
            {
                db.CreatePosts.Remove(CreatePost);
                db.SaveChanges();
            }
        }
        return RedirectToAction("Index", "Manage");
    }

And this is my delete

@Html.ActionLink("Slet", "_RemoveItem", "Home", new { @id = item.Id }, new { @class = "btn btn-danger" })

What am i doing wrong, since i can't make it so you need to be logged in before you can enter the page _RemoveItem


Solution

  • You can use the [Authorize] attribute, in a line above your method:

    [Authorize]
    public ActionResult _RemoveItems()
    

    This will require anyone accessing that method to be logged in, period.

    You can also add more parameters to the Authorize attribute to manage what roles are allowed and so on.

    As in:

    [Authorize(Roles="SpecialRole, OtherRole")]
    

    In this case, the method only allows users in the 'SpecialRole' role and/or the 'OtherRole' role, or in both roles to have access.