How to customize starup.cs to load from database

Dorababu Meka 96 Reputation points
2021-08-27T09:43:39.7+00:00

I am using Azure AD authentication in my asp.net application

 public class Startup
    {
        // The Client ID is used by the application to uniquely identify itself to Azure AD.
        string clientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"];

        // RedirectUri is the URL where the user will be redirected to after they sign in.
        string redirectUri = System.Configuration.ConfigurationManager.AppSettings["RedirectUri"];

        // Tenant is the tenant ID (e.g. contoso.onmicrosoft.com, or 'common' for multi-tenant)
        static string tenant = System.Configuration.ConfigurationManager.AppSettings["Tenant"];

        // Authority is the URL for authority, composed by Microsoft identity platform endpoint and the tenant name (e.g. https://login.microsoftonline.com/contoso.onmicrosoft.com/v2.0)
        string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, System.Configuration.ConfigurationManager.AppSettings["Authority"], tenant);

        /// <summary>
        /// Configure OWIN to use OpenIdConnect 
        /// </summary>
        /// <param name="app"></param>
        public void Configuration(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                // Sets the ClientId, authority, RedirectUri as obtained from web.config
                ClientId = clientId,
                Authority = authority,
                RedirectUri = redirectUri,
                // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
                PostLogoutRedirectUri = redirectUri,
                Scope = OpenIdConnectScope.OpenIdProfile,
                // ResponseType is set to request the code id_token - which contains basic information about the signed-in user
                ResponseType = OpenIdConnectResponseType.CodeIdToken,
                // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = OnAuthenticationFailed
                }
            }
        );
        }

        /// <summary>
        /// Handle failed authentication requests by redirecting the user to the home page with an error in the query string
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
        {
            context.HandleResponse();
            context.Response.Redirect("/?errormessage=" + context.Exception.Message);
            return Task.FromResult(0);
        }
    }

The settings are getting loaded initially, I would like to customize this so that I will read ClientId, Tenant from database based on the domain. On button click I would like customize this startup

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,242 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
19,381 questions
0 comments No comments
{count} votes

Accepted answer
  1. Dorababu Meka 96 Reputation points
    2021-09-01T12:33:50.22+00:00

    I made this and change and it is working as expected.

    public void Configuration(IAppBuilder app)
            {
                app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
                app.UseCookieAuthentication(new CookieAuthenticationOptions());
                SetApp(app);
            }
    
            private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
            {
                context.HandleResponse();
                context.Response.Redirect("/?errormessage=" + context.Exception.Message);
                return Task.FromResult(0);
            }
    
    
    private IAppBuilder SetApp(IAppBuilder app)
            {
                using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["azureSetting"].ConnectionString))
                {
                    using (SqlCommand cmd = new SqlCommand("SELECT DomainName, ClientId, TenantId, RedirectUrl, AuthorityUrl FROM AzureMapping", con))
                    {
                        cmd.CommandType = CommandType.Text;
                        using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                        {
                            using (DataSet ds = new DataSet())
                            {
                                sda.Fill(ds);
                                foreach (DataRow row in ds.Tables[0].Rows)
                                {
                                    app.UseOpenIdConnectAuthentication(
                                    new OpenIdConnectAuthenticationOptions(row["DomainName"].ToString())
                                    {
                                        // Sets the ClientId, authority, RedirectUri as obtained from web.config
                                        ClientId = row["ClientId"].ToString(),
                                        Authority = string.Format(System.Globalization.CultureInfo.InvariantCulture, row["AuthorityUrl"].ToString(), row["TenantId"].ToString()),
                                        RedirectUri = row["RedirectUrl"].ToString(),
                                        // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
                                        PostLogoutRedirectUri = "https://localhost:44346/signout-callback-oidc",
                                        Scope = OpenIdConnectScope.OpenIdProfile,
                                        // ResponseType is set to request the code id_token - which contains basic information about the signed-in user
                                        ResponseType = OpenIdConnectResponseType.CodeIdToken,
                                        // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
                                        Notifications = new OpenIdConnectAuthenticationNotifications
                                        {
                                            AuthenticationFailed = OnAuthenticationFailed
                                        }
                                    }
            );
                                }
                            }
                        }
                    }
                }
                return app;
            }
    

    On login.aspx page I am checking for the particular domain and calling the oprion

    protected void btnSignIn_Click(object sender, EventArgs e)
            {
                if (!Request.IsAuthenticated)
                {
                    HttpContext.Current.GetOwinContext().Authentication.Challenge(
                        new AuthenticationProperties { RedirectUri = "/" },
                      new MailAddress(txtEmail.Text).Host);
                    Session["Domain"] = new MailAddress(txtEmail.Text).Host;
                }
            }
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Laxmikant 216 Reputation points
    2021-08-27T15:27:59.78+00:00

    you should create a separate class library project to handle your configuration.

    You can use IConfiguration interface to get appsettings value configured in web applications.

    For more info you can check - read appsettings json in net core class library using dependency-injection

    public class ConfigManager : IGeekConfigManager
        {
            private readonly IConfiguration _configuration;
    
            public ConfigManager(IConfiguration configuration)
            {
                this._configuration = configuration;
            }
    
    
           public string NorthwindConnection
          {
             get
             {    
                return this._configuration["ConnectionStrings:NorthwindDatabase"]; 
             }
         }
    
        public string GetConnectionString(string connectionName)
        {
           return this._configuration.GetConnectionString(connectionName);
        } 
     }