3

我有一个 ASP.Net WebAPI 2.1,我刚刚过渡到使用不记名令牌使用 Identity 2.0。这工作正常。现在我试图引入一些 MVC 代码来创建一组登录和用户管理页面。我的问题是,Request.IsAuthenticated当我将 WebApi 设置HttpConfigurationSuppressDefaultHostAuthentication.

下面是我的代码,我不知道如何让它适用于这两种情况:(

这是我Startup.cs设置 Identity OWIN 模块和 WebAPI 的方法:

public class Startup
{
    public void Configure(IAppBuilder app)
    {
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

        PublicClientId = "self";
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/token"),
            Provider = new ApplicationOAuthProvider(PublicClientId),
            AuthorizeEndpointPath = new PathString("/api/account/externalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14)
        };
        app.UseOAuthBearerTokens(OAuthOptions);

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager, DefaultAuthenticationTypes.ApplicationCookie))
            }
        });

        var httpConfiguration = new HttpConfiguration();
        // Disable this line to allow Request.IsAuthenticated to work
        // But by doing this, it allows the 'redirect' to kick in on unauthenticated API requests, which returns a HTML page for a webapi call, rather than the JSON 'unauthenticated' response
        httpConfiguration.SuppressDefaultHostAuthentication();
        httpConfiguration.Filters.Add(new HostAuthenticationFilter(DefaultAuthenticationTypes.ApplicationCookie));
        httpConfiguration.MapHttpAttributeRoutes();
        app.UseWebApi(httpConfiguration);
    }
}

这是我的Global.asax.cs,它设置了 MVC 方面(AFAIK OWIN 不支持任何形式的app.UseMvc()):

public class WebApiApplication : HttpApplication
{
    protected void Application_Start()
    {
        // pretty much the defaults here for everything, just renamed
        AreaRegistration.RegisterAllAreas();
        MvcConfig.ConfigureFilters(GlobalFilters.Filters);
        MvcConfig.ConfigureRoutes(RouteTable.Routes);
        MvcConfig.ConfigureBundles(BundleTable.Bundles);
    }
}

现在在我的 Razor 视图中,我想使用Request.IsAuthenticatedIdentity 示例中使用的 ,但是在httpConfiguration.SuppressDefaultHostAuthentication启用 时会失败。我了解此扩展的目标是在 Identity 中间件运行后删除当前身份 - 以便 WebAPI 身份验证过滤器可以随心所欲。但我希望在 MVC 方面,不会发生抑制。

剃刀视图示例:

@if (Request.IsAuthenticated) // false when using httpConfiguration.SuppressDefaultHostAuthentication
{
  <div>User.Identity.Email</div>
}

谁能帮我?这甚至可能吗?

谢谢!

4

1 回答 1

2

看起来这一切都与应用程序构建器的顺序有关。如果我将身份承载配置放在 WebAPI 之前,那么我的 WebAPI 请求仍然使用身份 OWIN 模块。通过将 Cookie 配置放在 WebAPI 配置之后,Cookie 身份解析发生在 WebAPI 身份删除之后、MVC 执行之前。

不确定这是否是“正确”的做法,但它似乎解决了我打开的所有测试用例。

public class Startup
{
    public void Configure(IAppBuilder app)
    {
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

        PublicClientId = "self";
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/token"),
            Provider = new ApplicationOAuthProvider(PublicClientId),
            AuthorizeEndpointPath = new PathString("/api/account/externalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14)
        };
        app.UseOAuthBearerTokens(OAuthOptions);

        var httpConfiguration = new HttpConfiguration();
        httpConfiguration.SuppressDefaultHostAuthentication();
        httpConfiguration.Filters.Add(new HostAuthenticationFilter(DefaultAuthenticationTypes.ApplicationCookie));
        httpConfiguration.MapHttpAttributeRoutes();
        app.UseWebApi(httpConfiguration);

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager, DefaultAuthenticationTypes.ApplicationCookie))
            }
        });
    }
}

编辑 上述工作,但似乎更好地利用app.MapWhen()功能来做到这一点。

public class Startup
{
    public void Configure(IAppBuilder app)
    {
        // setup auth for all requests
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

        PublicClientId = "self";
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/token"),
            Provider = new ApplicationOAuthProvider(PublicClientId),
            AuthorizeEndpointPath = new PathString("/api/account/externalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14)
        };
        app.UseOAuthBearerTokens(OAuthOptions);

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager, DefaultAuthenticationTypes.ApplicationCookie))
            }
        });

        // setup webapi for only /api requests
        app.MapWhen(
            context => context.Request.Uri.PathAndQuery.StartsWith("/api"),
            newApp => {
                var httpConfiguration = new HttpConfiguration();
                httpConfiguration.SuppressDefaultHostAuthentication();
                httpConfiguration.Filters.Add(new HostAuthenticationFilter(DefaultAuthenticationTypes.ApplicationCookie));
                httpConfiguration.MapHttpAttributeRoutes();
                app.UseWebApi(httpConfiguration);
            }
    }
}    
于 2014-05-15T15:10:26.230 回答