简体   繁体   English

WebApi和MVC控制器的基于角色的自定义授权

[英]Role Based Custom Authorization for WebApi and MVC Controllers

I am using mvc controller for login and webapi controller for REST operations.I need to authorize web api controllers based on the user roles that set while login. 我将mvc控制器用于登录,将webapi控制器用于REST操作。我需要根据登录时设置的用户角色来授权Web api控制器。 After searching long time I came to know we can use forms authentication. 经过长时间的搜索,我知道我们可以使用表单身份验证。 The problem I think is the value from cookie can access from different application also? 我认为问题是cookie的值也可以从其他应用程序访问吗? How can we set Iprinciple values from mvc and access from webapi. 我们如何从mvc设置Iprinciple值以及如何从webapi进行访问。 Is it possible? 可能吗? If yes then, Can you provide any sample code? 如果是,那么您可以提供任何示例代码吗?

Current Approach: 当前方法:

Setting cookie from MVC: 从MVC设置cookie:

SessionWrapper.CustomPrincipalModel = customPrincipalModel;
            string userData = JsonConvert.SerializeObject(customPrincipalModel);

            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
              1, customPrincipalModel.LogonName, DateTime.Now, DateTime.Now.AddHours(8), false, userData);
            string encTicket = FormsAuthentication.Encrypt(authTicket);

            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);

            Response.Cookies.Add(cookie);

Read the cookie from webapi Filter Attribute. 从webapi过滤器属性读取cookie。

var header = filterContext.Request.Headers.GetCookies(FormsAuthentication.FormsCookieName);
            if (header != null && header.Count > 0)
            {
                //// Take out the cookie 
                var authCookie = header.First().Cookies.First(one => one.Name == FormsAuthentication.FormsCookieName);
                //// Create forms-authentication ticket based on the encrypted forms-authentication ticket. 
                var ticket = FormsAuthentication.Decrypt(authCookie.Value);
                if (ticket != null)
                {
                    //// Get the roles associated for the current user
                    var result = JsonConvert.DeserializeObject<CustomPrincipalModel>(ticket.UserData);
                    CustomPrincipal principal = new CustomPrincipal(new GenericIdentity(result.LogonName), result.AccessLevels);
                    principal.CustomPrincipalModel = result;
                    this.CurrentUser = principal;
                }
            }

            if (!string.IsNullOrEmpty(this.Roles))
            {
                if (this.CurrentUser.IsInRole(this.Roles))
                {
                    return true;
                }
            }

您可以对Web api使用基于令牌的身份验证,这是链接http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity /

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

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