2

I'm just trying to authentication a user with Asp.Identity in DelegatingHandler.

Like this code above:

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);
        }
    }

But, at my controller with the Authorize notation:

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

I recive 302 status e redirected to Login page. Is possible to authenticate in DelegatingHandler?

UPDATE: I don't know if I need to use OwinMiddleware

1 Answer 1

3

The 302 redirection is probably from Cookie middleware.

If you are going to use token authentication, you'd better use the OWIN bearer token middleware.

Please check out: https://blogs.msdn.microsoft.com/webdev/2013/09/20/understanding-security-features-in-the-spa-template-for-vs2013-rc/

The blog covers how to use bearer token in web api and how to work side by side with cookie middleware.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.