在我的asp.net MVC 4.6应用程序中,登录网站后,我需要调用RedirectToAction
来调用另一个控制器,但是当前的登录数据在到达另一个控制器之前就会丢失。但是,如果在启用匿名身份验证的情况下运行数据,则数据不会丢失。但我无法启用匿名身份验证。
这是我的AccountController类中的登录方法:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult LogOn(string userName, string password, string returnUrl)
{
if (ValidateLogOn(userName, password) == false)
{
return View();
}
FormsAuthenticationService.SignIn(userName, false);
IVtrsUser currentUser = MembershipService.Get(userName);
if (currentUser.IsPasswordExpired)
{
return RedirectToAction("ChangePassword");
}
else if (string.IsNullOrEmpty(returnUrl) == false)
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Calendar");
}
}
从调试中,我可以看到两个服务已正确设置当前用户:
FormsAuthenticationService.SignIn(userName, false);
IVtrsUser currentUser = MembershipService.Get(userName);
但是代码输出到CalendarController之后如下:
[Authorize(Roles = "Admin")]
public class CalendarController : Controller
{ ...
用户登录的数据包括Role =" Admin"丢失,导致CalendarController
中的以下代码错误,并且不执行Index()
的{{1}}方法,任何人都可以帮助我在匿名身份验证中丢失此用户登录数据的原因禁用模式?启用匿名身份验证模式时,用户数据是否仍然存在?
添加更多,有相关代码:
CalendarController
这是public IFormsAuthenticationService FormsAuthenticationService { get; private set; }
:
IFormsAuthenticationService
答案 0 :(得分:0)
请告诉我保持用户日志的标准或最佳方式 在数据中,然后我可以修改我的服务或重写代码以保持 用户登录数据。
在ASP.NET MVC中,您希望使用 ASP.NET OWIN Cookie中间件 而不是FormAuthentication。
private readonly HttpContextBase _context;
private const string AuthenticationType = "ApplicationCookie";
public OwinAuthenticationService(HttpContextBase context)
{
_context = context;
}
public void SignIn(User user)
{
IList<Claim> claims = new List<Claim>
{
new Claim(ClaimTypes.Sid, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.UserName),
new Claim(ClaimTypes.GivenName, user.FirstName),
new Claim(ClaimTypes.Surname, user.LastName),
};
ClaimsIdentity identity = new ClaimsIdentity(claims, AuthenticationType);
IOwinContext context = _context.Request.GetOwinContext();
IAuthenticationManager authenticationManager = context.Authentication;
authenticationManager.SignIn(identity);
}
public void SignOut()
{
IOwinContext context = _context.Request.GetOwinContext();
IAuthenticationManager authenticationManager = context.Authentication;
authenticationManager.SignOut(AuthenticationType);
}
您还需要为所有发生的事件配置启动。
[assembly: OwinStartup(typeof(YourApplication.Startup))]
namespace YourApplication
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "ApplicationCookie",
LoginPath = new PathString("/Account/Login")
});
}
}
}
然后,您可以在Controller和Action方法中开始使用[Authorize]
属性。
[Authorize]
public class UsersController : Controller
{
// ...
}
以下是使用AD进行身份验证的my sample application at GitHub。但核心部分是OwinAuthenticationService.cs和Startup.cs。