IGIT
IGIT

Reputation: 185

ASP.NET MVC 5 Identity restrict access to account

I find lots of information about Identity but nothing specifically addressing this very common scenario.

I have a controller named ShowAccount() that should display the account data of the currently logged in user, and prevent him from seeing anything but its own account.

Also unauthenticated users should not be able to access this functionality at all.

How do I achieve this?

Thanks

Upvotes: 1

Views: 2233

Answers (2)

K C Frank
K C Frank

Reputation: 19

I had a similar challenge but I got mine

public ActionResult Create()
    {
        return View();
    }

    // POST: ArtistGig/Create
    [HttpPost]
 public ActionResult Create(ArtistGig artistGig)
    {

        var userid = User.Identity.GetUserId();
        ///
        var artist = db.ArtistHubs.SingleOrDefault(a => a.ApplicationUserId == userid).Id;

               artistGig.ArtistHubId = artist;
                db.ArtistGigs.Add(artistGig);
                db.SaveChanges();

                return RedirectToAction("Index");

        }

User.Identity.GetUseId is to query for the loged in user's Id according to the DbContext you are using

Upvotes: 0

LiranBo
LiranBo

Reputation: 2126

Unauthenticated Users

K, I'll start with the simpler request, to block unauthenticated user from having access at all to your controller just add this attribute:

[Authorize]

above your controller, or if you want to allow some\disable some functions in the controller you can place it above the specific function.

In case you want to block your entire controller and allow just a few functions you can use this attribute:

[AllowAnonymous]

Limit user access to his own data

I'm doing something similar in one of my project so I thought it might help, nothing fancy, I would love to hear a better option myself.

For your 2nd issue, I assume that you have a model that stores data and that data has some kind relation to the UserID (foreign key maybe?).

What you can do is in your controler - filter the data you send back to the user, i.e on the view instead of returning:

 return View(db.MyDB.ToList()); 

return:

MyDBClass data = db.MyDB.Where(u => u.UserID == GetUserID()).ToList();
return View(data);

Assume GetUserID() is a function that gives you the current user ID, in case you use the default authentication in MVC I can share it here as well.

This solution tho is not complete, you need to continue enforcing it in any other actions such as edit\delete\create or what ever other actions you support, you need to always check that the user is accessing only his data by comparing between the userID saved in the DB to the one in the request.

Hope this helps.

Upvotes: 1

Related Questions