【问题标题】:How to exclude a controller from being authenticated如何将控制器排除在身份验证之外
【发布时间】:2014-03-10 06:15:46
【问题描述】:

我已经在我的 asp.net web api 项目中覆盖了 IautheticationFIlter。这是我的课:

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:
        var token = request.Headers.GetValues("Token").ElementAt(0);

        ...

        }
        return Task.FromResult(0);
    }


    public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
    {
        context.Result = new ResultWithChallenge(context.Result, realm);
        return Task.FromResult(0);
    }
}

现在我需要将我的登录控制器排除在身份验证之外:

目前,当我运行我的项目时,如果我放置 [Authorize]、[AllowAnonymous] 或根本没有过滤器,每个请求都会触发此代码。

这里是我添加过滤器的地方:

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

【问题讨论】:

    标签: asp.net asp.net-web-api authorization action-filter


    【解决方案1】:

    我认为,您混淆了身份验证授权。可能您希望将您的登录控制器排除在授权之外。
    [Authorize] 和 [AllowAnonymous] 属性用于授权上下文,与身份验证无关。这就是您的 IAuthenticationFilter 每次都被调用的原因。
    这篇文章也很有用http://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api

    【讨论】:

    • 我将授权和身份验证合二为一。我正在使用 JWT 令牌,我的 userId 在令牌中加密。因此,每个请求(一旦登录)都会在标头中有一个令牌。但他们需要先登录。我没有基于角色的身份验证,所以我希望你能看到我的问题?
    • 我相信这里可能有些混乱。没有基于角色的身份验证。角色用于授权。我建议将关注点(授权和身份验证)分开。这种分离是在 MVC 5 中实现 IAuthenticationFilter 的原因。无论如何,这篇文章可能会有所帮助 jameschambers.com/2013/11/…>。
    • 这篇关于授权的文章也可能很有趣blogs.msdn.com/b/rickandy/archive/2011/05/02/…>。您可能可以使用类似的方法进行身份验证。
    猜你喜欢
    • 1970-01-01
    • 2013-01-02
    • 1970-01-01
    • 2019-12-21
    • 2021-12-29
    • 2012-12-23
    • 2017-02-17
    • 1970-01-01
    • 2015-04-25
    相关资源
    最近更新 更多