WebApi身份验证不适用于MVC

时间:2015-02-09 05:50:37

标签: c# asp.net asp.net-web-api asp.net-mvc-5 asp.net-identity

我有自定义身份验证服务器的ASP.NET MVC应用程序。当用户想要登录时,应用弹出窗口,当他完成后,令牌返回,然后应用程序通过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());
        }
    }

1 个答案:

答案 0 :(得分:1)

如果您在同一MVC应用项目中制作Web Api,那么验证Web请求的方式是完全错误的。当你通过调用一个动作来请求你的视图然后你的mvc项目需要一个经过身份验证的请求时,你需要做的就是将你的accessstoken保存在客户端的cookie中,并将每个请求发送到服务器,并从该令牌中识别用户,设置IPrincipal。通过这个答案它会帮助你

ASP.NET MVC - Set custom IIdentity or IPrincipal

您的代码将如下所示

protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
    HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];

    if (authCookie != null)
    {
        FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

        JavaScriptSerializer serializer = new JavaScriptSerializer();

        CustomPrincipalSerializeModel serializeModel = serializer.Deserialize<CustomPrincipalSerializeModel>(authTicket.UserData);

        CustomPrincipal newUser = new CustomPrincipal(authTicket.Name);
        newUser.Id = serializeModel.Id;
        newUser.FirstName = serializeModel.FirstName;
        newUser.LastName = serializeModel.LastName;

        HttpContext.Current.User = newUser;
    }
}