我在一个项目中实现了Forms身份验证。在表单身份验证cookie中,我存储了用户的登录ID。即。
FormsAuthentication.SetAuthCookie(LoginId, false);
我现在需要在每个请求上读取cookie值以获取有关用户的更多信息,并将此信息放在HttpContext.Items属性中。该项目是一个MVC项目,既有常规MVC控制器,也有Web API控制器。目前我已经创建了两个动作过滤器 - 一个用于MVC控制器,另一个用于Web API控制器,我在这里读取了这个值。所以喜欢
public class MyMvcFilter : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie != null)
{
var ticket = FormsAuthentication.Decrypt(cookie.Value);
filterContext.HttpContext.Items.Add("LoginId",ticket.Name);
}
base.OnAuthorization(filterContext);
}
}
和
public class MyFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
base.OnActionExecuting(actionContext);
var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie == null)
{
return;
}
var ticket = FormsAuthentication.Decrypt(cookie.Value);
if (ticket == null)
{
return;
}
actionContext.Request.Properties.Add("LoginId", userId);
}
}
但是我想的越多,它对我来说就越难看。什么是正确的位置,我可以解密身份验证cookie并保持相同的MVC控制器以及Web API控制器?
答案 0 :(得分:1)
MVC和WebAPI(直到.NET Core)不共享相同的管道,因此您需要使用两个不同的过滤器。
如果您愿意,可以使用实用工具方法或其他方式共享代码。只是为了避免让两个代码做同样的事情
答案 1 :(得分:1)
我会:
阅读
上的cookieprotected void Application_PostAuthenticateRequest(object sender, EventArgs e)
{
}
在上面的方法中....将cookie转换为ClaimsPrincipal。 如下所示:
protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
{
IList<Claim> claimCollection = new List<Claim>
{
new Claim("http://www.mycompany.com/claims/LoginId, "123456" /* use info from cookie instead of 123456*/)
};
ClaimsIdentity claimsIdentity = new ClaimsIdentity(claimCollection, "My e-commerce website");
Console.WriteLine(claimsIdentity.IsAuthenticated);
ClaimsPrincipal customPrinc = new ClaimsPrincipal(claimsIdentity);
if (null != customPrinc)
{
Thread.CurrentPrincipal = customPrinc; /* Set here. But when you need to "get" it, use "System.Security.Claims.ClaimsPrincipal.Current" */
/* ASP.NET Authorization depends on value of HttpContext.Current.User.
* Consider putting ClaimsPrincipal into both HttpContext.Current.User and Thread.CurrentPrincipal */
HttpContext.Current.User = customPrinc;
/* Note the second setter is necessary so you don't lose it later on, learned the hard way by experience */
}
}
根据需要检索声明主体..
/* MVC */
public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
{
/* the below should be what you set in the Application_PostAuthenticateRequest method */
IPrincipal currentClaimsPrinc = ClaimsPrincipal.Current;
}
/* WebAPI */
public override void OnAuthorization(HttpActionContext actionContext)
{
IPrincipal claimsPrincCurrent = ClaimsPrincipal.Current;
}
你也可以这样做:
adding claims to forms authentication in asp.net
或者这个:
或者这个: