I've this:
// connect to MemberHub
function connect() {
// get unique id cookie
var uid = $.cookie('UniqueID', { path: '/' });
member.server.connect(uid).done(function (result) {
if (result.msg == 'success') {
// notify user
$('#log').append($('<li>', { html: 'Connected to MemberHUB' }));
}
});
}
Each time I try to read cookie it creates same cookie instead of read it.
Update: Here is how I assign cookies:
public static HttpCookie Create(string name, string value,
DateTime expires, HttpContextBase httpContext)
{
var cookie = new HttpCookie(name)
{
Value = value,
Expires = expires,
Secure = true,
HttpOnly = false,
Path = "/"
};
httpContext.Response.Cookies.Add(cookie);
return cookie;
}
Any advice will be helpful.
$.cookie is only read access if no other parameters (but the cookie's name) are supplied to the method [See the source]
If you're interested in reading it, just supply $.cookie('UniqueID') and remove the second parameter.
As an FYI, path (and other cookie properties) are only relevant when assigning a value, not retrieving. In other words, you don't need to supply path:'/' to get cookies that are applied to that path, document.cookie should natively perform that check.
Related
I'm trying to set and read a cookie value in asp.net core but the value is always null.
public async Task OnGet()
{
//Session Variable
HttpContext.Session.SetString("UserName", "User");
// HttpCookie cookie = HttpContext.Current.Request.Cookies[cookieName];
//Create new cookie
CookieOptions cookieOptions = new CookieOptions();
HttpContext.Response.Cookies.Append("user_id", "1", cookieOptions);
//bool cookieValueFromReq = Request.Cookies.TryGetValue("user_Id", out string strval);
cookieValue1 = Request.Cookies.TryGetValue("user_id", out string strval) ? strval : null;
I'm using cookie options to create a new cookie, which works. But I'm trying to figure out how to get the value of the cookie so I can read it.
Is there a way to read the cookie value in .net core? I've tried several ways that are commented out above. The last one was cookieValue1 which was null as well. Is there something I'm missing?
I'm building a web api and I have a method in my controller which gives the user a cookie. I can see it in the browser it is set, everything is fine.
[HttpGet]
[Route("[controller]/cookie")]
public IActionResult Cookie()
{
string cookieName = "av225461";
string key = $"blahblah";
HttpContext.Response.Cookies.Append(
cookieName, key,
new CookieOptions() { SameSite = SameSiteMode.Unspecified, HttpOnly = true, Expires =
DateTime.UtcNow.AddMinutes(15)/*, Secure = true*/ });
return Ok("");
}
But I am not able to read it in my Get method, if I am sending a request to my controller. The Cookies.Count is 0. Even if the cookie is set in browser and inthe requestheader of Firefox.
if (Request.Cookies.Count > 0)
{
//some code here
}
With postman sometimes it worked, and sometimes not. Someone an idea?
I am currently trying to replace our company wide user authentication that we use for all our internal web apps and what not as our current one was made in 2006 and fails on the regular. I was told to make it as simple as possible to implement on all existing projects. It is a .NET class library. It's .dll will be added as a reference to existing projects.
I am having an issue where I can log in exactly one time after all cookies have been cleared. Once I logout and log back in I get System.ArgumentException: Invalid value for 'encryptedTicket' parameter. I found some posts suggesting the cookie may be null, or I'm not trying to decrypt the name and not the value, but that wasn't the case. This happens on chrome and edge.
The user is authenticated every time though, assuming the correct username and password is used as I get redirected to the success page.
After authentication I add a cookie and then redirect.
private void AddCookie(int compID, bool persist, HttpContext httpContext)
{
httpContext.Request.Cookies.Add(SetUpSession(compID, persist));
FormsAuthentication.RedirectFromLoginPage(compID.ToString(), persist);
}
My method for creating the cookie
private HttpCookie SetUpSession(int companyID, bool persist)
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // ticket version
companyID.ToString(), // authenticated username
DateTime.Now, // issueDate
DateTime.Now.AddMinutes(30), // expiryDate
persist, // true to persist across browser sessions
FormsAuthentication.FormsCookiePath); // the path for the cookie
String encTick = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie("Cookie", encTick);
cookie.HttpOnly = true;
return cookie;
}
After I redirect to the success page there is a snipped of code that checks to see if the user is logged in. This is where the error happens
public dynamic isLoggedIn(HttpContext httpContext)
{
AuthenticationUtilities authUtil = new AuthenticationUtilities();
if (httpContext.Response.Cookies["Cookie"] != null)
{
companyID = authUtil.Authenticate(httpContext.Request.Cookies["Cookie"]);//the error occurs here
authUtil = new AuthenticationUtilities(companyID);
return authUtil;
}
else
{
httpContext.Response.Redirect("~/login.aspx");
return null;
}
}
The method that decrypts the cookie
public int Authenticate(HttpCookie cookie)
{
FormsAuthenticationTicket authTick = FormsAuthentication.Decrypt(cookie.Value);
return int.Parse(authTick.Name);
}
this method is called on any page that requires the user to be logged in, like this.
LMFJAuth.AuthenticationUtilities auth = _LMFJAuth.isLoggedIn(HttpContext.Current);//if the cookie is null it redirects to login.
This is the logout method
public void LogOut(HttpContext httpContext)
{
FormsAuthentication.SignOut();
HttpCookie cookie = new HttpCookie("Cookie");
cookie.Expires = DateTime.Now.AddMinutes(-1);
httpContext.Session.Clear();
httpContext.Response.Cookies.Add(cookie);
httpContext.Response.Redirect(FormsAuthentication.LoginUrl);
}
Can somone help explain what may be going on in which the value for the encrypted ticked is coming up as invalid after the first successful login/logout?
For me it was that the encrypted value of cookie.Value was coming up as greater than the maximum value of 4096, being 4200 in my case. I had just added some role strings to the user data.
I found it help to look up the source code of Microsoft classes when I'm stuck, in this case I used:
http://www.dotnetframework.org/default.aspx/DotNET/DotNET/8#0/untmp/whidbey/REDBITS/ndp/fx/src/xsp/System/Web/Security/FormsAuthentication#cs/1/FormsAuthentication#cs.
I have a single page application that starts off with default.aspx creating the basic HTML layout and then I use AJAX calls to get data from static WebMethods in other aspx pages. I also have a KeepAlive.aspx that reloads every once in a while to keep the session alive.
The login form that appears initially calls the login webmethod which uses an external web service to login and store user information in the session. I use HttpContext.Current.Session to get and set values in the session.
The very next web method that I call is to getuserpreferences from the external web service using identity information obtained at login time.
This is all working fine and dandy on various IIS servers. Recently we deployed this on a new server and it is not working there.
It does successfully login and saves the user values in session, but when the next ajax call to getuserpreferences happens, the getuserpreferences web method tries to get the session values... and it is NOT there any more!
I put in a bunch of logging and saw that session Id is changing! The login session id is different from the session id that I see from get userpreferences, even though both use HttpContext.Current.Session.
On the servers that it does work, sometimes (randomly?) it does behave in a similar way: it loses session values and throws me back to login.
Please provide help/tips to trace this issue and ensure the same session continues across ajax calls. This is not an MVC or WebAPI project; it is a simple aspx application.
UPDATE (Jan 8): I found the difference in behavior between the instances where this works and where it doesn't: ASP.Net_SessionId cookie value is being set where it works, but in this case it is not being set and is therefore not maintaining session state. Now I need to figure out why it is not setting.
Update 2 (Jan 8): When we installed a certificate on the server and implemented https, the session Id cookie started appearing. So although the issue is no longer urgent, I do want to find out why HTTP did not work.
Code:
WebServiceHelper.js
WebServiceHelper.prototype.invokeServiceMethod = function(serviceName, methodName, params, returntype) {
var self = this;
var obj = {};
var def = $.Deferred();
var url = serviceName + "/" + methodName;
$.support.cors = true;
$.ajax({
url: url,
data: ko.toJSON(params),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(mydata) {
if (mydata && mydata.d) {
def.resolve(mydata.d);
}
},
error: function(msg) {
def.reject(msg);
}
});
return def.promise();
};
Data Provider.js:
DataProvider.prototype.loginUser = function(email, password, token) {
var self = this;
var def = $.Deferred();
var webServiceHelper = new WebServiceHelper();
webServiceHelper.invokeServiceMethod("Login.aspx", "LoginUser", { email: email, password: password, token: token }, "json").done(function (retObj) {
self.userObj = retObj.userinfo;
self.loginTime = new Date();
self.loadInitialData();
def.resolve();
}).fail(
function(retObj1) {
def.reject(retObj1);
});
return def.promise();
};
Preference Manager.js
PreferenceManager.prototype.invokeGetPreferences = function (prefKey) {
var self = this;
var def = $.Deferred();
var webServiceHelper = new WebServiceHelper();
webServiceHelper.invokeServiceMethod("WebMethods.aspx", "GetPreferences", { key: prefKey }, "json").done(function (retObj) {
def.resolve(retObj);
}).fail(
function (retObj1) {
def.reject(retObj1);
});
return def.promise();
};
Login.aspx.cs:
[WebMethod(EnableSession=true)]
public static string LoginUser(string email, string password, string token)
{
if (Authenticate(email, password, token))
{
HttpContext.Current.Session["vanalyticsLastLoginDateTime"] = DateTime.Now;
var userjson = GetUserJson();
Logger.Debug("Login - Session Id {0} - Returning user json {1}", HttpContext.Current.Session.SessionID, userjson);
return userjson;
}
return "Error: " + _validationError;
}
private static bool Authenticate(string stremail, string strpassword, string token)
{
var vplug = new vPlugin();
HttpContext.Current.Session.Remove("vUserInfo");
vplug.Authenticate(HttpContext.Current, appsurl, stremail, strpassword, token);
_validationError = vplug.LastException != null ? vplug.LastException.Message : null;
return (HttpContext.Current.Session["vUserInfo"] != null);
}
vPlugin code: (eventually calls setuser)
private void SetUser(HttpContext obj, userInfo user)
{
HttpSessionState session = obj.Session;
session["vUserInfo"] = user;
....
session["vDataToken"] = setting.ContainsKey("token") ? setting["token"] : "0-0";
}
WebMethods.aspx:
[WebMethod(EnableSession=true)]
public static string GetPreferences(string key)
{
var myadr = new ADR.VrtDataService { Timeout = 20000 };
var token = GetTokenFromSession();
try
{
var result = myadr.getPreference(token, key);
myadr.Dispose();
return result;
}
catch (Exception ex)
{
return "Error: " + ex.Message;
}
}
public static string GetTokenFromSession()
{
var token = "";
var val2 = HttpContext.Current.Session["vDataToken"];
if (val2 != null)
{
token = (string) val2;
}
else
{
Logger.Error("Token is blank, session id is " + HttpContext.Current.Session.SessionID);
}
return token;
}
I am getting 'Token is blank' and the session id is different from the Id logged by the login method earlier.
Also, please note that the entire code is in JavaScript and aspx only serves as RESTful API with session.
It's Simple Just Use
HttpContext.Current.Session["user_id"] = ""
I am calling a void function using jquery ajax in mvc3. In that function when the Session is out then also it will come to success function of ajax. I need to know whether the Session is available or not before sending the request or inside the success function of ajax.
controller Action:
protected override void Save(Query query, string queryTitle)
{
}
Why not catch the expiry of the session on the server, return an HTTP 401 Unauthorized, then check for this response in jquery and pop up a "Your session has expired, please log in again" page?
Detecting Session expiry on ASP.NET MVC
How to set HTTP status code from ASP.NET MVC 3?
How do I get the HTTP status code with jQuery?
The code you need on the initial server call is:
protected void Save(Query query, string queryTitle)
{
// would probably be better to refactor this bit out into its own method
string sCookieHeader = Request.Headers["Cookie"];
if (Context.Session != null
&& Context.Session.IsNewSession
&& sCookieHeader != null
&& sCookieHeader.IndexOf("ASP.NET_SessionId") >= 0)
{
// session has expired
if (Request.IsAuthenticated)
{
FormsAuthentication.SignOut();
}
Response.StatusCode = 401
}
else
{
// we're authenticated, so do the save
}
}
and on the client:
$.ajax(serverUrl, {
data: dataToSave,
statusCode: {
200: function(response) {
// all good, continue
401: function (response) {
// session expired!
// show login box
// make ajax call to reauthenticate
// call save method again
},
});
Your reauthentication call would look something like this:
public ActionResult Reauthenticate(username, password)
{
if (IsValidUser(username, password))
{
// sometimes used to persist user roles
string userData = string.Join("|",GetCustomUserRoles());
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // ticket version
username, // authenticated username
DateTime.Now, // issueDate
DateTime.Now.AddMinutes(30), // expiryDate
isPersistent, // true to persist across browser sessions
userData, // can be used to store additional user data
FormsAuthentication.FormsCookiePath); // the path for the cookie
// Encrypt the ticket using the machine key
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
// Add the cookie to the request to save it
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
}
}
(Adapted from How to set HTTP status code from ASP.NET MVC 3?)
Why not try this ?
public void Save()
{
if (Session.IsNewSession)
{
throw new Exception("This session was just created.");
}
//Go on with save matter...
}
This should return a status 500 on your AJAX function and should cause the response to fall in the fail method you defined.
Another way is to setInterval() on the client that continually sends a dummy request to the server to keep the session alive, at least when the user is editing. This might be the best way to prevent them user from losing work. You could also use this to detect loss connectivity.
When the page is loaded first time , pass the current SessionId to the client side and assign to the local javascript variable.Next have a method which will return the current SessionId before making the Save method call from the AJAX , compare the local variable against the Session Id you have received.
public string GetCurrentSessionId(){
return HttpContext.Current.Session.SessionId;
}
Javascript function
$.ajax({
Url : 'GetCurrentSessionId',
success : function(result){
if(result === "LOCALSESSIONID")
CALL THE SAVE METHOD
else
alert('Session is expired');
}
});