我有一个ASP.Net WebAPI 2.1,我刚刚过渡到使用身份2.0使用持票人令牌。这工作正常。现在我试图拉入一些MVC代码来创建一组登录和用户管理页面。我的问题是,当我将WebApi HttpConfiguration
设置为SuppressDefaultHostAuthentication
时,我似乎无法从我的剃刀视图中获得Request.IsAuthenticated
。Request.IsAuthenticated使用身份与Owin的MVC和WebAPI
下面是我的代码,我出出主意,我怎么能得到这个对于这两种情况:(
这里是我的Startup.cs
其中规定了身份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侧(据我所知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.IsAuthenticated
,如在身份示例中使用的,但在启用httpConfiguration.SuppressDefaultHostAuthentication
时失败。我知道这个扩展的目标是在Identity中间件运行后移除当前的身份 - 这样WebAPI身份验证过滤器可以随心所欲地进行操作。但我希望在MVC方面,这种压制不会发生。
例Razor视图:
@if (Request.IsAuthenticated) // false when using httpConfiguration.SuppressDefaultHostAuthentication
{
<div>User.Identity.Email</div>
}
谁能帮助我?这甚至有可能吗?
谢谢!
我很想知道在'MapWhen'动作中重新注册Web API是不是一个好主意。我无法找到如何使用'MapWhen'处理请求的可靠答案。 – CalMlynarczyk