我的场景如下:
我已经为移动应用程序创建了WEB API。
- 令牌调用 - 它返回授权令牌成功和barer令牌 详
- GetCompanyDetails(int loginId)
- GetCompanyCustomer(int companyId)
我在数据库中有如下表:
登录表:
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
公司明细表:
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
客户明细表:
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
公司客户表:
ID | CompanyID | CustomerID
1 | 5 | 10
1 | 5 | 12
2 | 7 | 13
一旦我授权了API,那么在我调用该方法以获取公司客户之后。 那次我正在传递公司 ID 以获得客户。.
[HttpGet]
[Authorize(Roles=("Company")]
public List<Customer> CompanyCustomer(int companyId)
{
//Return the list of customer by companyId
}
我的观点是如何验证令牌授权时是同一用户的用户。
假设我要求
- ALEX 公司的公司 ID = 5,那么我称公司客户(5) 它 将返回所有客户
- 之后应该调用公司客户(7),然后它仍然返回另一家公司的所有客户。
如何通过请求的用户检测该 API 调用方令牌?
如何处理这种安全性?
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;
}
在身份验证时:
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);
}
}
}