Single Sign-On in ASP.NET


Introduction: Single Sign-On(SSO) is the concept where user can access multiple application with a single time log in.

Description: Here I have explained the SSO with some examples.

If we have multiple applications on same domain e;g

etc.

These all are different application configured on same domain (mycompany.com) having different login functionalities but same user table(registered users). So here the SSO will provide you the facility to access the features of different application after logging into one system.

HOW to achieve this?

It’s very simple when we enter into the cookie world. SSO can be achieved with the help of cookies.

Step I: Use form authentication and your <authentication> tab on web.config should be like below

<authentication mode=”Forms”>

<forms loginUrl=”CMSPages/logon.aspx” defaultUrl=”Default.aspx” name=”.ASPXFORMSAUTH” timeout=”60″ slidingExpiration=”true”/>

</authentication>

name: cookie name which is going to be used across the application. timeout: can be set according to your requirement.

Step II: The machine key should be same on all the applications. See the sample <machinekey> tag below

<machineKey validationKey=”6F91D67AF10322DDB2D42B29DE57C7064BD2D96C3F859D67C0D2B45F0A590E0D03912FF8DF 9C43CA76E41EA432A1C219AAD7B7F0ADB81B10C0BE05F538FA9A4A” decryptionKey=”2348D574C1421373A8C3F0D3A9118C15754E08A73EF2BB9A” validation=”SHA1″ />

For generating the machine key I have listed some sample sites and screen shots below

http://aspnetresources.com/tools/keycreator.aspx

http://www.codeproject.com/KB/aspnet/machineKey.aspx

http://www.developmentnow.com/articles/machinekey_generator.aspx

Please follow the below link to know more about machine Key

http://msdn.microsoft.com/en-us/library/w8h3skw9.aspx

Step III: Issue cookie after log-in from the main application. You can use the below code to achieve this

//creating cookie for user name which is common for both applications. //this cookie is required for Single Sign On functionality

FormsAuthenticationTicket fat = new FormsAuthenticationTicket(1, Username,DateTime.Now, DateTime.Now.AddHours(1), true, “”);

HttpCookie cookie = new HttpCookie(“.ASPXFORMSAUTH”); cookie.Value = FormsAuthentication.Encrypt(fat); cookie.Expires = fat.Expiration; HttpContext.Current.Response.Cookies.Add(cookie);

Here I have issued a cookie named .ASPXFORMSAUTH. If you can remember this cookie is common on all the applications configured on web.config.

Now this cookie is shared among the applications through this process. If we want to have some other cookie like I need to show Full name on top which should be same across the application after logging in.

In this case we should create cookie like below

//creating cookie for user full name

//This is required to display same name on the //welcome note on top

HttpCookie fullNameCookie = new HttpCookie(“fullname”); fullNameCookie.Value = UserFullName; fullNameCookie.Expires = cookie.Expires; HttpContext.Current.Response.Cookies.Add(fullNameCookie);

After issuing the cookie you can access the cookie as below

HttpCookie userFullnameCookie = HttpContext.Current.Request.Cookies[“fullname”]; userNameLabel.Text = userFullnameCookie.Value;

You can think of adding one more cookie(fullname) into the cookie we issued (.ASPXFORMSAUTH). But answer is no. Normally I could achieve this with normal cookie not with the Encrypted one.

Hello….. this is not going to work in all situations? :))

What is the issue?

Here issue with the domain name and www. When you have logged in and the URL is mycompany.com then it won’t retain the cookie for www. mycompany.com.

So in order to fix this issue we need to add domain to the cookie like below

//creating cookie for user name which is common for both applications. //this cookie is required for Single Sign On functionality

FormsAuthenticationTicket fat = new FormsAuthenticationTicket(1, Username,DateTime.Now, DateTime.Now.AddHours(1), true, “”);

HttpCookie cookie = new HttpCookie(“.ASPXFORMSAUTH”); cookie.Value = FormsAuthentication.Encrypt(fat);

cookie.Domain = “.mycompany.com”;

cookie.Expires = fat.Expiration; HttpContext.Current.Response.Cookies.Add(cookie);

it should be .domain name.

Now it looks complete. Great Job!!!!!!!!!!!!

It will work for the below domains

  • mycompany.com
  • subdomain.mycompany.com

Thank You for reading this article.

With Personal Regards

Swagat

Embed YouTube Video into WebPage using ASP.NET


Hello Developers,

Here is the code for Embedding YouTube video into ASP.NET site.

Embed is a term used to describe an object that is independent and does not need an external program or device to run it. For instance, in Web page design, one can link to or insert a video image or sound file into the page so that it is hyperlinked and clickable. When click on, the video image or sound file is played as the operation system usually contains a built-in multimedia application to play it.

/// YouTube video player  script generator

public static string GenerateScript(string videoId, int autoPlay, int width, int height){

StringBuilder sb = new StringBuilder();

sb.Append(@”<embed src=’http://www.youtube.com/v/“);

sb.Append(videoId);

sb.Append(“&autoplay=”);

// set autoplay options

sb.Append(autoPlay.ToString());

sb.Append(“‘ “);

sb.Append(“type=’application/x-shockwave-flash’ “);

sb.Append(“allowscriptaccess=’never’ enableJavascript =’false’ “);

sb.Append(“allowfullscreen=’true’ “);

// set width

sb.Append(“width='” + width.ToString() + “‘ “);

// set height

sb.Append(“height='” + height.ToString() + “‘ “);

sb.Append(@”></embed>”);

string embedScript = sb.ToString();

return embedScript; }

This function returns the string as below

<embed src=’http://www.youtube.com/v/XP9tzWtLFus&autoplay=0

type=’application/x-shockwave-flash’

allowscriptaccess=’never’ enableJavascript =’false’

allowfullscreen=’true’ width=’640′ height=’480′ ></embed>

Below are few samples on this:

Thanks for Reading this article.

With personal regards

Swagat

How to load Google Map dynamically with custom marker link, map center, zoom level and size


Abstract:

This document specifies the way of generating Google map dynamically with custom marker link, map center, zoom level and map size.

Table of Content:

1.  Generate Google Map

2.  Customize the marker link, map center, Zoom level and size

3.  Google Map API reference/Key

1. Generate Google Map: Please see the codes below for achieving this.

Default.aspx(Design Page)

<html xmlns=”http://www.w3.org/1999/xhtml”>

<head id=”Head1″ runat=”server”>

<title>Your Data on Google Map </title>

<%–Google API reference/key–%>

<script src=”http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false

&amp;key=abcdefg” type=”text/javascript”>

</script>

</head>

<body onload=”initialize()” onunload=”GUnload()”>

<form id=”form1″ runat=”server”>

<%–Place holder to fill with javascript by server side code–%>

<asp:Literal ID=”js” runat=”server”></asp:Literal>

<%–Place for google to show your MAP–%>

<div id=”map_canvas” style=”width: 100%; height: 728px; margin-bottom: 2px;”>

</div>

</form>

</body>

</html>

Default.aspx.cs(Code Behind)

private void BuildScript(DataTable tbl)

{

String Locations = “”;

foreach (DataRow r in tbl.Rows)

{

// bypass empty rows

if (r[“Latitude”].ToString().Trim().Length == 0)

continue;

string Latitude = r[“Latitude”].ToString();

string Longitude = r[“Longitude”].ToString();

// create a line of JavaScript for marker on map for this record

Locations += Environment.NewLine + ” map.addOverlay(new GMarker(new GLatLng(” + Latitude + “,” + Longitude + “)));”;

}

// construct the final script

js.Text = @”<script type=’text/javascript’>

function initialize() {

if (GBrowserIsCompatible()) {

var map = new GMap2(document.getElementById(‘map_canvas’));

map.setCenter(new GLatLng(45.05,7.6667), 2); ” + Locations + @”

map.setUIToDefault();

}

}

</script> “;

}

If you want to invoke the body onload and onunload functions, then you need to include the attributes at proper event as below.

body.Attributes.Add(“onload”, “javascript:initialize()”);

body.Attributes.Add(“onunload”, “javascript:GUnload()”);

Now your Map should look like this

2. Customize the marker link, map center, zoom level and size: Please see the codes below for achieving this.

Design:

<td style=”width: 282px; height: 278px;” align=”center” valign=”top”>

<%–Place holder to fill with javascript by server side code–%>

<asp:Literal ID=”js” runat=”server”>

</asp:Literal>

<%–Place for google to show your MAP–%>

<div id=”map_canvas” style=”width: 290px; height: 500px; margin-bottom: 2px;”>

</div>

</td>

Here you can set the size.

Code Behind:

//here I have used the master page body to render in specific page, you can use directly  the particular body ID

HtmlGenericControl body = (HtmlGenericControl)Master.FindControl(“mainBody”);

body.Attributes.Add(“onload”, “javascript:initialize()”); body.Attributes.Add(“onunload”, “javascript:GUnload()”); String Locations = “”;

string latitude = string.Empty;

string longitude = string.Empty;

string mapCenterLatitude = string.Empty; string mapCenterLongitude = string.Empty; foreach (var result in carResults)

{

latitude = Convert.ToString(result.gpsData.latitude);

longitude = Convert.ToString(result.gpsData.longitude);

if (result.gpsData.latitude != 0 && result.gpsData.longitude != 0)

{

mapCenterLatitude = latitude;

mapCenterLongitude = longitude;

}

//prepare point

string point = @”var point = new GLatLng(

” + latitude + @” ,

” + longitude + “);”;

//prepare marker with custom link and HTML

string marker = @”var marker = createMarker(point,'<div>Car Name: ” + result.Name +

@”<br/><a href=””search-car-details.aspx?locale=”+Request.QueryString[“locale”]+”&zip=” + result.zip

+ @” “”>Click here to get the details</a><div>’)”;

//add to overlay(map)

string addOverlay = “map.addOverlay(marker);”;

//prepare complete script for all locations

Locations += Environment.NewLine + point + Environment.NewLine + marker + Environment.NewLine + addOverlay;

}

// construct the final script

js.Text = @” <script type=’text/javascript’>

function initialize()

{

function createMarker(point,html)

{

var marker = new GMarker(point); GEvent.addListener(marker, “”click””, function() {

marker.openInfoWindowHtml(html);

});

return marker;

}

var map = new GMap2(document.getElementById(“”map_canvas””));

map.addControl(new GLargeMapControl());

map.setCenter(new GLatLng( ” + mapCenterLatitude + @”,

” + mapCenterLongitude + @”),12); // set zoom level

” + Locations + @” map.setUIToDefault();}

</script> “;

Now your Map should look like below screen shots


3. Google Map API Key: Please see the codes below for achieving this.

For generating API key please visit http://code.google.com/apis/base/signup.html


For more details please find the link below

http://code.google.com/apis/maps/documentation/javascript/basics.html

Note: This API V3 version of the Google Maps JavaScript API no longer needs API keys!.

Thanks for reading this article.

Enjoy


With personal regards

Swagat Parida