简体   繁体   English

WebApi身份验证不适用于MVC

[英]WebApi Authentication is not applied to MVC

I have ASP.NET MVC app with custom Authentication server. 我有带有自定义身份验证服务器的ASP.NET MVC应用程序。 When user wants to log in, app popups window, and when he is done, token returns, and app then logs in user via WebApi, 当用户想要登录时,应用程序弹出窗口,完成后,令牌返回,然后应用程序通过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);

and on every request - WebApi knows who is user, mean User.Identity is defined; 在每个请求上-WebApi知道谁是用户,即定义了User.Identity But in MVC views, it's always null and none of this execute 但是在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>

How to authenticate user from web api to mvc? 如何从Web API验证用户到MVC? App based on angularjs on front, so all authorization stuff is done on frontend, via webapi requests. 应用基于前端的angularjs,因此所有授权工作都是通过webapi请求在前端完成的。 So mvc simply doesnt know anything. 因此,mvc根本什么都不知道。

For the sake of fullness, this is TaiAuthPrincipal, there is nothing special indeed 为了完整起见,这是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 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 Startup.cs

public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
            app.UseOAuthBearerAuthentication(new Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationOptions());
        }
    }

If you are making Web Api in same project of MVC appliation then your way to authenticate your web request is totally wrong. 如果要在MVC应用程序的同一项目中制作Web Api,则验证Web请求的方式是完全错误的。 What happens is when you request your view by calling an action then your mvc project expects an authenticated request so what you need to do is save your accesstoken in a cookie on clientside and send it to server with every request and identify user from that token and set the IPrincipal. 发生的事情是,当您通过调用一个操作来请求视图时,您的mvc项目需要一个经过身份验证的请求,因此您需要做的就是将您的访问令牌保存在客户端的Cookie中,并随每个请求将其发送到服务器,并从该令牌中识别用户,设置IPrincipal。 Go through this answer it will help you 通过这个答案,它将帮助您

ASP.NET MVC - Set custom IIdentity or IPrincipal ASP.NET MVC-设置自定义IIdentity或IPrincipal

Your code will look like this 您的代码将如下所示

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