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

时间:2014-06-04 06:02:20

标签: c# asp.net-mvc-4 cookies asp.net-web-api

我使用mvc控制器进行登录,使用webapi控制器进行REST操作。我需要根据登录时设置的用户角色授权web api控制器。经过长时间的搜索,我才知道我们可以使用表单身份验证。我认为问题是来自cookie的价值还可以从不同的应用程序访问吗?我们如何从mvc设置Iprinciple值并从webapi设置访问权限。可能吗?如果是,那么,您能提供任何示例代码吗?

当前方法:

从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);

从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;
                }
            }

1 个答案:

答案 0 :(得分:0)

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