SAML SP for ASP.NET customization - SSO

Network address tolerance

The SAML protocol uses the network address of the user for session tracking and message replay detection.

In many deployments however the network address of the user is not reliable because of Network Address Translation (NAT), HTTP Proxy and other network components. Use the ServiceProvider.Netmask setting in the appSettings section of web.config to adjust how the Service Provider relies on the network address.

Specify an empty value to completely disable network address validation.

Controlling resource access

Use the ASP.NET standard authorization declarations with deny and allow roles to specify access control to the resources of the web application.

In the example below, Listing 1, only authenticated users ("*") can access the resource. Anonymous unauthenticated users ("?") are will be redirected to the Ubisecure Authentication Server for authentication and presented with a login page.

Listing 1. Specifying access control for Authenticated users only
<system.web>
	<authorization>
		<deny users="?"/>
		<allow users="*"/>
	</authorization>
</system.web>

Defining the User Name Attribute

By default, after authentication, the ASP.NET Context.User.Identity.Name variable contains the user principle in Distinguished Name (DN) format. In Ubisecure SSO Server version 5 or newer, this variable may optionally contain Transient or Persistent user IDs.

If the ASP.NET application requires Context.User.Identity.Name data in a different format (eg. Firstname Lastname or samAccountName from Active Directory), this can be achieved by first creating an Authorization Policy containing the desired value in another arbitrary attribute, and then mapping this attribute to Context.User.Identity.Name. Use the ServiceProvider.UsernameAttribute setting in the web.config file to specify the name of the user attribute which value will be returned by the ASP.NET Context.User.Identity.Name variable (see Listing 2).

In the example below (see Listing 2), the variable Context.User.Identity.Name will now contain the value of the attribute username, as specified in the Authorization Policy configured for this agent in Ubisecure Server Management. Figure 1 contains an example Authentication Policy setting, where the username value is set to the email address of the user. The chosen configuration depends on the requirements of the target application. For more information on Authorization Policy usage, please refer to Manage authorization policies - SSO.

Listing 2. Configuring web.config to use attribute data as the ASP.NET username
<appSettings>
	<add key="ServiceProvider.EntityID" value="<Insert entity ID>"/>
	<add key="ServiceProvider.UsernameAttribute" value="username"/>
</appSettings> 


Figure 1. Example Authentication Policy in Ubisecure SSO Management. Here the username attribute is set to the mail attribute of the user's account.


Event handlers

The Service Provider calls registered event listeners to notify the application of certain events during SAML protocol message processing.

Please refer to the API documentation for details about the following event handler interfaces (see API Documentation in SAML SP for ASP.NET application integration - SSO):

EventDescription
AuthnRequestEventThis event is called when the user is attempting to access a resource but has not yet been authenticated. This event allows the application designer to customize certain properties of the AuthnRequest protocol message, such as to pass the user locale to the IDP or to dynamically at runtime request a specific authentication technique.
LoginEventThis event is called when the user has authenticated at the IDP and returned with a valid response
LoginErrorEventThis event is called when the user has cancelled the login at the IDP or another error has occurred during login
LogoutEventThis event is called when logout has been requested.


Listing 3. Sample LoginEvent handler declared in global.asax
<%@ Application Language="C#" %>
<%@ Import Namespace="Ubisecure.SAML2.ServiceProvider.Event" %>
<script runat="server">
void ServiceProviderAuthentication_Login(object o, LoginEventArgs e) 
{
	// Handler for the Login Event 
}
</script>

The following example, Listing 4, will redirect the user to the specified page, for example if the cancel button is pressed during the login process.

Listing 4. Sample LoginErrorEvent handler declared in global.asax
<%@Application Language="C#"%>
<%@ Import Namespace="Ubisecure.SAML2.ServiceProvider.Event" %>
<script runat="server">
protected void ServiceProviderAuthentication_LoginError(object sender, LoginErrorEventArgs e) {
	HttpContext.Current.Response.Redirect("~/loginerror.aspx", true);
}
</script>

User attributes as specified in the Authorization Policy, are accessible from the Login event. Listing 5 is very basic example of how to access user attributes within the global.asax file.

Listing 5. Sample LoginEvent handler declared in global.asax
<%@ Application Language="C#" %>
<%@ Import Namespace="Ubisecure.SAML2.ServiceProvider.Event" %>
<%@ Import Namespace="Ubisecure.SAML2.ServiceProvider.Security" %>
<script runat="server">
void ServiceProviderAuthentication_Login(object o, LoginEventArgs e) 
{
	// Handler for the Login Event 
	Response.Write("<p>Your name is " + e.Assertion.GetFirstAttributeValue("name"));
	Response.Write("<p>Your phone number is " + 
		e.Assertion.GetFirstAttributeValue("TelephoneNumber"));
	Response.End();
}
</script>

For complete technical descriptions of the API interface, please refer to the API Documentation (see API Documentation in SAML SP for ASP.NET application integration - SSO).

Membership and Role Providers

ASP.NET provides a role-based security model. SAML SP for ASP.NET can optionally be configured to provide role information according to this interface (MembershipProvider and RoleProvider). The ServiceProviderMembershipProvider and ServiceProviderRoleProvider are implementations of ASP.NET MembershipProvider and RoleProvider.

For more information on the use of roles in applications, please refer to Microsoft ASP.NET documentation.

Roles defined in an Authorization Policy in Ubilogin Management will be mapped to ASP.NET roles.

Figure 2. Example Authorization Policy, Roles tab


Figure 3. Example Authorization Policy, Attributes tab - Roles are visible as a multi-value SAML attribute called role

Please note that the current implementation covers only the minimum feature set required for Microsoft SharePoint integration. Any features of MembershipProvider or RoleProvider that are not supported or not implemented will raise NotImplementedException or NotSupportedException errors. For example, ServiceProviderRoleProvider.CreateRole is not supported.

To use Membership and Role Providers, the configuration in Listing 6 must be added to the web.config file within the <system.web> section.

Listing 6. Membership and Role Provider configuration in web.config
<system.web>

<!—truncated incomplete sample -->

	<membership defaultProvider="UbiloginUsers">
		<providers>
			<clear/>
			<add name="UbiloginUsers"
				type="Ubisecure.SAML2.ServiceProvider.Security.ServiceProviderMembershipProvider,
					Ubisecure.SAML2.ServiceProvider, Version=1.13.0.0, Culture=neutral,
					PublicKeyToken=e76714ff33c956b5"/>
		</providers>
	</membership>

	<roleManager defaultProvider="UbiloginRoles" enabled="true">
		<providers>
			<clear/>
			<add name="UbiloginRoles"
				type="Ubisecure.SAML2.ServiceProvider.Security.ServiceProviderRoleProvider,
					Ubisecure.SAML2.ServiceProvider, Version=1.31.0.0, Culture=neutral,
					PublicKeyToken=e76714ff33c956b5"/>
		</providers>
	</roleManager>

<!-- truncated incomplete sample -->

</system.web>

Specifying a default role for all Authenticated users

Use the ServiceProvider.Role setting to specify the name of a ASP.NET role that is automatically associated with all users authenticated by the Service Provider. In the following example, Listing 7, all users will be assigned to a role called "UbiloginAuthenticatedUsers". This role name is arbitrary and does not need to be defined in the Authorization Policy. This role is additional to any roles received in the SAML request. This value is optional.

Listing 7. Assigning all Authenticated Users to a default ASP.NET role
<appSettings>
	<add key="ServiceProvider.EntityID" value="<Insert entity ID>"/>
	<add key="ServiceProvider.Role" value="UbiloginAuthenticatedUsers"/>
</appSettings>

Access control using roles

A typical use for roles is to establish rules that allow or deny access to pages or folders. These access rules are defined in the <authorization> section of the Web.config file. The following example, Listing 8, allows users in the role of ADMIN to view pages in the folder named FolderNameToBeProtected and denies access to anyone else. Multiple roles can also be specified, e.g., <allow roles="RoleA,RoleB" />.

Listing 8. Controlling access to pages and folders using roles via web.config file
<configuration>
	<location path="FolderNameToBeProtected">
		<system.web>
			<authorization>
				<allow roles="ADMIN" />
				<deny users="*" />
			</authorization>
		</system.web>
	</location>
	<!-- other configuration settings here -->
<configuration>

Use the role function of Authorization Policy settings in the Ubisecure Management application to associate roles with user groups. The roles specified in Ubisecure Management are automatically mapped into ASP.NET roles. In the following example, Listing 9, unauthenticated users and users with a role of VIEWLOG are forbidden access. Other authenticated users are permitted.

Listing 9. Allow or deny access based on roles
<system.web>
	<authorization>
		<deny users="?"/>
		<deny roles="VIEWLOG"/>
		<allow roles="UbiloginAuthenticatedUsers"/>
	</authorization>
</system.web>

Determining role membership in ASP.NET

Use the Roles.IsUserInRole() function to test for role membership. See Listing 10.

Listing 10. Checking Role Membership in C# using Roles.IsUserInRole()
using System.Web.Security;

if (Roles.IsUserInRole("ADMIN"))
{
	Label1.Text = User.Identity.Name + " is in admin role.";
}
else
{
	Label1.Text = User.Identity.Name + " is NOT in admin role";
} 

Listing all user roles in ASP.NET

Use the Roles.GetRolesForUser() function to list user roles. See Listing 11.

Listing 11. Accessing list of roles in C# using Roles.GetRolesForUser()
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<script runat="server">

    protected void Page_Load(object sender, EventArgs e)
    {
        string[] members = Roles.GetRolesForUser();
        foreach (string role in members)
        {
            Label1.Text += role + "<br />";
        }        
    } </script>

<html>
<head runat="server">
    <title>Role List</title>
</head>
<body>
    <p>The current user name is <%= HttpUtility.HtmlEncode(Context.User.Identity.Name) %> 
    <p>The User has the following roles:</p>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" />
    </div>
    </form>
</body>
</html>

Requesting a specific authentication method in ASP.NET

Use the RequestedAuthnContext.AuthnContextDeclRef function to request a specific method by method ID. For example, if the calling application knows what the authentication method that the user needs to use, this selection can be made before redirect to the Ubisecure Server. See Listing 11.

Listing 11. Requesting a specific authentication method in ASP.Net
protected void ServiceProviderAuthentication_AuthnRequest(object sender, AuthnRequestEventArgs e)

{
 
	e.ForceAuthn = true;
	e.RequestedAuthnContext.AuthnContextDeclRef.Add(e.IdentityProviderEntityID
+ "/saml2/names/ac/" + INSERT_METHOD_ID_HERE );
	e.Locale = "fi";

}