繁体   English   中英

WebApi身份验证不适用于MVC

[英]WebApi Authentication is not applied to MVC

我有带有自定义身份验证服务器的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());
        }
    }

如果要在MVC应用程序的同一项目中制作Web Api,则验证Web请求的方式是完全错误的。 发生的事情是,当您通过调用一个操作来请求视图时,您的mvc项目需要一个经过身份验证的请求,因此您需要做的就是将您的访问令牌保存在客户端的Cookie中,并随每个请求将其发送到服务器,并从该令牌中识别用户,设置IPrincipal。 通过这个答案,它将帮助您

ASP.NET MVC-设置自定义IIdentity或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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM