Web Api Asp.Net Identity

时间:2013-09-23 15:08:50

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

我只是尝试在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]
        public HttpResponseMessage Get() {
            return Request.CreateResponse(HttpStatusCode.OK);
        }

我恢复302状态,重定向到登录页面。可以在DelegatingHandler中进行身份验证吗?

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

1 个答案:

答案 0 :(得分:3)

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

如果要使用令牌身份验证,最好使用OWIN承载令牌中间件。

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

该博客介绍了如何在web api中使用bearer token以及如何与cookie中间件并行工作。