简体   繁体   中英

How to manage security over web methods using Web API?

My scenario is as below:

I have created WEB API for mobile app..

  • TOKEN CALL - It returning the authorize token success & barer token details
  • GetCompanyDetails(int loginId)
  • GetCompanyCustomer(int companyId)

I have table in Database as following :

Login Table:

ID| Username | Password | UserType | CreatedDate
1 | Alex | P#ssword | Company  | 2017-05-04
2 | Jhon | 4548@sd  | Company  | 2017-05-10
3 | Rubby | R#$S3343| Customer | 2017-05-11
4 | Moris | M#$353  | Customer | 2017-05-11
5 | Febio | Feb@153  | Customer | 2017-05-11 

CompanyDetails Table:

ID | LoginID | CompanyName | Address | CreatedDate | Location
5  |  1      | ALEX Company| Street 1| 2017-05-04  | USA
7  |  2      | JHON INC    | NJ, OPP PR market| 2017-05-10 | USA

CustomerDetails Table:

ID | LoginID | Address   | CreatedDate | Location
10  |  3      | Address 1| 2017-05-11  | USA
12  |  4      | Address 2| 2017-05-11 | USA
13  |  5      | Address 3| 2017-05-11 | USA

CompanyCustomer Table:

ID | CompanyID | CustomerID
1  |  5        | 10
1  |  5        | 12
2  |  7        | 13

Once I authorized the API then after I am calling the method to get company customers. that time I am passing the companyID to get customer..

[HttpGet]
[Authorize(Roles=("Company")]
public List<Customer> CompanyCustomer(int companyId)
{
 //Return the list of customer by companyId

}

My point is how to verify the user that are same user when Token authorized .
suppose I request with

  • ALEX Company's CompanyID = 5 then I call the CompanyCustomer(5) it will return all customer
  • after that supposed to call the companyCustomer(7) then still it returning the all customer of another company.

    How to detect that API caller token by requested user?

How to handle this kind of security?

public sealed class PrivateAttribute : Attribute, IAuthorizationFilter {
    public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(
        HttpActionContext actionContext,
        CancellationToken cancellationToken,
        Func<Task<HttpResponseMessage>> continuation) {
        var claimsPrincipal = actionContext.RequestContext.Principal as ClaimsPrincipal;
        if (actionContext.RequestContext.RouteData.Values.ContainsKey(CONSTANTS.USER_ID_KEY) && claimsPrincipal != null) {
            var requestedID = actionContext.RequestContext.RouteData.Values[CONSTANTS.USER_ID_KEY];
            if (claimsPrincipal.HasClaim(CONSTANTS.USER_ID_KEY, requestedID.ToString())) {
                return continuation();
            } else { // someone is trying to get resources of another user
                return whatever fail;
            }
        } else { // there is no {id} paramter in the route, nothing to do
            return continuation();
        }
    }

    public bool AllowMultiple => false;
}

And at the time of auth:

public override async Task GrantResourceOwnerCredentials(
        OAuthGrantResourceOwnerCredentialsContext context) {
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
        using (var authRepo = AuthRepository.Create()) {
            var findUserResult = await authRepo.FindUser(context.UserName, context.Password);
            if (findUserResult == UserModel.NoUser) {
                context.SetError("error", "User not found.");
            } else {
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim( // this is important, [PrivateAttribute] relies on this
                    new Claim(CONSTANTS.USER_ID_KEY, findUserResult.ID.ToString()));
                context.Validated(identity);
            }
        }
    }

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