简体   繁体   中英

c# User Authorization

I'm building a web app (asp.net mvc), where i'm using the attribute [Authorize] on GET and Post.

For example:

 [Authorize]
public ActionResult EditClient(string id)
{
//Do Stuff
}

I now want to look to ensure that the logged in user, can only access data that belongs to that user\\account? But I'm not sure how to do this, does .Net already provide methods\\attributes to use?

For example, this is how I would get a client:

    [Authorize]
    public ActionResult EditClient(string id)
    {
    var user= new Token(this.User.Identity.Name);
    //user.id
    //user.accountId

    //So does this Client belong to the same account as the user is in?
    //We know the client and user both belong to an account(id)
    //Are we allowed to return the below?
    var client = _clientService.GetClient(id);
    //client.id
    //client.accountId
    }

As mentioned not to sure what best practice\\options I should apply, obviously I know I should apply this kind of logic in most places?

Ideas? Sample?

There are many ways you could achieve this. for example you could create a custom attribute that takes in the parameter and checks the resource belongs to the requesting user. This could get complex as you'd have many different attributes for each type of entity you are accessing.

You probably want other validation rules such as the requested client even exists (ie non existing id) I would extract a bunch of rules out such as entity exists, requested entity belongs to authorised user, entity is editable etc etc and inject that into your actions before performing changes or returning said entities, you could throw custom exceptions depending on which validation fails and then send a generic 500, or 400 down to the user with minimal error details (no stack trace). So your action could look something like:

   [Authorize]
    public ActionResult EditClient(string id)
    {
        editClientValidator.Validate(id);

    var user= new Token(this.User.Identity.Name);
    //user.id
    //user.accountId

    //So does this Client belong to the same account as the user is in?
    //We know the client and user both belong to an account(id)
    //Are we allowed to return the below?
    var client = _clientService.GetClient(id);
    //client.id
    //client.accountId
    }

Where the EditClientValidator class contains your custom rules for editing a client. Alternatively you could create an attribute essentially doing the same thing but only for access (client belongs to the authenticated user)

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