ASP.NET – Dependency Injection in WebForms (JNNC Technologies)


Dependency injection (DI) is a technique whereby one object supplies the dependencies of another object. It decouples the objects so that no client code has to be changed simply because an object it depends on needs to be changed to a different one. MVC Framework already supports dependency injection, but has been very difficult to use this technique in ASP.NET Web Forms application. This new feature will make it much easier to use dependency injection in ASP.NET Web Forms application. This feature enables the following:
  • Support setter-based, interface-based and constructor-based injection in web application project in Handler, Module, Page, User control and Custom control.
  • Support setter-based and interface-based injection in web site project in Handler, Module, Page, User controls and Custom controls.
  • Be able to plug in different dependency injection frameworks.
Here’s a simple example of how you can use this feature. 
Step 1 – Implement IServiceProvider. You can implement your own DI logic in it or plug in third party DI framework, e.g. UnityNinject. Below is an example to inject ILog object through constructor.
public class SimpleActivator : IServiceProvider
{
public object GetService(Type serviceType)
{
var ctors = serviceType.GetConstructors();
ConstructorInfo targetCtor = null;
foreach (var c in ctors)
{
if(c.GetParameters().Select(p => p.GetType() == typeof(ILog)).Count() > 0)
{
targetCtor = c;
break;
}
}
if(targetCtor != null)
{
return targetCtor.Invoke(new object[] { new DebuggingLoger() });
}
else
{
return Activator.CreateInstance(
serviceType,
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.CreateInstance,
null,
null,
null);
}
}
}
Step 2 – Set WebObjectActivator in Global.asax.
public class Global : System.Web.HttpApplication
{
public override void Init()
{
HttpRuntime.WebObjectActivator = new NaiveActivator();
base.Init();
}
}
Step 3 – Use Dependency Injection in your Webform page.
public partial class WebForm2 : System.Web.UI.Page
{
private ILog _log;
public WebForm2(ILog l)
{
_log = l;
}
}

ASP.NET – SameSite Cookie

SameSite prevents the browser from sending this cookie along with cross-site requests.  In .NET Framework 4.7.2, a new property SameSite is added in HttpCookie type and ASP.NET will add SameSite attribute into the set-cookie header if HttpCookie.SameSite is set to SameSiteMode.Strict or SameSiteMode.Lax. The support for SameSite cookie is two-fold in this case: 
You can set SameSite for a HttpCookie object as follows.
var c = new HttpCookie("secureCookie", "same origin");
c.SameSite = SameSiteMode.Lax;
You can configure HttpCookie SameSite at application level through web.config as follows.
<system.web>
<httpCookies sameSite="Strict"/>
</system.web>
You can add SameSite for FormsAuthentication and SessionState cookies through web.config.
<system.web>
<authentication mode="Forms">
<forms cookieSameSite="Lax">
<!-- .... -->
</forms>
</authentication>
<sessionState cookieSameSite="Lax"></sessionState>
</system.web>

SQL – Azure AD Universal and Multi-factor Authentication Support

Growing compliance and security demand requires many customers to use Multi-Factor authentication (MFA).  In addition, current best practices directs developers from not including any user password directly to the connection string. We have extended SqlClient Connection String by introducing a new Azure AD Interactive authentication keyword to support MFA. This also enables support of Azure AD Authentication. 
This feature introduces a new value for the existing “Authentication” keyword, specifying a new authentication method called “Active Directory Interactive”. The new interactive method supports native and federated Azure AD users as well as Azure AD guest users.  When this method is being used, the MFA authentication imposed by Azure AD is supported for SQL DB. In addition, a user password is requested as part of an interactive dialog enabling us to adhere to security best practices.
Originally SQL connectivity in .NET Framework supported only ActiveDirectoryPassword and ActiveDirectoryIntegrated. Both of these are part of the non-interactive ADAL protocol which do not support MFA. With the new ActiveDirectoryInteractive keyword, the SQL connectivity supports MFA as well as existing authentication methods (password and integrated authentication) allowing users to enter user password interactively without the need to persist passwords in the SQL connection string.
This feature can be configured with tools like SQL Server Data Tools (SSDT), as illustrated below. In the latest Visual Studio preview, a new authentication option called “Active Directory Interactive Authentication” can be used to support MFA authentication to SQL database.
The following sample shows how to instantiate the communication provider that is required to register it to a specific authentication method. It also shows creating connections to SQL database using the different authentication methods, of which two are existing ones: ActiveDirectoryPassword, ActiveDirectoryIntegrated and the latest ActiveDirectoryInteractive.
class Program
{
static void Test()
{
// Instantiate the provider.
var provider = new ActiveDirectoryAuthProvider();
// Register the provider to auth methods. This only needs to be done once per process.
//This sample shows existing and new keywords. You can use few of these depending on your scenario.
SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryIntegrated, provider);
SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryInteractive, provider);
SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryPassword, provider);
// Start connections.
using (SqlConnection connection = new SqlConnection("test conn string..."))
{
connection.Open();
// query
}
}
// An auth provider implementation that supports all three AD auth methods
class ActiveDirectoryAuthProvider : SqlAuthenticationProvide
{
private readonly string _clientId = "clientId";
private readonly Uri _redirectUri = new Uri("redirect uri");
public override async Task<SqlAuthenticationToken> AcquireTokenAsync(SqlAuthenticationParameters
parameters)
{
AuthenticationContext authContext = new AuthenticationContext(parameters.Authority);
authContext.CorrelationId = parameters.ConnectionId;
AuthenticationResult result;
switch (parameters.AuthenticationMethod)
{
case SqlAuthenticationMethod.ActiveDirectoryInteractive:
result = await authContext.AcquireTokenAsync(parameters.Resource, _clientId,
_redirectUri, new PlatformParameters(PromptBehavior.Auto),
new UserIdentifier(parameters.UserId, UserIdentifierType.RequiredDisplayableId));
break;
case SqlAuthenticationMethod.ActiveDirectoryIntegrated:
result = await authContext.AcquireTokenAsync(parameters.Resource, _clientId,
new UserCredential());
break;
case SqlAuthenticationMethod.ActiveDirectoryPassword:
result = await authContext.AcquireTokenAsync(parameters.Resource, _clientId,
new UserPasswordCredential(parameters.UserId, parameters.Password));
break;
default: throw new InvalidOperationException();
}
return new SqlAuthenticationToken(result.AccessToken, result.ExpiresOn);
}
public override bool IsSupported(SqlAuthenticationMethod authenticationMethod)
{
return authenticationMethod == SqlAuthenticationMethod.ActiveDirectoryIntegrated
|| authenticationMethod == SqlAuthenticationMethod.ActiveDirectoryInteractive
|| authenticationMethod == SqlAuthenticationMethod.ActiveDirectoryPassword;
}
}
}

Post a Comment

0 Comments

'; (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })();