I have an application where i am doing a sessionTimeout of 3 hours.
this.SessionTimeout= createTimespan( 0, 3, 0, 0 );
on my sessionstart method, I had
session.startlogging = true;
on my sessionend method I have
session.startlogging = false;
in my code i want to add a code where I can check if he has already active session and one entry is made, do not make other entry,
wait until session expires and new session is setup and then make an entry
so i did like this
if (!StructkeyExists(session,'startlogging')) {
do my insert
}
Related
In my Application ID I changed in security attributes -> Maximum Session Idle Time in Seconds as 900 seconds, but issue is if I am on same page number it gives me session timeout message.
I want session timeout on user's movement over the page or other tabs it should not be restricted because all my application work is in mostly one page.
Session timeout is managed by the web application server and it needs a request or form submission to tell him, hey I'm alive, dude please don't kill the session, so for that reason you need to create an ajax request to tell web server you are still there.
You can use this script to detect user inactivity
var IDLE_TIMEOUT = 60; //seconds
var _idleSecondsCounter = 0;
document.onclick = function() {
_idleSecondsCounter = 0;
};
document.onmousemove = function() {
_idleSecondsCounter = 0;
};
document.onkeypress = function() {
_idleSecondsCounter = 0;
};
window.setInterval(CheckIdleTime, 1000);
function CheckIdleTime() {
_idleSecondsCounter++;
var oPanel = document.getElementById("SecondsUntilExpire");
if (oPanel)
oPanel.innerHTML = (IDLE_TIMEOUT - _idleSecondsCounter) + "";
if (_idleSecondsCounter >= IDLE_TIMEOUT) {
alert("Time expired!");
document.location.href = "logout.html";
}
}
Check this post Detecting user inactivity over a browser - purely through javascript
I configured Identity Server:
public void Configuration(IAppBuilder app)
{
var factory = new IdentityServerServiceFactory().UseInMemoryClients(new Client[] {
new Client()
{
ClientName = "MyClient",
ClientId = "MyClientId",
Enabled = true,
Flow = Flows.Implicit,
RedirectUris = new List<string> { "MyClientServer/callback" },
};
});
}
and client server:
public void Configuration(IAppBuilder app)
{
var cookieOptions = new CookieAuthenticationOptions();
cookieOptions.AuthenticationType = "Cookies";
app.UseCookieAuthentication(cookieOptions);
var authenticationOptions = new OpenIdConnectAuthenticationOptions() {
Authority = "https://MyIdentityServer/core",
ClientId = "MyClientId",
SignInAsAuthenticationType = "Cookies",
UseTokenLifetime = true,
RedirectUri = "MyClientServer/callback"
});
app.UseOpenIdConnectAuthentication(authenticationOptions);
}
When user login with "Remember Me" option Identity cookie has expired date:
idsvr.session expires 04 October ...
But client cookie does not:
.AspNet.Cookies at end of session
What should I do to set the same expiration date to client cookie?
UPDATE:
I can set any expiration date in client application:
authenticationOptions.Provider = new CookieAuthenticationProvider()
{
OnResponseSignIn = (context) =>
{
var isPersistent = context.Properties.IsPersistent;
if (isPersistent) // Always false
{
context.CookieOptions.Expires = DateTime.UtcNow.AddDays(30);
}
}
};
But I cannot determine when to set expiration date. It should be set only when user selects "Remember Me", but IsPersistent option always false on client side.
The problem exists on simple boilerplate project too:
https://identityserver.github.io/Documentation/docsv2/overview/mvcGettingStarted.html
UPDATE2:
I need client cookie to be persistent because of bug in Safari - https://openradar.appspot.com/14408523
Maybe some workaround exists, so I can pass expiration date in callback from Identity to Client?
UPDATE3:
Actually, our Identity and Client servers have same parent domain like app.server.local and id.server.local. Maybe I can pass expiration date via additional cookie that belongs to parent domain (.server.local)? But I have no idea where it can be written on Identity, and where it can be applied on Client.
A cookie issued by IdentityServer and a cookie issued by a client application are not linked in any way. IdentityServer does not have any control over cookies in a client application.
When you log in to IdentityServer, you are issued a cookie that tracks the authenticated user within IdentityServer. This saves the user from entering their credentials for every client application, facilitating single sign on.
By default this cookie lasts for that session (so it expires once the browser closes), otherwise if you set "remember me" it will last for a set number of days, across sessions.
A cookie in a client application would be issued upon successful verification of an identity token from IdentityServer. This cookie can have any expiration time, any policy, any name. It's completely controlled by the client application. In your case client cookie expiration can be set in the CookieAuthenticationOptions in your client application.
You need to handle the cookie auth events. The open id middleware just creates an auth cookie, so you can handle all aspects of this cookie from those events. You'll need to look at the events and with a little trial and error you should be able to manage the cookie lifetime.
You can do it at the java-script by using following code in here I have created this cookie to expires within 14 days.
var exdate = new Date();
exdate.setDate(exdate.getDate() + 14);
document.cookie = "yourcookie=" + yourCookieValue + ";expires=" + exdate.toUTCString() + ";";
I have a event receiver in my project and in the event receiver I have following code. It is bound to custom list.
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
// Get the web where the event was raised
SPWeb spCurrentSite = properties.OpenWeb();
//Get the name of the list where the event was raised
String curListName = properties.ListTitle;
//If the list is our list named SubSites the create a new subsite directly below the current site
if (curListName == "Customers")
{
//Get the SPListItem object that raised the event
SPListItem curItem = properties.ListItem;
//Get the Title field from this item. This will be the name of our new subsite
String curItemSiteName = properties.AfterProperties["Title"].ToString();
//Get the Description field from this item. This will be the description for our new subsite
string curItemDescription = properties.AfterProperties["Description"].ToString();
//Update the SiteUrl field of the item, this is the URL of our new subsite
properties.AfterProperties["SiteUrl"] = spCurrentSite.Url + "/" + curItemSiteName;
//Create the subsite based on the template from the Solution Gallery
SPWeb newSite = spCurrentSite.Webs.Add(curItemSiteName, curItemSiteName, curItemDescription, Convert.ToUInt16(1033), "WIKI#0", false, false);
//Set the new subsite to inherit it's top navigation from the parent site, Usefalse if you do not want this.
newSite.Navigation.UseShared = true;
CreateList(newSite);
newSite.Close();
}
}
This code works fine for farm solutions. For sandbox solutions it gives exception at :
SPWeb newSite = spCurrentSite.Webs.Add(curItemSiteName, curItemSiteName, curItemDescription, Convert.ToUInt16(1033), "WIKI#0", false, false);
Says "he sandboxed code execution request was refused because the Sandboxed Code Host Service was too busy to handle the request."
Any suggestion??
I have a question about the push notification service of the Windows Phone 7 device:
I can now send a push notification, using a web application to a phone, changing the data of the tile. But the problem is: when I start the app, I need to display the URI in the debugger output, and then copy-paste it inside the web application, which in turn will contact the MPNS, which is fine for an update, once to a single phone. But I want to create a webservice that can make multiple calls automatically, retrieve the URI of the application ( which changes after closing-and-opening the app, I think ) and send a push notification to it. But I haven't found an MSDN - topic that deals with this. They just use commends, saying : "to be replaced later with the URI needed." So my question is: how do I use the phone to send such a message to the webservice, respond to it, and connect to the phone again, handling such request?
and also: do I need an authenticated webservice, or is there a debug version?
This is what I have thus far :
/// <summary>
/// Setup a connection with a webservice, in order to update a shell, either a toast- or a tile shell.
/// </summary>
/// <param name="shellType">The type of shell you wish to update</param>
public void SetupShellChannel ( ShellBindType shellType )
{
//holds the push notification that is created. Since we can only have one notification channel open at any one time,
//we will need to check for existance. That is why, the channelName shouldn't be changed
HttpNotificationChannel _httpChannel = HttpNotificationChannel.Find( _channelName );
//if the _httpChannel was not found ( read: does not exist )
if ( _httpChannel == null )
{
_httpChannel = new HttpNotificationChannel( _channelName );
_httpChannel.Open( );
//because there is more than one shelltype we can open, we will use a switch to call the method we seek
BindToShell( _httpChannel, shellType );
}
//Only one push notification service is allowed per application, so we cannot send a tile notification, as well as
//a toast message notification. When we attempt this, we get a InvalidOperationException
else
{
//in this case, the _httpChannel did already exist, but the problem is, we cannot just add the eventHandlers,
//because there is the danger that it didn't exist, and we would get a null pointer exception.
//_httpChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>( httpChannel_ChannelUriUpdated );
//_httpChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>( httpChannel_ErrorOccurred );
//For testing purposes, we now display the URI to the user, and as output. Normally, we would pass this URI back to the webserver
System.Diagnostics.Debug.WriteLine( _httpChannel.ChannelUri.ToString( ) );
}
//if ( _httpChannel.ChannelUri )
//When the URI is updated, we want this to be sent to the server as well, so we know that the adress has changed,
//and don't just send data somewhere into the void. Also, when encountering an error, we want to show the user when
//an error has occured.
_httpChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>( HttpChannel_ChannelUriUpdated );
_httpChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>( HttpChannel_ErrorOccurred );
}
//here, also we would return the URI to the server, but for debugging purposes, we display them to the user.
void HttpChannel_ChannelUriUpdated( object sender, NotificationChannelUriEventArgs e )
{
Deployment.Current.Dispatcher.BeginInvoke( ( ) =>
{
System.Diagnostics.Debug.WriteLine( e.ChannelUri.ToString( ) );
MessageBox.Show( String.Format( "the URI is {0}", e.ChannelUri.ToString( ) ) );
} );
}
private void BindToShell( HttpNotificationChannel channel, ShellBindType shellType )
{
switch ( shellType )
{
case ShellBindType.BindToShellTile:
channel.BindToShellTile( );
break;
case ShellBindType.BindToShellToast:
channel.BindToShellToast( );
break;
}
}
void HttpChannel_ErrorOccurred( object sender, NotificationChannelErrorEventArgs e )
{
//getting an error would be caugth here, and then displayed to the user.
Deployment.Current.Dispatcher.BeginInvoke( ( ) =>
{
MessageBox.Show( String.Format( "A push notification {0} error occured. {1}{(2)}{3}",
e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData ) );
} );
}
Ok I understand your question. What I have done is once I get teh URI from MPNS, I call a web method on a service with this as a parameter -
Subscribe(int subscriberId, Uri channelUri);
So you need to make sure you generate a subscriberId in your app to identify a user and store it in Isolated Storage. This can be a GUID.
The onus is now upon hte server to save the Subscriber to Uri mapping in persistant storage.
Also you need to provide UnSubscribe method for user to opt out of the push notification. This is one of the certification requirement for Push notifications.
Now about your second question - Yes, you would need to secure your services - you dont want to be handling with unknown requests.
What i do personally, divide it into 2 services - Publishing service and subscription service. The Publishing service will send out hte notifications while subscription will have the subscribe/unsubscribe methods.
I guess you are trying to ask that you can send push notification from Windows Phone itself or not instead using any other server side ASP/PHP like explained in Sample Applications in MSDN. Yes. You can send notifications from phone/device itself. You have to just change Send function of Sample app as given in MSDN. Reply if you have any queries.
static async Task<string> SendPushNotification(string textToSend)
{
//You can maintain a DB to query different channel URIs of devices
string subscriptionUri = "<Uri To Which You Want Send Notification>";
HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(subscriptionUri);
sendNotificationRequest.Method = "POST";
string toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Toast>" +
"<wp:Text1>" + textToSend + "</wp:Text1>" +
"<wp:Param>/NotificationDetails.xaml?Message=" + textToSend + "</wp:Param>" +
"</wp:Toast> " +
"</wp:Notification>";
byte[] notificationMessage = Encoding.UTF8.GetBytes(toastMessage);
sendNotificationRequest.ContentLength = notificationMessage.Length;
sendNotificationRequest.ContentType = "text/xml";
sendNotificationRequest.Headers["X-WindowsPhone-Target"] = "toast";
sendNotificationRequest.Headers["X-NotificationClass"] = "2";
using (var requestStream = await Task.Factory.FromAsync<Stream>(sendNotificationRequest.BeginGetRequestStream, sendNotificationRequest.EndGetRequestStream, null))
{
requestStream.Write(notificationMessage, 0, notificationMessage.Length);
}
string notificationStatus;
using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(sendNotificationRequest.BeginGetResponse, sendNotificationRequest.EndGetResponse, null)))
{
//StreamReader reader = new StreamReader(response.GetResponseStream());
//result = reader.ReadToEnd();
notificationStatus = response.Headers["X-NotificationStatus"];
MessageBox.Show(notificationStatus);
}
return notificationStatus;
}
I'm having trouble creating a non-persistent cookie using the FormsAuthenticationTicket. I want to store userdata in the ticket, so i can't use FormsAuthentication.SetAuthCookie() or FormsAuthentication.GetAuthCookie() methods. Because of this I need to create the FormsAuthenticationTicket and store it in a HttpCookie.
My code looks like this:
DateTime expiration = DateTime.Now.AddDays(7);
// Create ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2,
user.Email,
DateTime.Now,
expiration,
isPersistent,
userData,
FormsAuthentication.FormsCookiePath);
// Create cookie
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
cookie.Path = FormsAuthentication.FormsCookiePath;
if (isPersistent)
cookie.Expires = expiration;
// Add cookie to response
HttpContext.Current.Response.Cookies.Add(cookie);
When the variable isPersistent is true everything works fine and the cookie is persisted. But when isPersistent is false the cookie seems to be persisted anyway. I sign on in a browser window, closes it and opens the browser again and I am still logged in. How do i set the cookie to be non-persistent?
Is a non-persistent cookie the same as a session cookie? Is the cookie information stored in the sessiondata on the server or are the cookie transferred in every request/response to the server?
Try deleting:
if (isPersistent)
{ cookie.Expires = expiration; }
... and replacing it with:
if (!isPersistent) {
cookie.Expires = DateTime.Now.AddYears(-1); }