我有一个现有的MVC 5项目,他们是WebAPI2控制器 . 我为我的前端使用表单身份验证,现在为我的WebAPI使用Bearer令牌 .
问题是如果我在登录MVC应用程序后使用WebAPI身份验证,即使我没有指定有效的承载令牌,webapi也认为我已经过身份验证 .
如果我打电话
config.SuppressDefaultHostAuthentication()
然后,一旦使用持票人令牌通过WebAPI登录,然后登录到MVC应用程序,即使将其设置为我的自定义原则(Application_AuthenticateRequest),也会将委托人设置为ClaimsPrinciple . 因此,当我稍后将HttpContext.User转换为我的自定义Prinicpal时,它不起作用,并且MVC应用程序认为我的用户已注销 .
那么,如何在不相互覆盖的情况下将两种身份验证方法分开?
MVC认证:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (Request.IsAuthenticated)
{
// check if we have the user in the cache
var userPrincipal = PrincipalManager.GetPrincipal();
if (userPrincipal == null || !userPrincipal.Identity.IsAuthenticated)
{
userPrincipal = new GenericPrincipal(new RoomixerIdentity(), null);
PrincipalManager.StorePrincipal(userPrincipal);
}
HttpContext.Current.User = userPrincipal;
}
}
1 回答
我建议您检查VS 2013 Web API模板(Web API和MVC核心依赖项),但检查个别帐户为this image,我相信您缺少在WebApiConfig.cs类中添加这两行:
您需要禁止默认身份验证(Forms Auth),然后仅为Web API添加承载身份验证 .