c# - 授权属性忽略 [AllowAnonymous]

标签 c# asp.net-web-api authorization custom-attributes

我在我的 asp.net web api 中设置了一个客户授权属性

全局文件:

  FilterConfig.RegisterHttpFilters(GlobalConfiguration.Configuration.Filters);

过滤配置.cs

public static void RegisterHttpFilters(System.Web.Http.Filters.HttpFilterCollection filters)
    {
        filters.Add(new TokenAuthentication(""));
    }

认证类:

  public class TokenAuthentication : Attribute, IAuthenticationFilter
{
    private readonly string realm;

    public bool AllowMultiple { get { return false; } }

    public TokenAuthentication(string realm)
    {
        this.realm = "realm=" + realm;
    }      

    public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
    {
        var request = context.Request;

        // Receive token from the client. Here is the example when token is in header:
        string token = null;

        if (request.Headers.Contains("Token"))
        {
            token = request.Headers.GetValues("Token").FirstOrDefault();
        }

        if (token != null && token != "")
        {
            // Get your secret key from the configuration
            var secretKey = ConfigurationManager.AppSettings["JWTSecurityKey"];

            try
            {
                //Get the Payload from the token
                string jsonPayload = JWT.JsonWebToken.Decode(token, secretKey);

                int separatorIndex = jsonPayload.IndexOf(';');
                string userId = "";
                DateTime timeIssued = DateTime.MinValue;
                if (separatorIndex >= 0)
                {
                    //userId = UTF8Encoding.UTF8.GetString(Convert.FromBase64String(jsonPayload.Substring(0, separatorIndex)));
                    userId = jsonPayload.Substring(1, separatorIndex - 1);
                    string tmpTime = jsonPayload.Substring(separatorIndex + 1, (jsonPayload.Length - separatorIndex) - 2);
                    timeIssued = DateTime.Parse(tmpTime);
                }

                short TokenTTL = 10;                //minuets
                //Int16.TryParse(ConfigurationManager.AppSettings["TokenTTL"],TokenTTL);               

                // if ((DateTime.Now.Subtract(timeIssued).TotalMinutes >= TokenTTL))
                if ((DateTime.Now.Subtract(timeIssued).TotalMinutes < 0))
                {
                    context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request);
                }
                else
                {
                    //Save user in context                
                    var claims = new List<Claim>()
                    {
                        new Claim(ClaimTypes.Name, userId)
                    };
                    var id = new ClaimsIdentity(claims, "Basic");
                    var principal = new ClaimsPrincipal(new[] { id });

                    // Set the user name to the user id in the httpcontext which is passed to the controller
                    context.Principal = principal;
                }

            }
            catch (JWT.SignatureVerificationException)
            {
                context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request);
            }
        }
        else
        {
            return Task.FromResult(0);
        }
        return Task.FromResult(0);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
    {
        context.Result = new ResultWithChallenge(context.Result, realm);
        return Task.FromResult(0);
    }
}

/// <summary>
/// 
/// </summary>
public class ResultWithChallenge : IHttpActionResult
{
    private readonly IHttpActionResult next;
    private readonly string realm;

    /// <summary>
    /// Constructor
    /// </summary>
    /// <param name="next"></param>
    /// <param name="realm"></param>
    public ResultWithChallenge(IHttpActionResult next, string realm)
    {
        this.next = next;
        this.realm = realm;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var res = await next.ExecuteAsync(cancellationToken);
        if (res.StatusCode == HttpStatusCode.Unauthorized)
        {
            res.Headers.WwwAuthenticate.Add(
               new AuthenticationHeaderValue("Basic", this.realm));
        }
        return res;
    }
}

现在我的问题是,即使将 [AllowAnonymous] 属性应用于我的 Controller 操作,也会调用此类。

这给我带来了登录操作方面的麻烦,因为用户还没有 token 。

我该如何纠正这个问题?

最佳答案

AllowAnonymous 仅适用于授权过滤器。您在这里拥有的是身份验证过滤器。请改用 System.Web.Http 中的 OverrideAuthentication

更新

我在原来的回答中哪里说过您必须实现身份验证?我所说的只是,如果您不想调用 TokenAuthenticationAuthenticateAsync 方法,请应用 OverrideAuthentication,而不是 允许匿名AllowAnonymous 仅适用于授权过滤器,不适用于身份验证过滤器。因此,在您的 Login 操作中,您需要像这样应用 OverrideAuthentication

public class SomeController : ApiController
{
    [OverrideAuthentication]
    public HttpResponeMessage Login(Dto dto)
    { }
}

关于c# - 授权属性忽略 [AllowAnonymous],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25454866/

相关文章:

C# - 传递 DataTable 与 SqlDataReader

c# - dapper插入/更新需要内联sql吗?

c# - 处置 WPF 用户控件

typescript - DDD如何正确分离权限和角色

amazon-web-services - aws api-gateway 中的多个自定义授权者

c# - Fluent NHibernate 生成的审计

已发布的 WebAPI 中的 Azure AD 身份验证不起作用

c# - 从 asp.net core 高效地发送文件

c# - 列出多个组下的 API 方法

asp.net-mvc-4 - 初始化 MVC 4 中的简单成员资格