Force sign-in
Single sign-on (SSO) adds security and convenience when users sign-in across multiple applications in Microsoft Entra ID. With single sign-on, users sign-in once with a single account and get access to multiple applications. When the user initially signs-in to an application, Microsoft Entra ID initiates a single sign-on session. Upon subsequent authentication requests, Microsoft Entra ID validates the session, and issues a security token without prompting the user to sign in again. The OAuth 2.0 authorization code flow's prompt=login query string paramter forces the user to enter their credentials on that request, negating single-sign on. Note, users can remove this query string parameter from the authorization request in the web browser address bar and bypass this method.
Prerequisites
Before you start make sure you have configured the following:The OAuth 2.0 authorization code flow supports the prompt=login query string parameter which forces the user to enter their credentials on that request, negating single-sign on. So, you don't need to configure anything special in your Microsoft Entra external ID tenant. In your application include the prompt=login parameter. The .NET code snippets in the next steps demonstrates how to use the OnRedirectToIdentityProvider event to pass the prompt parameter.
In the sign-in action of your code, use the Challenge Method to pass a custom property that informs the MSAL library that a custom code is required.
public IActionResult OnGetSignIn()
{
ChallengeResult challengeResult = new ChallengeResult(
OpenIdConnectDefaults.AuthenticationScheme,
new AuthenticationProperties
{
RedirectUri = "/"
});
// Force re-authentication
challengeResult.Properties.Items.Add("force", "true");
return challengeResult;
}
Next in your Program.cs file add the following code. The code sets the OnRedirectToIdentityProvider event with a reference to the OnRedirectToIdentityProviderFunc method. This method will be invoked before redirecting to the identity provider (Microsoft Entra ID) to authenticate.
builder.Services.Configure(OpenIdConnectDefaults.AuthenticationScheme,
options =>
{
options.TokenValidationParameters.RoleClaimType = "roles";
options.TokenValidationParameters.NameClaimType = "name";
options.Events.OnRedirectToIdentityProvider += OnRedirectToIdentityProviderFunc;
});
Finally, add the OnRedirectToIdentityProviderFunc method to the Startup.cs class.
async Task OnRedirectToIdentityProviderFunc(RedirectContext context)
{
// Read the 'force' custom parameter
var forceSignIn = context.Properties.Items.FirstOrDefault(x => x.Key == "force").Value;
// Add your custom code here
if (forceSignIn != null)
{
context.ProtocolMessage.Prompt = "login";
}
// Don't remove this line
await Task.CompletedTask.ConfigureAwait(false);
}