WebApi中具有AllowAnonymous属性的身份验证 [英] Authentication in WebApi with AllowAnonymous attribute

查看:280
本文介绍了WebApi中具有AllowAnonymous属性的身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过继承 DelegatingHandler 并将类添加为 configuration.MessageHandlers.Add(new MyDelegatingHandler()),实现了基于JWT的身份验证.

在实现 DelegatingHandler 时,我覆盖了 Task< HttpResponseMessage>SendAsync(HttpRequestMessage请求,CancelationToken cancelToken).那里的逻辑很简单-我从 Authorization 标头中检索令牌,检查其有效性.如果有效,请设置 Thread.CurrentPrincipal HttpContext.Current.User ,否则返回 new HttpResponseMessage(HttpStatusCode.Unauthorized)

基本上看起来像这样(非常简化):

 公共类TokenValidationHandler:DelegatingHandler{受保护的覆盖任务< HttpResponseMessage>SendAsync(HttpRequestMessage请求,CancellationToken cancelToken){var token = GetTokenFromAuthorizeHeader(request);如果(TokenIsValid(token)){varPrincipal = CreatePrincipal(token);Thread.CurrentPrincipal =主体;HttpContext.Current.User =主体;返回base.SendAsync(request,cancelToken);} 别的 {//TODO:修复返回Task< HttpResponseMessage> .Factory.StartNew(()=>新的HttpResponseMessage(HttpStatusCode.Unauthorized));}}} 

现在,即使在具有 [AllowAnonymous] 属性的WebApi方法上,也将调用此方法.这很好,因为即使该方法允许匿名,我也想设置主体.但是,如果 Authorization 标头中提供的令牌无效,则此逻辑将失败.

用户使用 [AllowAnonymous] 向资源发送请求,并且在 Authorization 标头中使用无效的令牌,这应该通过,因为资源允许匿名使用,但是我的代码会检查授权,发现令牌无效,并发送 HttpStatusCode.Unauthorized .

解决方法是检查//TODO:fix 在哪里,用户访问的资源是否允许匿名,并且仅发送 HttpStatusCode.Unauthorized 不是,但是我不知道如何正确地做到这一点.

我该怎么做?

解决方案

1.身份验证过滤器

使用身份验证过滤器,引入了Web API 2.它们仅执行身份验证,但是对于用户是否有权访问资源一无所知.正是您所需要的.

 公共类JwtAuthenticationFilter:IAuthenticationFilter{公共任务AuthenticateAsync(HttpAuthenticationContext上下文,CancellationToken cancelToken){var token = GetTokenFromAuthorizeHeader(context.Request);如果(TokenIsValid(token)){varPrincipal = CreatePrincipal(token);//使用context.Principal而不是Thread.CurrentPrincipal//和HttpContext.Current.User.context.Principal =主体;}返回Task.CompletedTask;}//TODO:实现其余的IAuthencitaionFilter成员.} 

全局应用此 JwtAuthenticationFilter 对所有请求执行身份验证:

 //httpConfig是HttpConfiguration的实例httpConfig.Filters.Add(new JwtAuthenticationFilter()); 

以这种方式,如果令牌正常,则对用户进行身份验证.但是,仍然所有用户都可以访问您的API,即使是使用无效令牌的用户也是如此.让我们进一步保护它.

2.AuthorizeAttribute

解决方案

1. Authentication Filter

Use Authentication Filters, which Web API 2 introduced. They perform just authentication, but say nothing about if user has access to a resource or not. Exactly what you need.

public class JwtAuthenticationFilter : IAuthenticationFilter
{
    public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
    {
        var token = GetTokenFromAuthorizeHeader(context.Request);
        if (TokenIsValid(token)) {
            var principal = CreatePrincipal(token);
            // Use context.Principal instead of Thread.CurrentPrincipal
            // and HttpContext.Current.User whenever.
            context.Principal = principal;
        }
        return Task.CompletedTask;
    }

    // TODO: Implement remaining IAuthencitaionFilter members.
}

Apply this JwtAuthenticationFilter globally to perform authentication for all requests:

// httpConfig is an instance of HttpConfiguration
httpConfig.Filters.Add(new JwtAuthenticationFilter());

In this way user is authenticated if token is OK. But still all users have access to your API - even the ones with invalid token. Let's move further and protect it.

2. AuthorizeAttribute

AuthorizeAttribute is what you need to restrict access to Web API from unauthenticated users. You can apply it globally by using the same approach as above:

httpConfig.Filters.Add(new AuthorizeAttribute());

The one who doesn't have valid token won't pass. Good. The last step is to allow access to some particular resources for users with invalid tokens.

3. AllowAnonymousAttribute

From now on AllowAnonymousAttribute should work. Basically AuthorizeAttribute just checks if resource is marked by [AllowAnonymous] and skips authorization in this case.


Conclusion

Generally Web API is protected from unauthenticated users, but some resources can disable authorization by applying [AllowAnonymous]. JwtAuthenticationFilter we implemented above works in any case, so users with valid token will be always authenticated - even if a resource allows anonymous access.

这篇关于WebApi中具有AllowAnonymous属性的身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆