【发布时间】:2015-04-08 19:49:44
【问题描述】:
我有带有自定义身份验证服务器的 ASP.NET MVC 应用程序。当用户想登录时,app弹窗,完成后,token返回,app再通过WebApi登录用户,
var cl = from d in (this.User.Identity as ClaimsIdentity).Claims
select new Claim(d.Type, d.Value);
var identity = new ClaimsIdentity(cl, "ApplicationCookie");
AuthenticationManager.SignIn(identity);
var name = cl.FirstOrDefault(x => x.Type.ToLower() == "login").Value;
Thread.CurrentPrincipal = new TaiAuthPrincipal(identity);
System.Web.Security.FormsAuthentication.SetAuthCookie(name, true);
并且在每个请求 - WebApi 知道谁是用户,意味着 User.Identity 被定义;
但在 MVC 视图中,它始终为 null,并且这些都不执行
<div class="headerPane">
@{
if (User.Identity.IsAuthenticated)
{
@Html.Partial("HeaderPartialView")
}
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
@Html.Partial("HeaderPartialView")
}
if (System.Threading.Thread.CurrentPrincipal.Identity.IsAuthenticated)
{
@Html.Partial("HeaderPartialView")
}
}
</div>
如何验证用户从 web api 到 mvc? 前端基于 angularjs 的应用程序,因此所有授权工作都通过 webapi 请求在前端完成。所以 mvc 根本什么都不知道。
为了完整起见,这里是TaiAuthPrincipal,确实没什么特别的
public class TaiAuthPrincipal : IPrincipal
{
private IIdentity identity;
public IIdentity Identity
{
get { return identity; }
}
public bool IsInRole(string role)
{
var _role = (this.Identity as ClaimsIdentity).Claims.FirstOrDefault(x => x.Type.ToLower().Contains("GroupName".ToLower()));
return _role == null ? false : true;
}
public TaiAuthPrincipal(IIdentity _identity)
{
this.identity = _identity;
}
public TaiAuthPrincipal(ClaimsIdentity _identity)
{
this.identity = _identity as IIdentity;
}
}
Global.asax
void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
if (HttpContext.Current.Request.Url.AbsolutePath.StartsWith("/api/"))
{
System.Web.HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
}
}
Startup.cs
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
app.UseOAuthBearerAuthentication(new Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationOptions());
}
}
【问题讨论】:
-
web api 是否在 mvc 的同一个项目中?
-
是的,它们在 1 个应用程序中
标签: c# asp.net asp.net-web-api asp.net-mvc-5 asp.net-identity