Sco*_*ott 8 c# authentication custom-attributes asp.net-web-api2
我想利用AllowAnonymous和习惯AuthenticationFilter.有人能指出我正确的方向使用AllowAnonymous或另一种选择吗?谢谢
我创建了自己的自定义过滤器,它继承自System.Attribute并实现System.Web.Http.Filters.IAuthenticationFilter
public class MyCustomAuthenticationAttribute : Attribute, IAuthenticationFilter
Run Code Online (Sandbox Code Playgroud)
我已经能够成功添加该AuthenticateAsync方法的逻辑
public async Task AuthenticateAsync(
HttpAuthenticationContext context,
CancellationToken cancellationToken) {}
Run Code Online (Sandbox Code Playgroud)
我的问题是我需要忽略一些Web API控制器操作或控制器.我以为我可以System.Web.Http.AllowAnonymousAttribute用来做这个.例如,这是一个显示意图的非常简单的示例.
[MyCustomAuthentication]
public class HomeController : ApiController
{
// no authentication needed allow anonymous
[HttpGet]
[Route("hianonymous")]
[AllowAnonymous]
public IHttpActionResult Hello(string name) {
return Ok(new { message = "hello " + name });
}
// needs to be authenticated
[HttpGet]
[Route("hiauthenticated")]
public IHttpActionResult Hello() {
var name = User.Identity.Name;
return Ok(new { message = "hello authenticated user " + name });
}
}
Run Code Online (Sandbox Code Playgroud)
问题是Authenticate()仍然需要调用MyCustomAuthenticationAttribute.我想使用AllowAnonymous或其他一些方法来实现这一目标.感谢您的任何意见.
我知道我可以在操作级别而不是控制器级别使用我的自定义身份验证属性,但有些情况下我想要整个控制器甚至作为全局过滤器,因此我需要能够在单个操作或控制器的基础上排除.
hat*_*cyl 10
如果找不到它无法识别的授权方案,那么您的实现IAuthenticationFilter应该没有.
http://www.asp.net/web-api/overview/security/authentication-filters
// 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;
}
Run Code Online (Sandbox Code Playgroud)
我们的想法是,您的过滤器只是一种使用已知方案进行AUTHENTICATE的方法.
您仍然需要使用内置AuthorizeAttribute和AllowAnonymousAttribute控制AUTHORIZATION.
| 归档时间: |
|
| 查看次数: |
10439 次 |
| 最近记录: |