【问题标题】:Web Api Asp.Net IdentityWeb Api Asp.Net 身份
【发布时间】:2013-09-28 13:22:00
【问题描述】:

我只是想在 DelegatingHandler 中使用 Asp.Identity 对用户进行身份验证。

就像上面这段代码:

public class TokenAuthentication : DelegatingHandler {
        private readonly AuthenticationIdentityManager _identityManager;

        public TokenAuthentication() {
            _identityManager = new AuthenticationIdentityManager(new IdentityStore(new NFeDb()));
        }

        private Microsoft.Owin.Security.IAuthenticationManager AuthenticationManager {
            get {
                return HttpContext.Current.GetOwinContext().Authentication;
            }
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
            if (request.Headers.Contains("X-TokenCliente")) {
                var tokenCliente = request.Headers.GetValues("X-TokenCliente").First();
                var s = _identityManager.Authentication.SignIn(this.AuthenticationManager, tokenCliente, false);
                if (s.Success) {
                    return await base.SendAsync(request, cancellationToken);
                }
            }

            return request.CreateResponse(HttpStatusCode.Unauthorized);
        }
    }

但是,在我的控制器上使用 Authorize 表示法:

[Authorize]
        public HttpResponseMessage Get() {
            return Request.CreateResponse(HttpStatusCode.OK);
        }

我收到 302 状态并重定向到登录页面。是否可以在 DelegatingHandler 中进行身份验证?

更新:我不知道是否需要使用 OwinMiddleware

【问题讨论】:

    标签: asp.net authentication asp.net-web-api owin asp.net-identity


    【解决方案1】:

    302 重定向可能来自 Cookie 中间件。

    如果要使用令牌认证,最好使用 OWIN 不记名令牌中间件。

    请查看:https://blogs.msdn.microsoft.com/webdev/2013/09/20/understanding-security-features-in-the-spa-template-for-vs2013-rc/

    该博客介绍了如何在 web api 中使用不记名令牌以及如何与 cookie 中间件一起工作。

    【讨论】:

      猜你喜欢
      • 2017-10-22
      • 2012-06-16
      • 2020-02-05
      • 2015-09-17
      • 2017-07-30
      • 2016-12-22
      • 1970-01-01
      • 2015-05-26
      • 1970-01-01
      相关资源
      最近更新 更多