美好的一天,
我正在尝试使用针对AD的FormsAuthentication对用户进行身份验证。 我通过ajax请求将数据发送到我的控制器,在那里执行身份验证。在用户进行身份验证并创建cookie之后,我尝试在我的Global.asax中的Application_PostAuthenticateRequest事件中访问该cookie,但cookie始终为null。我不确定我是否正确执行此操作以及任何指针这会很有帮助。
这是我的登录
$("#btnSubmit").click(function () {
try {
$(this).prop('disabled', true);
// debugger;
var username = $("#Username").val();
var pwd = $("#Password").val();
//is username empty
if (username==null) {
throw "User name cannot be Empty.";
}
if (pwd==null) {
throw "password cannot be Empty.";
}
param = {userName:username,password:pwd};
$.ajax({
type: "POST",
url: "/Login/Authenticate",
data: JSON.stringify(param),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (msg, status, xhr) {
// Replace the div's content with the page method's return.
// $("#Data").text(msg.d);
// debugger;
if (msg.Success) {
var url = '@Url.Action("BillRegisterMain", "Home")';
var url2 = '@Url.Content("~/Home/BillRegisterMain")'
if (xhr.readyState == 4 && xhr.status == 200) {
window.location.href = url2;
}
return false;
}
else {
// ////debugger;
showErrorMSg(msg.Message);
return false;
//alert("Error Authenticating.Please try again");
}
},
error: function () {
// ////debugger;
throw(msg.payload);
}
});
} catch (e) {
showErrorMSg(e);
}
$(this).prop('disabled', false);
return false;
});
这是我的控制器:
public JsonResult Authenticate()
{
try
{
var CustUser = new TTParlBillBook.Auth.AdAuthenticationService.CustomUser();
var resolveRequest = System.Web.HttpContext.Current.Request;
var response = System.Web.HttpContext.Current.Response;
resolveRequest.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
string jsonString = new System.IO.StreamReader(resolveRequest.InputStream).ReadToEnd();
JavaScriptSerializer serializer = new JavaScriptSerializer();
UsrObj _model = new UsrObj();
_model = serializer.Deserialize<UsrObj>(jsonString);
string username = _model.username;
string password = _model.password;
UserViewModel UserViewModel = new UserViewModel();
string[] roles;
string name = string.Empty;
string pic = string.Empty;
bool r = UserViewModel.Athenticate(username, password, out roles, out name, "", out pic, out CustUser);
if (r)
{
UserViewModel.Username = username;
UserViewModel.picture = pic;
UserViewModel.roles = roles;
var userData = Newtonsoft.Json.JsonConvert.SerializeObject(UserViewModel);
//change this
//CustUser.userName = username;
//CustUser.userPhoto = pic;
//Session["currentUser"] = CustUser;
//create forms authentication ticket
//System.Web.Security.FormsAuthentication.SetAuthCookie(username, true);
DateTime currentTdate = DateTime.Now;
var ticket = new System.Web.Security.FormsAuthenticationTicket(1, UserViewModel.Username, currentTdate, currentTdate.AddMinutes(15), true, userData);
var encTicket = System.Web.Security.FormsAuthentication.Encrypt(ticket);
var faCookie = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, encTicket);
faCookie.Expires = DateTime.Now.AddDays(1);
faCookie.Secure = true;
response.Cookies.Add(faCookie);
//HttpCookie authCookie = System.Web.Security.FormsAuthentication.GetAuthCookie(username, true);
//authCookie.Value = encTicket;
//HttpCookie authCookie = System.Web.Security.FormsAuthentication.SetAuthCookie()
//authCookie.Expires = DateTime.Now.AddDays(1);
//Response.Cookies.Add(authCookie);
}
return new JsonResult
{
Data = new { Success = r,Message="Success" },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.DenyGet
};
}
catch (Exception ex)
{
return new JsonResult
{
Data = new { Success = false,Message=ex.Message },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.DenyGet
};
}
}
这是我在global.asax
中的Application_PostAuthenticateRequest protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
if (FormsAuthentication.CookiesSupported==true)
{
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
try
{
HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
if (!string.IsNullOrEmpty(authCookie.Value))
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}
Application_PostAuthenticateRequest中的