目前已經是一個類,它可以提供豐富索賠ClaimsAuthenticationManager,您可以延長因此處理您的特定領域的要求,例如...
public class MyClaimsAuthenticationManager : ClaimsAuthenticationManager
{
public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
{
if (!incomingPrincipal.Identity.IsAuthenticated)
{
return base.Authenticate(resourceName, incomingPrincipal);
}
return AddApplicationClaims(incomingPrincipal);
}
private ClaimsPrincipal AddApplicationClaims(ClaimsPrincipal principal)
{
// TODO: Add custom claims here based on current principal.
return principal;
}
}
下一個任務是提供合適的中間件調用此方法。對於我的項目,我寫了下面的類...
/// <summary>
/// Middleware component to apply claims transformation to current context
/// </summary>
public class ClaimsTransformationMiddleware
{
private readonly Func<IDictionary<string, object>, Task> next;
private readonly IServiceProvider serviceProvider;
public ClaimsTransformationMiddleware(Func<IDictionary<string, object>, Task> next, IServiceProvider serviceProvider)
{
this.next = next;
this.serviceProvider = serviceProvider;
}
public async Task Invoke(IDictionary<string, object> env)
{
// Use Katana's OWIN abstractions
var context = new OwinContext(env);
if (context.Authentication != null && context.Authentication.User != null)
{
var manager = serviceProvider.GetService<ClaimsAuthenticationManager>();
context.Authentication.User = manager.Authenticate(context.Request.Uri.AbsoluteUri, context.Authentication.User);
}
await next(env);
}
}
然後接線延伸......
public static class AppBuilderExtensions
{
/// <summary>
/// Add claims transformation using <see cref="ClaimsTransformationMiddleware" /> any depdendency resolution is done via IoC
/// </summary>
/// <param name="app"></param>
/// <param name="serviceProvider"></param>
/// <returns></returns>
public static IAppBuilder UseClaimsTransformation(this IAppBuilder app, IServiceProvider serviceProvider)
{
app.Use<ClaimsTransformationMiddleware>(serviceProvider);
return app;
}
}
我知道這是服務定位器的反模式,但使用的IServiceProvider是集裝箱中性並且似乎是將依賴關係納入Owin中間件的可接受方式。
最後,你需要在你的啓動來這樣使用,下面的例子假定團結和註冊/暴露出IServiceLocator屬性...
// Owin config
app.UseClaimsTransformation(UnityConfig.ServiceLocator);
在JabbR的Owin大堂@Pinpoint聊天后,似乎到認證線的唯一途徑就是通過IAppBuilder的UseOAuthBearerAuthentication指定自定義提供商。然後可以將聲明添加到身份上下文中(context.Ticket.Identity.AddClaim(...))。這是根據請求完成的。 – 2015-02-18 13:40:31