【发布时间】:2014-07-24 16:06:29
【问题描述】:
我使用 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;
}
}
【问题讨论】:
标签: c# asp.net-mvc-4 cookies asp.net-web-api