Custom

Sample SSO using a .NET custom HTTP module

The advantage of the custom HTTP module solution is that it secures all WorkflowGen HTTP requests, including web services. It also provides more customization possibilities than the form authentication-based solution.
This section focuses on the custom HTTP module authentication solution.
This sample illustrates a very basic scenario that uses a separate IIS website as the remote authentication service provider to host a login.aspx page (e.g. to simulate an authentication service provider that validates user credentials against an identity provider) and WorkflowGen in another IIS website where the custom HTTP module is installed and configured.
We recommend securing the WorkflowGen website with SSL and using encryption to secure the token. The code provided below is a basic sample, so you might have to customize it to enforce security and hide detailed error messages.

WorkflowGen custom HTTP module authentication configuration

  1. 1.
    Download the CustomAuthModuleSSO 2.0 sample package, unzip the package, then copy the \VS Project\bin\Release\CustomAuthModuleSSO.dll file into the following folders:
    • \wfgen\bin
    • \wfgen\wfapps\webforms\bin
    • All of your custom web forms' \bin folders
  2. 2.
    In IIS, change the Authentication configuration. Enable Anonymous Authentication on all of the following IIS applications under the WorkflowGen website:
    • \wfgen
    • \wfgen\wfapps\webforms
    • All of your custom web form folders
    ✏️ Note: All of your web service apps (subfolders in the \wfgen\wfapps\webservices folder) should be using Basic authentication, since this sample redirects to the remote authentication server's login.aspx page, which is not supported in the web service scenario.
  3. 3.
    Edit your \wfgen\web.config file and add the following configuration:
    1
    <configuration>
    2
    3
    <appSettings>
    4
    <add key="RemoteAuthenticationServiceProviderLoginUrl" value="http://{remoteauthserver:port}/login.aspx" />
    5
    </appSettings>
    6
    7
    <system.webServer>
    8
    <modules>
    9
    <add name="ApplicationSecurityAuthenticationModule" type="WorkflowGen.Samples.CustomAuthModule" />
    10
    </modules>
    11
    </system.webServer>
    12
    13
    </configuration>
    Copied!
    ✏️ Note: Change the {remoteauthserver:port} value of the RemoteAuthenticationServiceProviderLoginUrl key to your existing remote authentication server name and port number.
  4. 4.
    If you want to customize the behavior of CustomAuthModuleSSO, open the \VS Project\CustomAuthModuleSSO.sln solution in Visual Studio, then edit the CustomAuthModuleSSO.cs file. When ready, rebuild the solution and redeploy the \VS Project\bin\Release\CustomAuthModuleSSO.dll file as in step 1.

Remote Authentication Service Provider web server configuration

  1. 1.
    Copy the \Remote auth service provider\login.aspx sample file from the package to your remote authentication server IIS website's root folder. If there's no existing website, then create a new IIS website on your web server and copy the file to the root folder. Normally, the remote authentication server IIS website is a separate website from the WorkflowGen IIS website. ✏️ Note: Don't forget to update the {remoteauthserver:port} value for the RemoteAuthenticationServiceProviderLoginUrl key in the \wfgen\web.config file if the remote authentication server name and port are different or have changed. See step 3 of the previous section.
  2. 2.
    Edit login.aspx and change the {workflowgenserver:port} to your WorkflowGen server name and port number.
  3. 3.
    In IIS, change the Authentication configuration. Enable Anonymous Authentication on the remote authentication server IIS website.
  4. 4.
    Open the http://{remoteauthserver:port}/login.aspx URL in a browser and make sure it's accessible and working properly.

How the sample works

  1. 1.
    When a user connects to WorkflowGen (http://{workflowgenserver:port}/wfgen), CustomAuthModuleSSO checks if a token is available (in the Cookies, QueryString, Form, or Server variables collections) in order to retrieve the current login user. If no token is found, then it will redirect the user to your remote authentication server login.aspx page with a return URL.
    1
    http://{remoteauthserver:port}/login.aspx?return_url=http%3A%2F%2F%7Bworkflowgenserver%3Aport%7D%2Fwfgen
    Copied!
  2. 2.
    Your remote authentication server will show a login page for the user to input their username and password for submission.
  3. 3.
    When the user submits the form, the login page validates the user credentials against the authentication service provider (code to implement in login.aspx). If the credentials are valid, then the page generates a token and sets it as a parameter in the WorkflowGen return URL. For the simplicity of this sample, the token only contains the username that is encoded in base64.
    1
    http://{workflowgenserver:port}/wfgen?token=dXNlcm5hbWU%3D
    Copied!
  4. 4.
    When WorkflowGen receives the new HTTP request from your remote authentication server, CustomAuthModuleSSO will retrieve the token from the QueryString. It decodes the token to retrieve the username and creates a GenericPrincipal object used to set the current user session, then it saves the token as a cookie for future HTTP requests. WorkflowGen will now use the user principal (GenericPrincipal object) of the HTTP request context to verify and load the WorkflowGen user's profile. If the user is invalid (e.g. no matching username is found in the database), WorkflowGen will reject the user and display a Security error: You are not authorized to view this page error message.
  5. 5.
    For sign out, the user can use one of the following URLs. WorkflowGen will clear the token cookie, which will force the user to log in if they want to access WorkflowGen again.
    1
    http://{workflowgenserver:port}/wfgen/logout
    2
    3
    http://{workflowgenserver:port}/wfgen?logout=true
    4
    5
    http://{workflowgenserver:port}/wfgen?logout=y
    Copied!
For a more secure token, the remote authentication server (login.aspx in this sample) can generate a JSON Web Token containing the user information and sign it using a shared secret key. WorkflowGen must know the shared secret key in order to verify and retrieve the user information from the JWT. There are many JWT signing and verification libraries available on jwt.io.

CustomAuthModuleSSO.cs source code

1
//*********************************************************************
2
// Sample code for an HTTP Authentication module
3
//*********************************************************************
4
5
using System;
6
using System.Web;
7
using System.Security.Principal;
8
using System.Text;
9
using System.Configuration;
10
11
namespace WorkflowGen.Samples
12
{
13
/// <summary>
14
/// Summary description for CustomAuthModule
15
/// </summary>
16
// ReSharper disable once UnusedMember.Global
17
public class CustomAuthModule : IHttpModule
18
{
19
private static readonly string RemoteAuthenticationServiceProviderLoginUrl =
20
ConfigurationManager.AppSettings["RemoteAuthenticationServiceProviderLoginUrl"];
21
private const string TokenName = "token";
22
private const bool OnAuthenticationErrorRedirect = true;
23
24
/// <summary>
25
/// Release any resources
26
/// </summary>
27
public void Dispose()
28
{
29
}
30
31
/// <summary>
32
/// Initialization of module
33
/// </summary>
34
public void Init(HttpApplication application)
35
{
36
application.AuthenticateRequest += Application_AuthenticateRequest;
37
}
38
39
/// <summary>
40
/// Delegate for authenticating a request
41
/// </summary>
42
/// <param name="sender"></param>
43
/// <param name="e"></param>
44
private void Application_AuthenticateRequest(object sender, EventArgs e)
45
{
46
var application = sender as HttpApplication;
47
48
Authenticate(application);
49
}
50
51
/// <summary>
52
/// Authenticate a user
53
/// </summary>
54
/// <param name="application"></param>
55
private void Authenticate(HttpApplication application)
56
{
57
var request = application.Context.Request;
58
var response = application.Context.Response;
59
var server = application.Context.Server;
60
61
// if sign out request from the remote authentication service provider
62
if (request.RawUrl.EndsWith("/logout") || request["logout"] != null &&
63
(request["logout"].ToLower() == "true" || request["logout"].ToLower() == "y"))
64
{
65
// Clear the token cookie when user logout
66
var tokenCookie = new HttpCookie(TokenName) {Expires = DateTime.UtcNow.AddDays(-1d)};
67
application.Response.Cookies.Add(tokenCookie);
68
69
response.Redirect(RemoteAuthenticationServiceProviderLoginUrl);
70
}
71
72
string token = null;
73
74
// Retrieve the authentication token from a QueryString parameter
75
if (request[TokenName] != null)
76
{
77
token = request[TokenName];
78
}
79
80
string returnUrl = server.UrlEncode(request.Url.Query == string.Empty
81
? request.Url.AbsoluteUri
82
: request.Url.AbsoluteUri.Replace(request.Url.Query, string.Empty));
83
84
// If the token is empty
85
if (string.IsNullOrEmpty(token))
86
{
87
// Redirect to back to the Remote Authentication Service Provider login page
88
response.Redirect(RemoteAuthenticationServiceProviderLoginUrl + "?return_url=" + returnUrl);
89
90
return;
91
}
92
93
string username = null;
94
95
try
96
{
97
username = Base64Decode(token);
98
}
99
catch (Exception e)
100
{
101
if (OnAuthenticationErrorRedirect)
102
{
103
// Redirect to back to the Remote Authentication Service Provider login page
104
response.Redirect(RemoteAuthenticationServiceProviderLoginUrl + "?return_url=" + returnUrl);
105
return;
106
}
107
else
108
{
109
throw new Exception(quot;Unable to decode the token: {e.Message}");
110
}
111
}
112
113
try
114
{
115
// Create and set this user for the session
116
application.Context.User =
117
new GenericPrincipal(new GenericIdentity(username, "Basic"), new[] {"user"});
118
119
// Store the token in cookie for the current user session if not exists
120
if (request.Cookies[TokenName] == null)
121
{
122
var tokenCookie = new HttpCookie(TokenName, Base64Encode(username))
123
{
124
Expires = DateTime.UtcNow.AddMinutes(20)
125
};
126
127
application.Response.Cookies.Add(tokenCookie);
128
}
129
}
130
catch (Exception e)
131
{
132
if (OnAuthenticationErrorRedirect)
133
{
134
// Redirect to back to the Remote Authentication Service Provider login page
135
response.Redirect(RemoteAuthenticationServiceProviderLoginUrl + "?return_url=" + returnUrl);
136
}
137
else
138
{
139
throw new Exception(quot;WorkflowGen authentication error: {e.Message}");
140
}
141
}
142
}
143
144
private static string Base64Encode(string message)
145
{
146
return Convert.ToBase64String(Encoding.UTF8.GetBytes(message));
147
}
148
149
private static string Base64Decode(string message)
150
{
151
return Encoding.UTF8.GetString(Convert.FromBase64String(message));
152
}
153
}
154
}
Copied!

login.aspx source code

1
<%@ Import Namespace="System.Web.Security" %>
2
<html>
3
<head>
4
<title>Remote Authentication Service Provider</title>
5
<script runat="server" language="C#">
6
void btnSubmit_Click(Object Source, EventArgs e)
7
{
8
// Perform custom username and password validation here.
9
// ...
10
11
// If all OK then redirect back to WorkflowGen with the token in QueryString of the URL.
12
// For simplicity, the token contains the username encoded in base64.
13
Response.Redirect((!string.IsNullOrEmpty(Request["return_url"]) ? Request["return_url"] : "http://{workflowgenserver:port}/wfgen") +
14
"?token=" + HttpContext.Current.Server.UrlEncode(Base64Encode(txtUsername.Text)));
15
}
16
17
string Base64Encode(string message)
18
{
19
return Convert.ToBase64String(Encoding.UTF8.GetBytes(message));
20
}
21
</script>
22
</head>
23
24
<body
25
class="AuthenticationPage"
26
onload="document.getElementById('txtUsername').focus();"
27
>
28
<div class="Div">
29
<form method="Post" runat="server">
30
<fieldset class="FieldSet">
31
<legend class="Legend">Remote Authentication Service Provider</legend>
32
<table class="Table" cellpadding="0" cellspacing="0">
33
<tr class="Row">
34
<td class="CellCaption">
35
<span class="Username">Username:</span>
36
</td>
37
<td class="CellValue">
38
<asp:TextBox
39
CssClass="InputUsername"
40
ID="txtUsername"
41
runat="server"
42
/>
43
</td>
44
</tr>
45
<tr class="Row">
46
<td class="CellCaption">
47
<span class="Password">Password:</span>
48
</td>
49
<td class="CellValue">
50
<asp:TextBox
51
CssClass="InputUsername"
52
ID="txtPassword"
53
runat="server"
54
/>
55
</td>
56
</tr>
57
</table>
58
<table class="Footer" cellpadding="0" cellspacing="0">
59
<tr class="Row">
60
<td class="Cell">
61
<asp:Button
62
CssClass="Button"
63
ID="btnSubmit"
64
Text="Submit"
65
OnClick="btnSubmit_Click"
66
runat="server"
67
/>
68
</td>
69
</tr>
70
</table>
71
</fieldset>
72
</form>
73
</div>
74
</body>
75
</html>
Copied!

Generic sample code for an HTTP module

Overview

This sample is an HTTP module that uses the HTTP_AUTHORIZATION server variable for authentication. You must insert your own method to authenticate users.
This sample uses the common Basic authentication method to request and retrieve the user credentials. It can be easily modified to use any other standard or custom methods, such as a token or a username stored in a cookie, a query string parameter, a form data parameter, or a server variable. The main objective of this custom HTTP module is to create and set the GenericPrincipal object with a valid login username (in clear text) of the current HTTP request context that will be later used by WorkflowGen to verify and load the user's profile.

Source code

1
//*************************************************************************
2
// Copyright © 2021
3
//
4
// Purpose: Generic sample code for an HTTP module using HTTP_AUTHORIZATION
5
//
6
//*************************************************************************
7
8
using System;
9
using System.Web;
10
using System.Security.Principal;
11
using System.Text;
12
using System.Diagnostics;
13
14
namespace MyCompany.Hosting.Samples
15
{
16
/// <summary>
17
/// Summary description for CustomAuthModule
18
/// </summary>
19
public class CustomAuthModule : IHttpModule
20
{
21
/// <summary>
22
/// Constructor
23
/// </summary>
24
public CustomAuthModule()
25
{
26
}
27
28
/// <summary>
29
/// Release any resources
30
/// </summary>
31
public void Dispose()
32
{
33
}
34
35
/// <summary>
36
/// Initialization of module
37
/// </summary>
38
/// <param name="context"></param>
39
public void Init(HttpApplication application)
40
{
41
application.AuthenticateRequest += new EventHandler(application_AuthenticateRequest);
42
}
43
44
/// <summary>
45
/// Delegate for authenticating a request
46
/// </summary>
47
/// <param name="sender"></param>
48
/// <param name="e"></param>
49
void application_AuthenticateRequest(object sender, EventArgs e)
50
{
51
HttpApplication application = sender as HttpApplication;
52
53
Debug.Assert(application != null);
54
55
// Has the client sent Authorization information
56
if (application.Context.Request.ServerVariables["HTTP_AUTHORIZATION"] == null)
57
{
58
// Redirects client to send HTTP Basic credentials
59
application.Response.StatusCode = 401;
60
application.Response.AddHeader("WWW-Authenticate", "Basic");
61
application.Response.End();
62
}
63
else
64
{
65
// Retrieve authentication string
66
string authString = application.Request.ServerVariables["HTTP_AUTHORIZATION"];
67
68
// If the authentication method is basic
69
if (authString.StartsWith("basic", StringComparison.InvariantCultureIgnoreCase))
70
{
71
string[] credentials;
72
bool isValidUser = false;
73
74
// Decode credentials
75
credentials = Base64Decode(authString.Substring(6)).Split(':');
76
77
// Credentials should have two cells
78
// credentials[0] is the username
79
// credentials[1] is the password
80
Debug.Assert(credentials.Length == 2);
81
82
// ****************************
83
// Perform your check here
84
// ****************************
85
// isValidUser = YourAuthenticationMethod(credentials[0], credentials[1]);
86
87
if (isValidUser)
88
{
89
// Create a user
90
GenericPrincipal user =
91
new GenericPrincipal(
92
new GenericIdentity(credentials[0], authString),
93
new string[] { "role_name" });
94
95
// Set this user for the session
96
application.Context.User = user;
97
}
98
}
99
}
100
}
101
102
private static string Base64Decode(string message)
103
{
104
return Encoding.UTF8.GetString(Convert.FromBase64String(message));
105
}
106
}
107
}
Copied!
Last modified 6mo ago