我有验证码:
var authTicket = new FormsAuthenticationTicket(/*blahblah....*/);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(cookie);
var name = HttpContext.User.Identity.Name; // line 4
Run Code Online (Sandbox Code Playgroud)
通过输入调试语句,我发现name第4行是空的.但是下次我在这个浏览器会话上打电话时,HttpContext.User.Identity.Name会正确设置.
那么这个值何时得到设定?
我已经打了好几个小时了,我很难过.我正在向MVC 5控制器发出ajax post请求,试图自动登录特定的预定义"超级"用户.在控制器方法中,我正在尝试以编程方式设置HttpContext.Current.User并进行身份验证,因此超级用户可以跳过手动登录的过程.对此的共识似乎就在这里,我实现了:
这似乎有效,直到我尝试使用自定义AuthorizeAttribute查看任何其他控制器方法.
控制器方法:
[HttpPost]
[AllowAnonymous]
public ActionResult Login(string username)
{
string password = ConfigurationManager.AppSettings["Pass"];
User user = service.Login(username, password);
var name = FormsAuthentication.FormsCookieName;
var cookie = Response.Cookies[name];
if (cookie != null)
{
var ticket = FormsAuthentication.Decrypt(cookie.Value);
if (ticket != null && !ticket.Expired)
{
string[] roles = (ticket.UserData as string ?? "").Split(',');
System.Web.HttpContext.Current.User = new GenericPrincipal(new FormsIdentity(ticket), roles);
}
}
//...processing result
return Json(result);
}
Run Code Online (Sandbox Code Playgroud)
上面的service.Login方法创建cookie:
FormsAuthentication.SetAuthCookie(cookieValue, false);
Run Code Online (Sandbox Code Playgroud)
虽然我正在设置具有Identity和IsAuthenticated的User,但下面的filterContext.HttpContext.User不是同一个用户.它本质上是空的,好像从未分配过,并且未经过身份验证.
public override void OnAuthorization(AuthorizationContext filterContext)
{
string[] userDetails = …Run Code Online (Sandbox Code Playgroud) 我在SO上找到了一个很好的答案,描述了如何设置自定义用户角色,我在我的项目中也做了同样的事情.所以在我的登录服务中,我有:
public ActionResult Login() {
// password authentication stuff omitted here
var roles = GetRoles(user.Type); // returns a string e.g. "admin,user"
var authTicket = new FormsAuthenticationTicket(
1,
userName,
DateTime.Now,
DateTime.Now.AddMinutes(20), // expiry
false,
roles,
"/");
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(cookie);
return new XmlResult(xmlDoc); // don't worry so much about this - returns XML as ActionResult
}
Run Code Online (Sandbox Code Playgroud)
在Global.asax.cs中,我(从另一个答案中逐字复制):
protected void Application_AuthenticateRequest(Object sender, EventArgs e) {
var authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null) {
var authTicket = …Run Code Online (Sandbox Code Playgroud)