question

AzureDevTest avatar image
0 Votes"
AzureDevTest asked AzureDevTest edited

How to customize starup.cs to load from database

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



azure-active-directorydotnet-aspnet-general
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

AzureDevTest avatar image
0 Votes"
AzureDevTest answered AzureDevTest edited

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;
             }
         }


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

llaxmikant avatar image
0 Votes"
llaxmikant answered YijingSun-MSFT commented

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);
     } 
  }


· 6
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Can I get the sample code, for the azure thing I am using ASP.NET application not core or mvc

0 Votes 0 ·

Hi @DorababuM-5440 ,
Could you tell us what's type of your project?Asp.net c#?Asp.net Webform? Asp.net Webapi? The startup.cs file isn't exist in these type's application, so you need to customize and you need to make sure that Owin is recognizing it.
Best regards,
Yijing Sun

0 Votes 0 ·

It is an asp.net webform (.aspx) project. It had startup.cs but I would like to customize the code which I shared

0 Votes 0 ·
Show more comments