注意:我在下面的代碼註釋中散佈了很多問題。我也需要這些答案。我在哪裏處理webapi中的自定義身份驗證和授權?
我已閱讀(以及許多其他)下面的文章:
- http://blogs.msdn.com/b/hongmeig1/archive/2012/05/11/how-to-write-a-custom-parameter-binding-to-construct-an-object-either-from-body-or-from-uri-s-query.aspx
- http://blogs.msdn.com/b/jmstall/archive/2012/05/11/webapi-parameter-binding-under-the-hood.aspx
我想爲我的網絡API有使用授權的標頭中發送認證頭。我想將這個頭文件填充到名爲AuthenticationToken
的c#類中。然後,當我在做參數綁定時,我想檢索此前創建的AuthenticationToken
對象,並將其傳遞給我的控制器操作。舉例來說,如果我有以下控制器
public class MyServiceController : ApiController {
readonly ISecurityService _security;
readonly IMyService _myService;
// constructor values are injected
public MyServiceController(ISecurityService security, IMyService myService) {
_security = security;
_myService = myService;
}
public SomeData GetASpecificItem(AuthenticationToken token, int id) {
if (_security.IsAuthorized(token, Permissions.Read)) {
return myService.DoStuffToGetSomeData(token);
} else {
var msg = new HttpResponseMessage(HttpStatusCode.Forbidden);
throw new HttpResponseException(msg);
}
}
}
和下面的參數綁定類
public class AuthenticationTokenParameterBinding
: HttpParameterBinding { // do I need to inherit from a different class?
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider,
HttpActionContext actionContext,
CancellationToken cancellationToken) {
try {
AuthenticationToken token; // UPDATED: how can i get this from the data
// available from inside this method?
SetValue(actionContext, token);
// is this the correct task to return on successfull parameter binding?
return base.ExecuteBindingAsyn(metadataProvider, actionContext, cancellationToken);
} catch {
return Task<HttpResponseMessage>.Factory.StartNew(() => {
var hpm = new HttpResponseMessage(HttpStatusCode.Unauthorized);
hpm.Headers.Add("WWW-Authenticate","MyCustomScheme");
return hpm;
});
}
}
}
如果這兩個都正確實施,那麼控制器會自動獲取被授權期間創建的AuthenticationToken
實例。
我不知道在這個過程之前認證的地方。我也不知道如何在身份驗證和授權之間傳遞對象。
UPDATE: 我不能使用自定義AuthorizeAttribute
,因爲授權可以是針對對象:
public SaveResponse Save(AuthenticationToken user, SomeObjectThatNeedsToBeSaved obj) {
// NOTE: permissions are checked between the object and the user, not a role
if (_security.IsAuthorized(user, obj, Permission.Modify, Permission.Create)) {
// NOTE: other permissions we don't know about may need to be checked in the service call
return new SaveResponse {
Success = ISomeService.Save(user, obj); // bool return value
}
} else {
// return 403 Forbidden }
}
我需要通過令牌控制器動作,但我還需要驗證令牌傳遞給控制器之前。由於基於這一切並不一定作用,我不知道怎樣才能從自定義AuthorizeAttribute
我無法使用基於角色的安全性。此方法不起作用。這就是爲什麼我試圖以我提出的問題的方式來做到這一點。 –
此方法不排除基於角色的授權方法。如果你不使用角色,你在授權什麼?針對物體的 –
,例如該用戶是否具有對xyz對象的修改權限?另外,我的問題是關於認證,而不是授權。授權在代碼中完成。這就是爲什麼我需要方法簽名中的身份驗證令牌。 –