I'm looking for guidance on integrating Azure AD authentication into a legacy ASP.NET webforms project built for .NET Framework 4 (specifically, .ASPX
pages). Despite extensive research, I haven't come across any relevant documentation or examples, as most resources seem to focus on newer technologies like ASP.NET MVC and SPAs.
I've successfully registered an application in Azure AD, but I'm struggling with the implementation of the authentication flow. Can someone provide step-by-step instructions or point me to documentation that covers this specific scenario?
My files looks like this:
The following code is sample code from Login.aspx.cs
:
protected void SignIn_Click(object sender, EventArgs e)
{
try
{
string username = txtUsername.Text;
string password = txtPassword.Text;
string btnText = btnSignIn.Text;
// Encrypt the password
string EncPass = EncryptPassword(password);
if ("Recover".Equals(btnText))
{
password = "blank";
}
if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
{
// Retrieve user data
System.Data.DataTable user = GetUserByUsername(username);
if (user.Rows.Count > 0)
{
if ("Recover".Equals(btnText))
{
// Generate a new password
string newPassword = GenerateNewPassword();
string saltValueN = GetSaltValue(newPassword);
string encPassN = EncryptPassword(newPassword);
// Reset the user's password
int userId = ResetUserPassword(username, encPassN);
if (userId > 0)
{
// Send the new password via email
bool sent = SendEmail(username, newPassword);
if (sent)
{
// Session cleanup and notification
Session.RemoveAll();
Session.Abandon();
ShowMessage("A temporary password has been sent.");
UpdateUserStatus(userId, 3); // 2 is verified
}
else
{
ShowMessage("There was an issue sending your password.");
}
}
else
{
ShowMessage("There was an issue generating a temporary password.");
}
ResetFormFields();
}
else
{
// Get stored password and validate
string storedPassword = GetUserStoredPassword(user);
bool validated = ValidatePassword(password, storedPassword);
int saltLength = GetSaltLength();
string saltValue = GetSaltValue(storedPassword);
string hashedPassword = EncryptPasswordWithSalt(password, saltValue);
int userID = ValidateUser(username, hashedPassword);
if (!btnText.Contains("Change") && userID > 0 && validated)
{
// Session management and redirection
ManageSession(username);
RedirectAuthenticatedUser();
}
else if (btnText.Contains("Change") && userID > 0 && validated)
{
// Handle password change
HandlePasswordChange(user);
}
else
{
// Authentication failure handling
HandleAuthenticationFailure(userID, validated);
}
}
}
else
{
ShowMessage("User not found.");
}
}
else
{
ShowMessage("Username and password are required.");
}
}
catch (Exception ex)
{
HandleException(ex);
}
}
And the following is sample code from LoginAs.aspx.cs
:
public partial class LoginAs : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsRolePermitted())
{
RedirectUnauthorizedAccess();
}
if (!IsPostBack)
{
ConfigurePageLayout();
}
}
protected void SignIn_Click(object sender, EventArgs e)
{
string username = txtUsername.Text;
if (!string.IsNullOrEmpty(username))
{
int userID = AuthenticateUser(username, "Test");
if (userID == -1)
{
InitiateUserSession(username);
RedirectAuthenticatedUser();
}
else
{
DisplayAuthenticationError();
}
}
}
private bool IsRolePermitted()
{
// Check user's role permission
return RoleItem.IsRoleItemPermittedToUser(UserName.GetUserLogin(), 31);
}
private void RedirectUnauthorizedAccess()
{
// Redirect to an unauthorized access page
Response.Redirect("~/UnAuthorizedAccess.aspx");
}
private void ConfigurePageLayout()
{
Master.ShowTopMenu = false;
Master.ShowTitle = true;
Master.ShowUserLogin = false;
Master.PageTitle = "Login As Screen";
Master.FormTitle = "Login As Screen";
}
private int AuthenticateUser(string username, string password)
{
// Authenticate user logic
return DataService.Contact.SelectLogin(username, password);
}
private void InitiateUserSession(string username)
{
// Set session variables for the authenticated user
Session["FromLogin"] = "Yes";
FormsAuthentication.RedirectFromLoginPage(username, false);
}
private void RedirectAuthenticatedUser()
{
// Redirect the authenticated user to the appropriate page
Response.Redirect("~/YourAuthenticatedPage.aspx");
}
private void DisplayAuthenticationError()
{
// Display an authentication error message
cusValWrongLogin.IsValid = false;
}
}
Thanks @Andrew Williamson for the comment.
If you don't want to migrate and still want to use the Legacy ASP.NET Framework, check the below steps.
With your Application Folder Structure and code, it is clear that, you are adding the code related to Azure AD Authentication manually.
We have few ways to Integrate the Azure AD code within our application automatically.
Way 1 :
Refer the SOThread which I have answered to get the sample code of Azure AD Integration.
Way 2 :
While creating WebApp, select the Authentication type as Microsoft.
This step makes you to setup the automatic configuration of Azure AD registered app in your application.
Select the correct tenant. As you have already registered the app in AD, select the same app.
Web.config
file.Web.config
file:
<appSettings>
<add key="ida:ClientId" value="**********" />
<add key="ida:AADInstance" value="https://login.microsoftonline.com/" />
<add key="ida:Domain" value="****.onmicrosoft.com" />
<add key="ida:TenantId" value="**********" />
<add key="ida:PostLogoutRedirectUri" value="https://localhost:44346/signin-oidc" />
</appSettings>
The default code uses the OpenIdConnectAuthentication
.
In App_Start
folder, StartupAuth.cs
file will be created with Code related to Authentication configuration.
Way 3:
Output: