我只是尝试在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
答案 0 :(得分:3)
302重定向可能来自Cookie中间件。
如果要使用令牌身份验证,最好使用OWIN承载令牌中间件。
该博客介绍了如何在web api中使用bearer token以及如何与cookie中间件并行工作。