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
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.