My cookie test isn't working - c#

I am testing to see whether the user has cookies turned on and I don't seem to be doing something right.
Here is my test:
private bool CookiesAllowed()
{
var testCookie = new HttpCookie("TestCookie", "abcd");
System.Web.HttpContext.Current.Response.Cookies.Set(testCookie);
var tst = System.Web.HttpContext.Current.Request.Cookies.Get("TestCookie");
if (tst == null || tst.Value == null)
{
return false;
}
return true;
}
I'm putting a cookie out there... and then getting it back. But it always succeeds.
Here is how I'm disabling them:
I go to Gmail and it tells me my cookies are disabled so I believe I am doing that part right.
What am I doing wrong?
EDIT
To answer James' question, I am calling this from my logon screen, which is my entry screen as the first check:
public ActionResult LogOn(string id)
{
if (!CookiesAllowed())
{
return View("CookiesNotEnabled");
}
Also, I have tested this live, outside of visual studio and not at localhost and it did the same thing.

You have to let your client/browser do a new Request in order to see if you get the cookie back. When you add a Cookie to the response object, you can only check the presence of it in subsequent new Requests.
Here's a way to do it within the same page in ASP.NET WebForms (since I saw your edit indicating you are using MVC):
private bool IsCookiesAllowed()
{
string currentUrl = Request.RawUrl;
if (Request.QueryString["cookieCheck"] == null)
{
try
{
var testCookie = new HttpCookie("SupportCookies", "true");
testCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(testCookie);
if (currentUrl.IndexOf("?", StringComparison.Ordinal) > 0)
currentUrl = currentUrl + "&cookieCheck=true";
else
currentUrl = currentUrl + "?cookieCheck=true";
Response.Redirect(currentUrl);
}
catch
{
}
}
return Request.Cookies.Get("SupportCookies") != null;
}
This code snippet is inspired by this thread.

Related

Refresh sectionTree on new user login

I have a sectiontree which varies based on the current logged in users UserType.
The thing is that if i log-out from the backoffice, and logs in with a new user with a lower UserType, the tree is not refreshed - The code is not rerun to generate the tree.
This means that the user with a non administrative UserType can access administrative areas in the section, as long as an administrator have been logged in earlier on the same solution.
How would i make the SectionTree refresh on new users login?
Update
protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings)
{
var sectionApi = new SectionApiController();
// Root handler
if (id == Constants.System.Root.ToInvariantString())
{
this.RootHandler();
}
else if(id.Contains("COUNTRY_") || id.Contains("LEVEL_") )
{
var section = new IdConvert(id);
if ( section.Area.Equals("country") )
{
this.FirstLevelHandler(section.Id);
}
else if (section.Area.Equals("level"))
{
this.GetLevels(section.Id);
}
// Render clubs.
this.ClubHandler();
// Render levels
this.LevelHandler();
} else if(id.Contains("CLUB_")) {
}
else if(id.Contains("SPORTS_")) {
var Country = new IdConvert(id);
this.SportsHandler(Country.Id);
}
else if (id.Contains("QUESTIONS_"))
{
var Country = new IdConvert(id);
this.QuestionsHandler(Country.Id);
}
return this._nodes;
}
The Tree works fine, it renders what it should render. But It doesent refresh upon new user login.
I'm using the following to check wether or not a person is "admin"
public static bool IsAdministrator()
{
try
{
if (_curNewUser == null)
{
GetCurrentUser();
}
if (_curNewUser.UserType.Alias == "admin")
{
return true;
}
}
catch (Exception e) { }
return false;
}
Based on a comment you are not clearing _curNewUser when user logs out and that's why you are seeing this issue.
Instead of keeping the reference to _curNewUser you should use umbraco built in UmbracoContext.Current.Security.CurrentUser directly in your UserProvider and that will fix it, something like this:
public static bool IsAdministrator()
{
var user = UmbracoContext.Current.Security.CurrentUser;
return user != null && user.UserType.Alias == "admin";
}
No need for you to hook up to logout events or anything like that.

SoundCloud API - can't get past 2nd page of results using linked_partitioning

Hi there I have recently switched from using an offset to linked_partitioning to get paginated results from the SoundCloud API as detailed here: https://developers.soundcloud.com/blog/offset-pagination-deprecated
The issue I have is that when I get to the second page of results, the next_href value is exactly the same as the url used to get the second page of results, hence I can never get past the second page.
Here is the code I am using:
this.feedItemRootObject = await this.soundCloudRequester.GetFeedItems(TracksToLoadUrl, roamingSettings.Values["access_token"].ToString());
if (this.feedItemRootObject != null)
{
if (!string.IsNullOrEmpty(this.feedItemRootObject.LoadMoreUrl))
{
TracksToLoadUrl = this.feedItemRootObject.LoadMoreUrl;
}
else
{
this.HasMoreItems = false;
}
bindableTracks = await TrackConverter.ConvertToListOfFeedItems(this.feedItemRootObject);
}
else
{
this.HasMoreItems = false;
return null;
}
and the original URL I am using is https://api.soundcloud.com/me/favorites.json?limit=20&linked_partitioning=1&oauth_token=
Any help is much appreciated!

How to detect if WSFederationSession has expired or ended?

I have a several methods in controller:
public ActionResult Issue()
{
var message = WSFederationMessage.CreateFromUri(HttpContext.Request.Url);
// sign in
var signinMessage = message as SignInRequestMessage;
if (signinMessage != null)
{
return ProcessWSFederationSignIn(signinMessage, ClaimsPrincipal.Current);
}
// sign out
var signoutMessage = message as SignOutRequestMessage;
if (signoutMessage != null)
{
return ProcessWSFederationSignOut(signoutMessage);
}
return View("Error");
}
And the most valuable for me in this question:
private ActionResult ProcessWSFederationSignOut(SignOutRequestMessage message)
{
FederatedAuthentication.SessionAuthenticationModule.SignOut();
var mgr = new SignInSessionsManager(HttpContext, _cookieName);
// check for return url
if (!string.IsNullOrWhiteSpace(message.Reply) && mgr.ContainsUrl(message.Reply))
{
ViewBag.ReturnUrl = message.Reply;
}
return View("Signout");
}
All works fine, but, there are interesting moment.
This thing works in both cases, if I ended session by myself, or session simply expired. Its fine but actually, I need to tell the difference between those cases, write in ViewBag something like "You are singed out" or "Session expired" depends on result and show it oy the View.
Is there are some kind of way to detect session expired situations or should it be something different?
P.S Sorry for my bad English.
Since you changed the topic I will update my answer. I haven't used WSFederatinSession but maybe you could store the inf about how session ended (in a cookie for example) and during the next request (in a global asax for example) read this inf and do what you want to do.

How to clear/change the query string in aspx page?

I have two pages
1. a.aspx and
2. b.aspx
I pass query string from "b.aspx?save=success" to a.aspx.
In Page Load of a.aspx I have the following code:
Page_Load()
{
if(!Postback)
{
if (Request.QueryString["save"] != null)
{
noDataFound.InnerHtml = "operation success";
}
}
}
Problem: On load of a.aspx page I get the message "operation success". This is Ok.But When I refresh the page again I get the same message as "operation success". How not to display again the same message on page refresh(pressing F5or reload).
function invokeMeMaster() {
var isPostBack = <%= Page.IsPostBack ? "true" : "false" %> ;
if (!isPostBack) {
/* START */
var query = getQueryParams(document.location.search);
var p = query.save;
if (sessionStorage.hits) {
sessionStorage.hits = Number(sessionStorage.hits) + 1;
} else {
sessionStorage.hits = 1;
}
if (p == "success" && (sessionStorage.hits) % 2 == 0) {
document.getElementById("<%=noDataFound.ClientID %>").innerText = "Testing...........";
}
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {}, tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
}
return params;
}
/* END */
} else {
document.getElementById("<%=noDataFound.ClientID %>").innerText = "";
}
}
window.onload = function () {
invokeMeMaster();
};
untested solution (Keeping F5 or Reload of Page in mind), may be you have do something like below:
if(!IsPostBack)
{
if (Request.QueryString["save"] != null && Session["CheckSuccess"] == null)
{
noDataFound.InnerHtml = "operation success";
Session["CheckSuccess"] = "true";
}
else
noDataFound.InnerHtml = string.Empty;
}
The best I can think of is using the IsPostback property to check that.
if (!this.IsPostback)
{
// first try
if (Request.QueryString["save"] != null)
{noDataFound.InnerHtml = "operation success";}
}
NOTE: IsPostback is not set on refresh, only if clicking a button or something alike triggers the ASP.NET postback action.
The other thing you could do is set a Session variable then the 'operation succesful' must be shown (probably you determine this in another Page.
// other page
Session["showSaveMessage"] = true;
// this page
if (Session["showSaveMessage"] == true)
{
// show message
Session["showSaveMessage"] = false;
}
A third option is to move this client side. Create a javascript action on load of the page. When a specific part is added to the query string (#showmessage), you can catch that and show the message (How to get the value from the GET parameters?).
Then redirect to the parameterless version (#) by setting the url to the stripped version. Set window.location.href or window.location.search for that (this won't cause a call to the webserver, since it is all client side).
This circumvents the drawbacks of the first solution, but introduces more code client side. Luckily, ASP.NET MVC has some mechanisms for this. Unfortunately ASP.NET Web Forms doesn't have those.

Asp.net MVC 4 and FormsAuthentication.User

Im trying to use FormsAuthentication in asp.net MVC 4 application.
The authentication itself works fine, but whenever Im getting the User from FormsAuthenticationEventArgs.User and assign to Http.Context.Current.User it works at that exactly moment and next call method bellow Http.Context.Current.User is null again...
What am I doing wrong?
protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
{
if (FormsAuthentication.CookiesSupported == true)
{
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
try
{
string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
var usuarioRn = new UsuarioRN();
string roles = usuarioRn.GetRoles(username);
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value);
e.User = new System.Security.Principal.GenericPrincipal(new System.Web.Security.FormsIdentity(ticket), roles.Split(';'));
//First time get here assign e.User to HttpContext.Current.User, all good
//Next call HttpContext.Current.User is again null, why?
HttpContext.Current.User = e.User;
}
catch (Exception)
{
}
}
}
FormsAuthenticationEventArgs.User is just so you can set the User property of the current HttpContext to a custom IPrincipal object.
It would probably be a lot easier to understand if it had this signature:
FormsAuthenticationEventArgs.SetHttpContextUser(IPrinciple user);
In other words, it will always be null - it actually sets something else (the HttpContext User) when you assign something to it.

Categories