實際上你很幸運 - 因爲你不必親自處理授權。你需要做的就是通知.NET基礎設施。最簡單的方法是添加你自己的IAuthenticationFilter
此示例假設必須同時「X-直呼其名」和「X-LAST-NAME」出現在請求作爲以HTTP報頭作爲身份驗證的用戶進行處理。
public class CustomHostAuthenticationFilter : IAuthenticationFilter
{
public bool AllowMultiple { get { return true; } }
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var request = context.Request;
if (request == null)
{
throw new ArgumentException("Request must not be null.", nameof(context));
}
if (request.Headers != null)
{
string firstName = null;
IEnumerable<string> values;
if (request.Headers.TryGetValues("X-FIRST-NAME", out values) && values.Any())
{
firstName = values.First();
}
string lastName = null;
if (request.Headers.TryGetValues("X-LAST-NAME", out values) && values.Any())
{
lastName = values.First();
}
if (!string.IsNullOrEmpty(firstName) && !string.IsNullOrEmpty(lastName))
{
var identity = new ClaimsIdentity("JWT");
identity.AddClaim(new Claim(ClaimTypes.Name, firstName + " " + lastName));
var principal = new ClaimsPrincipal(identity);
context.Principal = principal;
}
}
return Task.FromResult(0);
}
public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
{
return Task.FromResult(0);
}
}
然後將過濾器添加到管道中。
services.ConfigureMvc(options =>
{
options.Filters.Add(new CustomHostAuthenticationFilter());
}
這實際上看起來非常好,我明天會試試這個......看起來它可能工作得很好。謝謝。只有一件事,是不是現在叫做IAuthorizationFilter? –