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?
Related
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.
When using cookie authentication in ASP.NET MVC, after calling PasswordSignInAsync to log the user in, a cookie with encrypted session information is stored for future requests. By default this is named .AspNet.ApplicationCookie. Is there a way to get the value of that cookie immediately after signing the user in, before leaving the method that it was called from?
I've inspected Response.Cookies after successful sign in, but it doesn't contain any values and I can't figure out when that cookie is actually being set.
No, you can't get the value of that cookie in the same request as where the cookie is set - the setting is delayed until very late, when the reply is actually sent.
But the cookie is encrypted and not much you can do with the value anyway. I suspect you want to add data to the cookie, but there are better ways to do it, without having to modify cookie itself.
I discovered that it is possible to intercept the value of the cookie before returning the response, although not in the same method as the signin like I was originally hoping for.
The following code needs to be added in the ConfigureAuth method:
const string applicationCookieName = ".AspNet.ApplicationCookie";
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/"),
CookieName = applicationCookieName,
Provider = new CookieAuthenticationProvider
{
// Called *after* user is signed in -- the cookie
// we want has been set at this point.
OnResponseSignedIn = context =>
{
var cookies = context.Response.Headers.GetCommaSeparatedValues("Set-Cookie");
var cookieValue = "";
foreach (var cookie in cookies)
{
var cookieKeyIndex = cookie.IndexOf(applicationCookieName);
if (cookieKeyIndex != -1)
{
// Add extra character for '='
cookieValue = cookie.Substring(applicationCookieName.Length + 1);
break;
}
}
// Do what you need with cookieValue
}
}
});
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
i use this code but it return Object reference not set to an instance of an object.
what is the wrong with it
You should be creating the cookie outside of the constructor, so you can at least discern why it's throwing the exception.
Typically for something like this I would do the following :
// create the auth cookie with the domain you've specified
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName)
{
Domain = FormsAuthentication.CookieDomain;
};
// create the auth ticket and encrypt it
var authTicket = new FormsAuthenticationTicket(1, "USERS_EMAIL_OR_USERNAME", DateTime.Now, DateTime.Now.AddHours(24), true, "ANY_USER_INFO_THAT_SHOULD_GO_INTO_THE_COOKIE");
var encryptedTicket = FormsAuthentication.Encrypt(authTicket);
// set the cookie value to the encrypted ticket
cookie.Value = encryptedTicket;
// now, add it to the response, but remove the old one in case it's still there
Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
Response.Cookies.Add(cookie);
If anything, that will at least allow you to find out what's causing your null reference exception, if not fix the issue entirely.
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.
When a user logs in to my site, I create a cookie with some info in it. However, whenever they change page from logging in, the cookie loses it's value. Cookie is still there but it's empty.
I've checked my code and the cookie doesn't get rewritten by anything I've done.
Does anyone have any idea to why the cookie becomes empty when the page is changed?
Here's the method for creating the cookie.
public static void CreateUserCookie(long userId, string username, bool rememberMe) {
HttpCookie cookie = new HttpCookie("CookieName");
cookie.Value = string.Format("{0}+{1}+{2}", userId, username, SecurityUtils.CreateHashedCookieValue(userId, username));
if (rememberMe) {
cookie.Expires = DateTime.Now.AddMonths(1);
} else {
cookie.Expires = DateTime.MinValue;
}
HttpContext.Current.Response.Cookies.Add(cookie);
}
When you call this method, do you pass in true for the "rememberMe" parameter? If not, the cookie will instantly expire.
You haven't shown your calling code, so this is potentially what you've done.