使用OnValidateIdentity对cookie数据执行其他验证

Evi*_*lDr 5 c# asp.net owin katana

Brock Allen的博客中,他表示

CookieAuthenticationOptions类具有Provider属性...并且它具有您可以订阅的委托的属性.这允许您在进入应用程序时验证cookie(OnValidateIdentity).在此回调中,您可以拒绝或替换身份.

我是OWIN和C#的新手,所以我正在努力调整OnValidateIdentity我在网上发现的许多例子以满足我的需求.在每个"私人"网页上接受cookie有效后,我想检查以下内容:

  1. 该cookie包含至少一个声明
  2. CustomerId声明值大于零

我可以用普通方法实现这两个检查,但我无法弄清楚如何挂钩登录OnValidateIdentity.这是我到目前为止所拥有的:

我写了一些代码,但无法弄清楚需要从使用的方法返回什么.

public void Configuration(IAppBuilder app)
{
    dynamic cookieExpirationPeriod = TimeSpan.FromMinutes(60);

    CookieAuthenticationProvider prov = new CookieAuthenticationProvider();
    prov.OnValidateIdentity = ctx =>
    {
        MyClaimsIdentityObject si = MyApp.Identity.Current();
        if (si == null || si.UserId == 0 || si.CustomerId == 0) {
            ctx.RejectIdentity();
            // what needs to happen here for a return value?
        }
    };


    CookieAuthenticationOptions coa = new CookieAuthenticationOptions {
        AuthenticationMode = AuthenticationMode.Active,
        CookieName = "MyApp",
        ExpireTimeSpan = cookieExpirationPeriod,
        SlidingExpiration = true,
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/login.aspx"),
        CookieHttpOnly = true,
        Provider = prov
    };

    if (HttpContext.Current.Request.IsLocal) {
        coa.CookieSecure = CookieSecureOption.Never;
    } else {
        coa.CookieSecure = CookieSecureOption.Always;
    }

    app.UseCookieAuthentication(coa);

}
Run Code Online (Sandbox Code Playgroud)

小智 3

我相信这只是:

return Task.FromResult<int>(0);
Run Code Online (Sandbox Code Playgroud)