Archive

Author Archive

Mixed Mode with MVC & Identity

May 1, 2015 2 comments

This post is a brief description of how to go about setting up a mixed mode authentication scenario. In our scenario we use Identity Server 3 and windows Authentication. For Identity Server, we utilize OWIN’s UseOpenIdConnectAuthentication. However, certain customers who require us to setup our applications on their internal networks ask that their users not have to authenticate to a separate application.

Ultimately what we ended up doing is creating a single WinAuth.aspx page. In IIS we set authentication to this page only to Windows.

For us we then use an app.settings value so we can disable Mixed Mode if we want to. If enabled, in our RegisterRoutes, we set the default route to a WindowsLogin action which allows Anonymous. In the action we check for user authenticated and if not, they are redirected to the WinAuth.aspx page.

In the WinAuth.aspx we use the following code:


if(Request.LogonUserIdentity.IsAuthenticated)

{


string _windowsUserName = Request.LogonUserIdentity.Name.Split(‘\\’)[1];

 


SLAppUserManager _userManager = new
SLAppUserManager(new
UserStore<SLApplicationUser>(new
CredentialService<SLApplicationUser>()));

 


// Figure out what to user here, our UserManager or what


// Make call to GetWindowsUserByName to get username and password.

 


// See if a user exists which matches the windows user.


var _slUser = await _userManager.FindByNameAsync(_windowsUserName);

 


if(_slUser != null)

{


// Create an IdentityUser


// var _userIdentity = await _slUser.GenerateUserIdentityAsync(_userManager);

 


// Next authenticate the user

 

 


var _tokenClient = new
OAuth2Client(


new
Uri(ConfigurationManager.AppSettings[“IdentityTokenEndpoint”]),


ConfigurationManager.AppSettings[“ClientId”],


ConfigurationManager.AppSettings[“ClientSecret”]

);

 


var _response = await _tokenClient.RequestResourceOwnerPasswordAsync(_slUser.UserName, _slUser.PasswordLegacy, “openid email profile SLWindowsAuthentication offline_access”);

 

 


if(!string.IsNullOrEmpty(_response.AccessToken))

{


BearerTokenMessageInspector _inspector = new
BearerTokenMessageInspector();

 


TokenValidationParameters _validationParameters = _inspector.CreateTokenValidationParameters();

 

 


SecurityToken _securityToken = null;

 


JwtSecurityTokenHandler _tokenHandler = new
JwtSecurityTokenHandler();

 


// Next call will throw the exception if the token or configuration is not valid


// var identities = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers.ValidateToken(tokenString, _validationParameters, out _securityToken);


var _claimsPrincipal = _tokenHandler.ValidateToken(_response.AccessToken, _validationParameters, out _securityToken);

 

 


var _ctx = HttpContext.Current.GetOwinContext();

 


var _authenticationManager = _ctx.Authentication;

 


// Not sure why this is needed on a new login but I see it in examples and


// adding this did seem to fix the problem

_authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);

 


//var _identity = await _userManager.CreateIdentityAsync(_slUser, DefaultAuthenticationTypes.ApplicationCookie);


var _identity = await _userManager.CreateIdentityAsync(_slUser, DefaultAuthenticationTypes.ApplicationCookie);

 


var _claims = new
List<Claim>(from c in _claimsPrincipal.Claims


where c.Type != “scope” &&

c.Type != “client_id” &&

c.Type != “iss” &&

c.Type != “aud” &&

c.Type != “nbf” &&

c.Type != “exp” &&

c.Type != “iat” &&

c.Type != “nonce” &&

c.Type != “c_hash” &&

c.Type != “at_hash”


select c);

 


//var _identity = new ClaimsIdentity(_claimsPrincipal.Claims, DefaultAuthenticationTypes.ApplicationCookie);

 

_identity.AddClaims(_claims);

 

_identity.AddClaim(new
Claim(“access_token”, _response.AccessToken));

_identity.AddClaim(new
Claim(“expires_at”, DateTime.Now.AddSeconds(_response.ExpiresIn).ToLocalTime().ToString()));

_identity.AddClaim(new
Claim(“refresh_token”, _response.RefreshToken));

 


ClaimsPrincipal _cp = new
ClaimsPrincipal(_identity);

 

 


// Session[“SLWindowsOpenIdClaimsPrincipal”] = _cp;

 


// await _authenticationManager.AuthenticateAsync(“SLWindowsOpenIdAuthentication”);

 


// 5/1/15 – After a lot of hours, all this works if we call the signout above in code first.

_authenticationManager.SignIn(new
AuthenticationProperties() { IsPersistent = false }, _identity);

 

First we make sure the user was authenticated to the domain the IIS server is a part of. If so, we use our own custom FindByName method to check that a user associated with the AD account is found.

If so, then we get an access token from our Identity Server. We then create Token Validation parameters and then we use the Microsoft JwtSecurityTokenHandler to Validate the token.

Next we get the OwinContext so we can use it’s AuthenticationManager. The SignOut call, I’m not exactly sure what that’s doing when a user was not logged in but it must be called or the SignIn will not work.

Then we manually create an Identity, we strip all irrelevant claims out. Then finally a call is made to the AuthenticationManager.SignIn.

Once all of the above have completed, then the OwinContext.Authentication.User is properly populated to be utilized in the rest of the application.

 

 

 

Advertisements
Categories: Software Architecture

Identity Server v3 LOB Part 3 Clients

March 5, 2015 Leave a comment

This is Part 3 of a series of three posts about setting up and configuring Identity Server for a Line of Business application.

Links

Intro Identity Server v3 Walk through for LOB application

Part 1 Hosting Identity Framework With IIS

Part 2 IDSv3 Web Api & WCF Configuration

Part 3 IDS Client Walkthrough

Client Sample Code

Identity Server Code

In Part 3, we’re going to walk through the MyJWTConsole application which is a simple console application which gets a JWT token and makes calls to a Web Api service and then a WCF service.

As mentioned in Part 2, to build a WSDL from an WCF using the BearerTokenMessageInspector, you must disable this in the web.config file of the WCF service first. Generate the service reference and then re-enable the message inspector.

The rest of the code in this sample, took from the Identity Server Simple Oauth authentication sample. The main point of interest in this sample over the original sample is how to build an HTTP Authorization header to pass a Bearer JWT token to WCF.

At this time, only a JWT token retrieved from the GetUserToken() endpoint can be used for making a WCF service call to a WCF service utilizing our custom BearerTokenMessageInspector. (Please read Part 2 for more information on the BearerTokenMessageInspector.)

The console application call to GetClientToken results in an AccessToken. At this time there we don’t have code in place in the WCF solution to build a ClaimsPrincipal from the AccessToken generated from GetClientToken. If somebody knows how to do this, please send the code and I’ll update Part 2 of this series to include the code.

For now, the CallWCF() method is what we’ll discuss. I found the code to build an HttpRequest header from this post.

First an HttpRequestProperty is instantiated. Then an Authorization Bearer header is added. Then the WCF Operation context is instantiated and then the Authorization header is added to the OperationScopeContext.

This Authorization header is what’s inspecting in the WCF Bearer Token inspector we created in Part 2 of this series. It’s important that the header starts with the Bearer text, space and then the Jwt token. If not, then the WCF bearer inspector will reject the request.

Once the authorization header is added, then you use the WCF client to call your service endpoints as normal.

Here is the code to build the header:


static
void CallWcf(TokenResponse token)

{


var _httpRequestProperty = new
HttpRequestMessageProperty();

 

_httpRequestProperty.Headers[HttpRequestHeader.Authorization] = string.Format(“Bearer {0}”, token.AccessToken);


//_httpRequestProperty.Headers[HttpRequestHeader.Authorization] = string.Format(“Bearer {0}”, _token.AccessToken);


var _wcfClient = new
Service1Client();

 


var _context = new
OperationContext(_wcfClient.InnerChannel);

 


using (new
OperationContextScope(_context))

{

_context.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = _httpRequestProperty;

 


var _response = _wcfClient.GetData(10);

 


Console.WriteLine(string.Format(“WCF GetData() Call: {0}”, _response));

 

}

}

We like to build client service classes as PCL and add create the Service references in these classes. We then abstract away code such as setting up the Http Header. We also do this because we convert data we receive from services into Models which we can do things such as add validation code, calculated properties, implement IEditable and such.

In closing, most of the heavy lifting was done in WCF covered in Part 2. We hope these samples and posts will help others trying to figure out how to integrate Identity into their applications. Then we also hope they can help build off what we’ve started with the goal of making it easier and easier for developers to implement good solid security into their applications without it taking up so much time.

Please share any comments or send any updates you have that may help others.

Kris Frost

Lead Software Architect

SmartLogix, Inc

 

 

Categories: Identity Server

Identity Server v3 LOB Part 2 Web Api & WCF Configuration

March 5, 2015 2 comments

This is Part 2 of a series of three posts about setting up and configuring Identity Server for a Line of Business application.

Links

Intro Identity Server v3 Walk through for LOB application

Part 1 Hosting Identity Framework With IIS

Part 2 IDSv3 Web Api & WCF Configuration

Part 3 IDS Client Walkthrough

Client Sample Code

Identity Server Code

In Part 2, we’re going to walk through the Web Api & WCF setup. Web Api is simple and straight forward. I’m adding a stub here for it in case we need to add more information down the road.

Web Api

While writing this post, I don’t recall if we added the IdentityWebApis to the Thinktecture.IdentityServer3 solution or the original zip contained it but the configuration is in the Starup.cs file.

In the UseIdentityServerBearerTokenAuthentication() method. Set the Authority to the URL of your Identity Server web app. Required scopes will not need to be changed unless you changed the scope for the IdSvr startup and the client application.

If you want to force authentication, in the WebApiConfig.cs you add the following line of code: config.Filters.Add(new
AuthorizeAttribute());

That’s pretty much it Web Api.

WCF

WCF was built for SOAP and natively for claims authentication, WIF is typically used with SAML tokens. However, WCF is highly configurable and with the help of some online posts we figured out how to create a custom IDispatcherMessageInspector to handle bearer tokens. The WCFJWTServices is the web app inside the Thinktecture.IdentityServer3 solution the sample we’ll use to walk through how to configure WCF to build a ClaimsPrincipal out of a JWT token obtained from IDS v3.

The following NuGet packages are required for the code below to work.

Identity Protocol Extensions for Microsoft .Net Framework 4.5

JSON Web Token Handler for Microsoft .Net Framework 4.5

Json.Net

The BearerTokenMessageInspector class contains the custom code which will allow our WCF services to build a ClaimsPrincipal from a JWT token.

AfterReceiveRequest() method inspects the HttpRequest headers and makes sure there is an AuthorizationHeader passed in. In Part 3 of this series, we will cover how to build an Http Authorization header to pass into WCF.

The Authenticate class is where the JWT is processed.

First to make sure we’re dealing with a JWT token, we check for Bearer at the start of the header. If present we extract the JWT token from the string.

We make a call to CanReadToken() to make sure the token is readable.

Next, we must instantiate a TokenValidationParamters variable. We use a private CreateTokenValidationParameters() method to build these options. The key here is to make sure the audience is valid and we build a X509SecurityToken which be used to Validate the JWT token.

To build the Json Web Key (JWK) dynamically, first we make a call to Identity services /core/.well-known/jwks endpoint because we need the x5c value. We parse the string into a JObject. Then we write code to parse out the x5c value. We use the x5c value to ultimately build an X509SecurityToken. Note, you can use a browser and browse to the URL, get the value and hard code it in a config file or somewhere if you don’t care about doing this dynamically.

Once we have the TokenValidationParameters, then we make a call to ValidateToken(). To do this, we must use the JwtSecurityTokenHandler. In other samples, you define your SecurityTokenHandlers in the web.config. However, what I found is that using JwtSecurityTokenHandler, the call to FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers.ValidateToken() only takes one parameter. To process a JWT token, JwtSecurityTokenHandler requires you pass in the token, validationparameters and then a reference to a SecurityToken which will get built if ValidateToken() is successful.

The call to ValidateToken() if successful will generate a ClaimsPrincipal which will used to Authenticate. Once authenticated, then the Service AuthorizationContext is populated and completes the authentication.

 

Note: Most of the code for the Bearer Token inspector and WCF configuration below came from this post. The code to for CreateTokenValidationParameters is based off code found here.

 

WCF Configuration

Once the WCF code above is completed, we must make changes to the web.config for the WCF service for the new code to work. First, to wire up the BearerTokenMessageInspector, we must add an extensions element to the system.servicemodel element.

<extensions>

<behaviorExtensions>

<add
name=bearerTokenRequired
type=WCFJWTServices.BearerTokenExtensionElement, WCFJWTServices />

</behaviorExtensions>

</extensions>

Next, in the Servicebehavior section, add the newly created extension.

<behaviors>

<serviceBehaviors>

<behavior
name=WcfServiceBehavior>

<!– To avoid disclosing metadata information, set the values below to false before deployment –>

<serviceMetadata
httpGetEnabled=true
httpsGetEnabled=true/>

<!– To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information –>

<serviceDebug
includeExceptionDetailInFaults=false/>

 

<serviceCredentials
useIdentityConfiguration=true />

<serviceAuthorization
principalPermissionMode=Always />

 

<!– Comment this out to update WSDL –>


<bearerTokenRequired />

 

</behavior>

</serviceBehaviors>

</behaviors>

Note, at the writing of this post, I find when we make changes to our services, we must comment out <bearerTokenRequired /> to generate or update the WSDL. When done, uncomment. Otherwise you will get an exception.

Additionally we have to configuration for IdentityModel.

First the following configSections are added:

<configSections>

<section
name=system.identityModel
type=System.IdentityModel.Configuration.SystemIdentityModelSection, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089 />

<section
name=system.identityModel.services
type=System.IdentityModel.Services.Configuration.SystemIdentityModelServicesSection, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089 />

</configSections>

 

The config file I use contains an element for System.IdentityModel.Services in the Compilation/Assemblies section.

The system.IdentityModel section is where define the JwtSecurityTokenHandler. I had issues with the IssuerNameRegistry section that’s commented out in the sample.

<system.identityModel>

<identityConfiguration>

<audienceUris>

<add
value=users />

</audienceUris>

<securityTokenHandlers>

<clear />

<!–<add type=”System.IdentityModel.Tokens.JwtSecurityTokenHandler, System.IdentityModel.Tokens.Jwt, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″ />–>

<add
type=System.IdentityModel.Tokens.JwtSecurityTokenHandler, System.IdentityModel.Tokens.Jwt />

<securityTokenHandlerConfiguration>

<certificateValidation
certificateValidationMode=None />

<!–<issuerNameRegistry type=”System.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, System.IdentityModel”>

<trustedIssuers>

<add thumbprint=”97249e … 158de” name=”contoso.com” />

</trustedIssuers>

</issuerNameRegistry>–>

</securityTokenHandlerConfiguration>

</securityTokenHandlers>

</identityConfiguration>

</system.identityModel>

Conclusion

With the above configuration, any calls made to your WCF services, the BearerTokenMessageInspector code should run for any call. If there are problems, the exception reported back to the client at this point is generic and not helpful most of the time. I’d advise attaching to the IIS process and setting a break point in the AfterReceiveRequest() first then work your way from there.

Again, if you want to test the service endpoint loads in a browser to check for issues or you need to generate a WSDL, you must comment out the <bearerTokenRequired /> from the ServiceBehavior. This disables security so be sure and re-enable it when finished.

 

Categories: Identity Server

Identity Server v3 LOB Part 1 Hosting IDS v3 with IIS

March 4, 2015 Leave a comment

This is Part 1 of a series of three posts about setting up and configuring Identity Server for a Line Of Business application.

Links

Intro Identity Server v3 Walk through for LOB application

Part 1 Hosting Identity Framework With IIS

Part 2 IDSv3 Web Api & WCF Configuration

Part 3 IDS Client Walkthrough

Client Sample Code

Identity Server Code

 

In part one, we are going to do a walkthrough a modified version of the Thinktecture.IdentityServer3 solution which can be found here.

In this post, we’re going to cover:

  1. How to setup a 2048+ bit certificate and then how to make sure your app pool account has permissions.
  2. Hard coding our Client & Scope data. We won’t go into many details as its fairly straight forward for the examples.
  3. We will create a simple LocalClaimsProvider as well as a Local User Service. We won’t tie directly to a database. However, in these classes you will be able to write your own code to use whatever type of repository you like.

The link for Identity Server Code above is the solution we will be working our way through in this post. I’m not going to go into how to create the entire solution from scratch.

2048 Bit Certificate

We work with predominately Microsoft technology. So we will walk through how to install a certificate on a Windows 8 computer running IIS.

  1. Start clicking Start, type in Run and in the Run text box, type in MMC.
  2. Next File, Add Remove Snap-In, Highlight Certificates and click Add

  1. When prompted, make sure to select Computer Account and click next.

  1. Leave Local Computer selected and click Finish.
  2. Expand Certificates/Persona/Certificates and right click on Certificate.
  3. Next, if you are importing a Certificate, choose Import.
  4. If you want to get a Certificate from an Active Directory, select Request New Certificate.

  1. After the certificate shows up in the Certificates folder, right click on it and select Manage Private Keys.
  2. A Permissions window will popup, click Add.
  3. In the Select Users, Computers, Service Accounts or Groups window, if your computer is in a domain, click on Locations and select your computer and click Ok.
  4. Next enter the name of the App Pool being used by the web application hosting the IdSrv web app in the Thinktecture IdentityServer3 solution you downloaded. The format would be IIS AppPool\<Type Identity’s name here>
    1. This assumes you opened the solution in a Visual Studio 2013 instance which you opened up as administrator.
    2. Doing so, a web directory in IIS should have been created. If not, however you go about doing it, make sure a virtual directory is setup in IIS.
    3. Then select or create an AppPool to use.
  5. Click Ok and you should see the Identity of the AppPool. May sure it has at least Read permissions. (May require full control, I’m not 100% sure.)
  6. Now we must open up IIS manager and make sure the web site which contains the Virtual Directory for IdSrv has its Https Binding configured to use the Certificate we just imported/created.

Virtual Directory configuration

In the IDS solution, now you will need to change app.settings to your environment. All app settings for the IdSvr web app are in IdSrv.config.

  1. First you need to configure the IdentityCertCommonName to make the subject name of the certificate we setup in the previous section. (The key for this could have been named better.). You can open the certificate and look at the subject to get the values you need to update here.
  2. If you’re running Identity locally, you can leave the other settings. I would suggest you change the IdentitySiteName to whatever you want your site name to be. This value shows up in the Login page.
  3. EnableIdentityLogging, I would leave set to true while in Dev. Obviously you would want to change this value to false in production.

Client & Scope

I haven’t had that much time to get into client and scope so I’ve just hard coded values in the existing IDS Client and Scope classes. Maybe at a later date a blog post on how to dynamically create these is warranted.

Local User Service

Our custom applications we have our own credential related tables which store user, role and security information. Identity Server Framework allows you to easily build a custom user server. In the sample code, the custom user service can be found in the IdentityServices project.

In the sample we create user bob in the LocalUserService constructor and load it into memory. However, you can do the look up in the AuthenticateLocalAsyn method if you need to authenticate against a repository.

In the Startup.cs configuration method, we instantiate the custom LocalClaimsProvider class. Then we register it with factories UserService.

Local Claims Provider

To pull back our records and build custom claims, we create a custom LocalClaimsProvider class which you can also find in the IdentityServices project. We created a custom GetUserClaims() method. Currently we manually create some claims. However, you could make your database calls here and pull back records to build your custom claims.

Note, we had to add the nameidentifier claim to satisfy @Html.AntiForgeryToken() in MVC websites.

As with the Local User Services, instantiate the custom Claims provider in Startup and add it to the factory ClaimsProvider.

 

 

 

 

 

 

 

 

 

 

 

Categories: Identity Server

Identity Server v3 Intro Commercial LOB Application

February 23, 2015 Leave a comment

Welcome to the introduction of a series of blog post described how to setup up Identity Server to use Claims based Identity for a commercial Line of Business, Microsoft software application.

Before we get started, here are links to all posts and sample code.

Links

Intro Identity Server v3 Walk through for LOB application

Part 1 Hosting Identity Framework With IIS

Part 2 IDSv3 Web Api & WCF Configuration

Part 3 IDS Client Walkthrough

Client Sample Code

Identity Server Code

 

I’m writing these series of blog post for a couple of reasons.

1) As with most products, samples and documentation show “simple” ways of doing things which really aren’t that much help. I’ve wasted 3 to 4 weeks digging around, asking questions etc just to get to where we are today. My goal is that posting these samples it will save other time and they can add to these posts overtime so we all end up with better implementations.

2) Documentation for our internal team. Also, building off 1, my hope is again our team reads and takes what I have and studies it and shares ideas going forward. Along with others out on the internet who use these samples.

The key to the software we build is maintainability and flexibility.

For a typical application, we will have a UI solution and then a service solution. Going forward with our new applications, we want to utilize the built in Claim functionality of .Net so we’re adding a third web application which host the Identity Server v3 framework. Also to have a SSO framework for our applications.

In our blogs we will start with:

Part 1 which will be what it takes to setup and host Identity Server v3 in IIS which can be found here. The following will be covered:

  1. How to setup a 2048+ bit certificate and then how to make sure your app pool account has permissions.
  2. We will hard code our Client & Scope data. We won’t go into many details as its fairly straight forward for the examples.
  3. We will create a simple LocalClaimsProvider as well as a Local User Service. We won’t tie directly to a database. However, in these classes you will be able to write your own code to use whatever type of repository you like.

     

Part 2 will consist of the building services that will utilize tokens from IDSv3. This blog post can be found here.

  1. First we will do a simple walk through how to setup a WebApi service to use a JWT token from IDS v3.
  2. Then we will create a WCF service and add code which will allow WCF to use a JWT bearer token passed from a client obtained from IDSv3.
    1. Note at this time, this sample will only work with a JWT token.

Part 3 will consist of building a simple console application. This blog post can be found here.

  1. The console application will contain a WSDL from our WCF service we build in Part 1.
    1. We will build an HTTP Authorize Header which will contain a JWT which will be used by code we mentioned in Part 2.
  2. The console app will make a call to a WebApi controller method.

 

In summary, we’re going to do a walkthrough of the UI, WebApi & WCF services & hosting Identity Server v3 in IIS. This should give developers who build enterprise LOB applications a good start of integrating Claims & IDS v3 into their applications.

The Identity Server solution that contains Web Api & WCF services can be found https://github.com/kkfrosty/IdentityServer/.

The client console application can be found here.

Categories: Identity Server

Clearing Session Part 2

February 28, 2009 Leave a comment

Web.config  (Relevant portion of the web.config file.  This should get created automatically if you choose to add an ajax enabled WCF to your web site.)

<system.serviceModel>

<

behaviors>

<

endpointBehaviors>

<behavior name="SessionMethodsAspNetAjaxBehavior">

<

enableWebScript/>

<

webHttp></webHttp>

</

behavior>

</

endpointBehaviors>

</

behaviors>

<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>

<

services>

<

service name="SessionMethods">

<endpoint address="" behaviorConfiguration="SessionMethodsAspNetAjaxBehavior" binding="webHttpBinding" contract="SessionMethods"/>

</

service>

</

services>

</

system.serviceModel>

</

configuration>

 

 

Service file (SessionMethods.svc)

<%

@ ServiceHost Language="C#" Debug="true" Service="SessionMethods" CodeBehind="~/App_Code/SessionMethods.cs" %>

Service Code Behind (SessionMethods.cs)

using

System;

using

System.Linq;

using

System.Runtime.Serialization;

using

System.ServiceModel;

using

System.ServiceModel.Activation;

using System.ServiceModel.Web;

using System.Web;

[

ServiceContract(Namespace = "", SessionMode = SessionMode.Allowed)]

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]

public

class SessionMethods

{

// Add [WebGet] attribute to use HTTP GET

[OperationContract()]

public void ClearSession()

{

HttpContext.Current.Session.Clear();

}

}

I have an additional page so the user can go back and forth between the default.aspx page and this OtherPage.aspx and watch what happens to the Session Variable depending on whether the checkbox is checked or not.

<%

@ Page Language="C#" AutoEventWireup="true" CodeFile="OtherPage.aspx.cs" Inherits="OtherPage" %>

<!

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html xmlns="http://www.w3.org/1999/xhtml"&gt;

<

head runat="server">

<title></title>

<script type="text/javascript">

function pageLoad() {

}

</script>

</

head>

<body>

<form id="form1" runat="server">

<div>

<asp:ScriptManager ID="ScriptManager1" runat="server" />

<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/Default.aspx">Back to Default to check Session State</asp:HyperLink>

</div>

</form>

</

body>

</

html>

 

I apologize, but Live doesn’t appear to have an elegant way to post code.  I’m also working on a place to post the full sample code.

 

Categories: Software Development

Clearing Session on window close Part 1

February 28, 2009 Leave a comment
Dealing with an app that needs to store quite a bit of data and Session as been chosen throughout the app.  However, this makes me nervous as the traffic against the application grows.  For the pages I’m writing, I’ve been searching for a way to clear the session variables when a use goes to another page or closes IE.
 
I finally got what I was looking for using ajax WCF service in my application.
 
My default.aspx page is as follows:
 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<

html xmlns="http://www.w3.org/1999/xhtml"&gt;

<

head runat="server">

<title></title>

</

head>

<

body>

<form id="form1" runat="server">

<script type="text/javascript">

function window.onunload() {

var checked = $get(‘<%= CheckBox1.ClientID %>’).checked;

// Use window.event.clientY values to determine when you want to clear session

//alert(window.event.clientY);

if (checked) {

SessionMethods.ClearSession(ClearSuccess, ClearFail);

}

}

// These won’t fire because the window is gone

function ClearSuccess(){

alert(

‘ClearSuccess’);

}

function ClearFail(){

alert(

‘ClearFail’);

}

</script>

<asp:ScriptManager ID="ScriptManager1" runat="server">

<Services>

<asp:ServiceReference Path="~/SessionMethods.svc" />

</Services>

</asp:ScriptManager>

<div>

<asp:UpdatePanel ID="UpdatePanel1" runat="server">

<ContentTemplate>

<div>

<asp:Label ID="Label2" runat="server" Text="Session DateTime:"></asp:Label>

</div>

<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

<div>

<asp:CheckBox ID="CheckBox1" runat="server" Text="Clear Session on window.unload? Checked, Session state is cleared when you leave the page. Unchecked Session is left in tact."></asp:CheckBox>

</div>

<div>

<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />

</div>

</ContentTemplate>

</asp:UpdatePanel>

<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/OtherPage.aspx">HyperLink</asp:HyperLink>

</div>

</form>

</

body>

</

html>

 

The code behind for this page page is.

using

System;

using System.Collections.Generic;

using

System.Linq;

using

System.Web;

using

System.Web.UI;

using System.Web.UI.WebControls;

public

partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

Label1.Text = Session[

"SessionTest"] as string;

}

protected void Button1_Click(object sender, EventArgs e)

{

Session[

"SessionTest"] = DateTime.Now.ToString();

Label1.Text = Session["SessionTest"] as string;

}

}

 

Categories: Software Development