您可以使用消息处理程序来设置 currentprincipal,如下所示:
public class TokenAuthMessageHandler : DelegatingHandler
{
public TokenAssembler<Token> TokenAssembler { get; set; }
const string SSOTOKEN = "token";
protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
Token token;
IEnumerable<string> headers;
if (request.Headers.TryGetValues(SSOTOKEN, out headers))
{
token = TokenAssembler.Decrypt(headers.First());
}
else
{
var qs = HttpUtility.ParseQueryString(request.RequestUri.Query);
var tokenstr = qs[SSOTOKEN];
if (!string.IsNullOrEmpty(tokenstr))
{
token = TokenAssembler.Decrypt(tokenstr);
}
}
if (token != null)
{
var principal = new GenericPrincipal(new GenericIdentity(Username), null);
Thread.CurrentPrincipal = principal;
HttpContext.Current.User = principal;
}
return base.SendAsync(request, cancellationToken)
.ContinueWith(task =>
{
var response = task.Result;
if (response.StatusCode == HttpStatusCode.Unauthorized
&& !response.Headers.Contains(BasicAuthResponseHeader))
{
// redirect to some log in page?
}
return response;
});
}
您可以像这样在 webapiconfig 中注册消息处理程序:
config.MessageHandlers.Add(new TokenAuthMessageHandler() { TokenAssembler = MyTokenAssembler });