WEB API – 在控制器或操作级别授权(无身份validation)

我有一个没有身份validation的现有API。 它是一个公共Web API,几个客户通过发出简单的请求来使用它。

现在,需要授权访问某种方法。

有没有办法做到这一点,保持其他控制器和相应的方法为已经使用此Web API的客户端“打开”?

如何识别请求是否有权访问此“受保护”方法?

您需要做的是将[Authorize]属性添加到要保护的方法,可选地使用接受调用用户必须接受的一个或多个角色名称的重载。

然后,您必须实现的是确保调用者的身份validation数据转换为Principal对象的方法。 设置Principal通常是你自己不做的事情,而是让框架为你做。

如果您确实想要提供自己的界面,可以使用实现System.Web.Http.Filters.IAuthenticationFilter接口的身份validation筛选器。

所以你会得到的是:

 [MyAuthentication] [Authorize] public SomeClass MyProtectedMethod() { return new SomeClass(); } 

然后实现MyAuthentication属性。 下面是一个示例,重要的是您使用传入请求的上下文并最终使用新的Principal设置context.Principal属性

 public class MyAuthentication : ActionFilterAttribute, System.Web.Http.Filters.IAuthenticationFilter { public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { // 1. Look for credentials in the request. HttpRequestMessage request = context.Request; AuthenticationHeaderValue authorization = request.Headers.Authorization; // 2. If there are no credentials, do nothing. if (authorization == null) { return; } // 3. If there are credentials but the filter does not recognize the // authentication scheme, do nothing. if (authorization.Scheme != "Basic") { return; } // 4. If there are credentials that the filter understands, try to validate them. // 5. If the credentials are bad, set the error result. if (String.IsNullOrEmpty(authorization.Parameter)) { context.ErrorResult = new AuthenticationFailureResult("Missing credentials", request); return; } Tuple userNameAndPasword = ExtractUserNameAndPassword(authorization.Parameter); if (userNameAndPasword == null) { context.ErrorResult = new AuthenticationFailureResult("Invalid credentials", request); } string userName = userNameAndPasword.Item1; string password = userNameAndPasword.Item2; IPrincipal principal = await AuthenticateAsync(userName, password, cancellationToken); if (principal == null) { context.ErrorResult = new AuthenticationFailureResult("Invalid username or password", request); } // 6. If the credentials are valid, set principal. else { context.Principal = principal; } } ... other interface methods here } 

我希望这可以帮助你走上正确的轨道。 有关更多信息,请查看此post: http : //www.asp.net/web-api/overview/security/authentication-filters

您可以在特定的API方法和控制器级别使用[Authorize]属性。 如果您将[Authorize]属性放在控制器级别,那么您可以对要访问的API方法使用[AllowAnonymous]属性而无需身份validation。

默认情况下,授权在应用程序上全局禁用。 您可以通过添加操作filter[授权]强制您的控制器仅允许授权请求。

 [Authorize] // This will enforce all methods inside should be authorized public class AuthorizeController : ApiController { //this method will only be called if user is authorized public IHttpActionResult GetList() { return Ok(); } } 

您还可以强制仅授权某些方法:

 public class AuthorizeController : ApiController { [Authorize] //this method will only be called if user is authorized public IHttpActionResult GetList() { return Ok(); } // This method can still be called even if user is not authorized public IHttpActionResult GetListUnauthorized() { return Ok(); } } 

或者只是对需要授权的控制器内的某些方法禁用授权:

 [Authorize] public class AuthorizeController : ApiController { //this method will only be called if user is authorized public IHttpActionResult GetList() { return Ok(); } [AllowAnonymous]// This method can be called even if user is not authorized due the AllowAnonymous attribute public IHttpActionResult GetListUnauthorized() { return Ok(); } } 

您还可以使用以下方法设置允许访问方法的人员:

 [Authorize(Users="Joey,Billy")] 

或者使用规则:

 [Authorize(Roles="Administrator,Manager")] 

或者甚至构建一个更复杂的Authorize属性,如本答案(基于声明):声明的授权属性