gpt4 book ai didi

asp.net-mvc - 将 Identity 与 Owin 用于 MVC 和 WebAPI 时的 Request.IsAuthenticated

转载 作者:行者123 更新时间:2023-12-02 01:13:22 24 4
gpt4 key购买 nike

我有一个 ASP.Net WebAPI 2.1,我刚刚将其转换为使用不记名 token 的 Identity 2.0。这很好用。现在,我尝试引入一些 MVC 代码来创建一组登录和用户管理页面。我的问题是,当我将 WebApi HttpConfiguration 设置为 SuppressDefaultHostAuthentication 时,我似乎无法从 Razor View 中获取 Request.IsAuthenticated 工作。

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

这是我的 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 View 中,我想使用 Identity 示例中使用的 Request.IsAuthenticated,但在启用 httpConfiguration.SuppressDefaultHostAuthentication 时会失败。我了解此扩展的目标是在身份中间件运行后删除当前身份 - 以便 WebAPI 身份验证过滤器可以随心所欲地执行。但我希望在 MVC 方面,不会发生抑制。

Razor View 示例:

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

有人可以帮助我吗?这可能吗?

谢谢!

最佳答案

看起来这全都与应用程序构建器的顺序有关。如果我将身份承载配置放在 WebAPI 之前,那么我的 WebAPI 请求仍然使用 Identity 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);
}
}
}

关于asp.net-mvc - 将 Identity 与 Owin 用于 MVC 和 WebAPI 时的 Request.IsAuthenticated,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23680348/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com