我有一个 ASP.Net WebAPI 2.1,我刚刚过渡到使用不记名令牌使用 Identity 2.0。这工作正常。现在我试图引入一些 MVC 代码来创建一组登录和用户管理页面。我的问题是,Request.IsAuthenticated
当我将 WebApi 设置HttpConfiguration
为SuppressDefaultHostAuthentication
.
下面是我的代码,我不知道如何让它适用于这两种情况:(
这是我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.IsAuthenticated
Identity 示例中使用的 ,但是在httpConfiguration.SuppressDefaultHostAuthentication
启用 时会失败。我了解此扩展的目标是在 Identity 中间件运行后删除当前身份 - 以便 WebAPI 身份验证过滤器可以随心所欲。但我希望在 MVC 方面,不会发生抑制。
剃刀视图示例:
@if (Request.IsAuthenticated) // false when using httpConfiguration.SuppressDefaultHostAuthentication
{
<div>User.Identity.Email</div>
}
谁能帮我?这甚至可能吗?
谢谢!