Code:
/ FXUpdate3074 / FXUpdate3074 / 1.1 / DEVDIV / depot / DevDiv / releases / whidbey / QFE / ndp / fx / src / xsp / System / Web / Security / WindowsAuthenticationModule.cs / 3 / WindowsAuthenticationModule.cs
//------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//-----------------------------------------------------------------------------
/*
* WindowsAuthenticationModule class
*
* Copyright (c) 1999 Microsoft Corporation
*/
namespace System.Web.Security {
using System.Web;
using System.Web.Configuration;
using System.Security.Principal;
using System.Security.Permissions;
using System.Globalization;
using System.Web.Management;
using System.Web.Util;
using System.Web.Hosting;
///
///
/// Allows ASP.NET applications to use Windows/IIS authentication.
///
///
[AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)]
public sealed class WindowsAuthenticationModule : IHttpModule {
private WindowsAuthenticationEventHandler _eventHandler;
private static bool _fAuthChecked;
private static bool _fAuthRequired;
private static WindowsIdentity _anonymousIdentity;
private static WindowsPrincipal _anonymousPrincipal;
///
///
/// Initializes a new instance of the
/// class.
///
///
[SecurityPermission(SecurityAction.Demand, Unrestricted=true)]
public WindowsAuthenticationModule() {
}
///
/// This is a global.asax event that must be
/// named WindowsAuthenticate_OnAuthenticate event. It's used primarily to attach a
/// custom IPrincipal object to the context.
///
public event WindowsAuthenticationEventHandler Authenticate {
add {
_eventHandler += value;
}
remove {
_eventHandler -= value;
}
}
///
/// [To be supplied.]
///
public void Dispose() {
}
///
/// [To be supplied.]
///
public void Init(HttpApplication app) {
app.AuthenticateRequest += new EventHandler(this.OnEnter);
}
////////////////////////////////////////////////////////////
// OnAuthenticate: Custom Authentication modules can override
// this method to create a custom IPrincipal object from
// a WindowsIdentity
///
/// Calls the
/// WindowsAuthentication_OnAuthenticate handler if one exists.
///
void OnAuthenticate(WindowsAuthenticationEventArgs e) {
////////////////////////////////////////////////////////////
// If there are event handlers, invoke the handlers
if (_eventHandler != null)
_eventHandler(this, e);
if (e.Context.User == null)
{
if (e.User != null)
e.Context.User = e.User;
else if (e.Identity == _anonymousIdentity)
e.Context.SetPrincipalNoDemand(_anonymousPrincipal, false /*needToSetNativePrincipal*/);
else
e.Context.SetPrincipalNoDemand(new WindowsPrincipal(e.Identity), false /*needToSetNativePrincipal*/);
}
}
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Methods for internal implementation
///
///
///
void OnEnter(Object source, EventArgs eventArgs) {
if (!IsEnabled)
return;
HttpApplication app = (HttpApplication)source;
HttpContext context = app.Context;;
WindowsIdentity identity = null;
//////////////////////////////////////////////////////////////////
// Step 2: Create a Windows Identity from the credentials from IIS
if (HttpRuntime.UseIntegratedPipeline) {
// The native WindowsAuthenticationModule sets the user principal in IIS7WorkerRequest.SynchronizeVariables.
// The managed WindowsAuthenticationModule provides backward compatibility by rasing the OnAuthenticate event.
WindowsPrincipal user = context.User as WindowsPrincipal;
if (user != null) {
// identity will be null if this is not a WindowsIdentity
identity = user.Identity as WindowsIdentity;
// clear Context.User for backward compatibility (it will be set in OnAuthenticate)
context.SetPrincipalNoDemand(null, false /*needToSetNativePrincipal*/);
}
}
else {
String strLogonUser = context.WorkerRequest.GetServerVariable("LOGON_USER");
String strAuthType = context.WorkerRequest.GetServerVariable("AUTH_TYPE");
if (strLogonUser == null) {
strLogonUser = String.Empty;
}
if (strAuthType == null) {
strAuthType = String.Empty;
}
if (strLogonUser.Length == 0 && (strAuthType.Length == 0 ||
StringUtil.EqualsIgnoreCase(strAuthType, "basic")))
{
////////////////////////////////////////////////////////
// Step 2a: Use the anonymous identity
identity = _anonymousIdentity;
}
else
{
identity = new WindowsIdentity(
context.WorkerRequest.GetUserToken(),
strAuthType,
WindowsAccountType.Normal,
true);
}
}
///////////////////////////////////////////////////////////////////////////////////
// Step 3: Call OnAuthenticate to create IPrincipal for this request.
if (identity != null) {
OnAuthenticate( new WindowsAuthenticationEventArgs(identity, context) );
}
}
internal static IPrincipal AnonymousPrincipal { get { return _anonymousPrincipal; } }
internal static bool IsEnabled {
get {
if (!_fAuthChecked) {
AuthenticationSection settings = RuntimeConfig.GetAppConfig().Authentication;
settings.ValidateAuthenticationMode();
_fAuthRequired = (settings.Mode == AuthenticationMode.Windows);
if (_fAuthRequired) {
_anonymousIdentity = WindowsIdentity.GetAnonymous();
_anonymousPrincipal = new WindowsPrincipal(_anonymousIdentity);
}
_fAuthChecked = true;
}
return _fAuthRequired;
}
}
}
}
// File provided for Reference Use Only by Microsoft Corporation (c) 2007.
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//-----------------------------------------------------------------------------
/*
* WindowsAuthenticationModule class
*
* Copyright (c) 1999 Microsoft Corporation
*/
namespace System.Web.Security {
using System.Web;
using System.Web.Configuration;
using System.Security.Principal;
using System.Security.Permissions;
using System.Globalization;
using System.Web.Management;
using System.Web.Util;
using System.Web.Hosting;
///
///
/// Allows ASP.NET applications to use Windows/IIS authentication.
///
///
[AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)]
public sealed class WindowsAuthenticationModule : IHttpModule {
private WindowsAuthenticationEventHandler _eventHandler;
private static bool _fAuthChecked;
private static bool _fAuthRequired;
private static WindowsIdentity _anonymousIdentity;
private static WindowsPrincipal _anonymousPrincipal;
///
///
/// Initializes a new instance of the
/// class.
///
///
[SecurityPermission(SecurityAction.Demand, Unrestricted=true)]
public WindowsAuthenticationModule() {
}
///
/// This is a global.asax event that must be
/// named WindowsAuthenticate_OnAuthenticate event. It's used primarily to attach a
/// custom IPrincipal object to the context.
///
public event WindowsAuthenticationEventHandler Authenticate {
add {
_eventHandler += value;
}
remove {
_eventHandler -= value;
}
}
///
/// [To be supplied.]
///
public void Dispose() {
}
///
/// [To be supplied.]
///
public void Init(HttpApplication app) {
app.AuthenticateRequest += new EventHandler(this.OnEnter);
}
////////////////////////////////////////////////////////////
// OnAuthenticate: Custom Authentication modules can override
// this method to create a custom IPrincipal object from
// a WindowsIdentity
///
/// Calls the
/// WindowsAuthentication_OnAuthenticate handler if one exists.
///
void OnAuthenticate(WindowsAuthenticationEventArgs e) {
////////////////////////////////////////////////////////////
// If there are event handlers, invoke the handlers
if (_eventHandler != null)
_eventHandler(this, e);
if (e.Context.User == null)
{
if (e.User != null)
e.Context.User = e.User;
else if (e.Identity == _anonymousIdentity)
e.Context.SetPrincipalNoDemand(_anonymousPrincipal, false /*needToSetNativePrincipal*/);
else
e.Context.SetPrincipalNoDemand(new WindowsPrincipal(e.Identity), false /*needToSetNativePrincipal*/);
}
}
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Methods for internal implementation
///
///
///
void OnEnter(Object source, EventArgs eventArgs) {
if (!IsEnabled)
return;
HttpApplication app = (HttpApplication)source;
HttpContext context = app.Context;;
WindowsIdentity identity = null;
//////////////////////////////////////////////////////////////////
// Step 2: Create a Windows Identity from the credentials from IIS
if (HttpRuntime.UseIntegratedPipeline) {
// The native WindowsAuthenticationModule sets the user principal in IIS7WorkerRequest.SynchronizeVariables.
// The managed WindowsAuthenticationModule provides backward compatibility by rasing the OnAuthenticate event.
WindowsPrincipal user = context.User as WindowsPrincipal;
if (user != null) {
// identity will be null if this is not a WindowsIdentity
identity = user.Identity as WindowsIdentity;
// clear Context.User for backward compatibility (it will be set in OnAuthenticate)
context.SetPrincipalNoDemand(null, false /*needToSetNativePrincipal*/);
}
}
else {
String strLogonUser = context.WorkerRequest.GetServerVariable("LOGON_USER");
String strAuthType = context.WorkerRequest.GetServerVariable("AUTH_TYPE");
if (strLogonUser == null) {
strLogonUser = String.Empty;
}
if (strAuthType == null) {
strAuthType = String.Empty;
}
if (strLogonUser.Length == 0 && (strAuthType.Length == 0 ||
StringUtil.EqualsIgnoreCase(strAuthType, "basic")))
{
////////////////////////////////////////////////////////
// Step 2a: Use the anonymous identity
identity = _anonymousIdentity;
}
else
{
identity = new WindowsIdentity(
context.WorkerRequest.GetUserToken(),
strAuthType,
WindowsAccountType.Normal,
true);
}
}
///////////////////////////////////////////////////////////////////////////////////
// Step 3: Call OnAuthenticate to create IPrincipal for this request.
if (identity != null) {
OnAuthenticate( new WindowsAuthenticationEventArgs(identity, context) );
}
}
internal static IPrincipal AnonymousPrincipal { get { return _anonymousPrincipal; } }
internal static bool IsEnabled {
get {
if (!_fAuthChecked) {
AuthenticationSection settings = RuntimeConfig.GetAppConfig().Authentication;
settings.ValidateAuthenticationMode();
_fAuthRequired = (settings.Mode == AuthenticationMode.Windows);
if (_fAuthRequired) {
_anonymousIdentity = WindowsIdentity.GetAnonymous();
_anonymousPrincipal = new WindowsPrincipal(_anonymousIdentity);
}
_fAuthChecked = true;
}
return _fAuthRequired;
}
}
}
}
// File provided for Reference Use Only by Microsoft Corporation (c) 2007.
// Copyright (c) Microsoft Corporation. All rights reserved.
Link Menu

This book is available now!
Buy at Amazon US or
Buy at Amazon UK
- MessageHeaders.cs
- EditorPartDesigner.cs
- ListenerAdapterBase.cs
- XmlDocumentType.cs
- HttpInputStream.cs
- InputReportEventArgs.cs
- DataBindingCollection.cs
- CompositeFontParser.cs
- ShowExpandedMultiValueConverter.cs
- OleDbErrorCollection.cs
- TemplatedWizardStep.cs
- ChangePassword.cs
- OdbcDataAdapter.cs
- ValidationManager.cs
- SqlCacheDependencyDatabaseCollection.cs
- QueryExecutionOption.cs
- CalendarDay.cs
- SymLanguageVendor.cs
- UserPreferenceChangingEventArgs.cs
- LinearQuaternionKeyFrame.cs
- RuntimeConfigurationRecord.cs
- TypeSystem.cs
- TrailingSpaceComparer.cs
- GenericUI.cs
- WindowHelperService.cs
- AutoSizeComboBox.cs
- XmlUtilWriter.cs
- CodeAttachEventStatement.cs
- TypeUtils.cs
- IsolatedStorageFileStream.cs
- Brush.cs
- ProcessHostServerConfig.cs
- TransformPatternIdentifiers.cs
- SignatureDescription.cs
- OdbcEnvironmentHandle.cs
- FastEncoderWindow.cs
- WebPartHelpVerb.cs
- AutomationPeer.cs
- GeneralTransform3DGroup.cs
- OdbcFactory.cs
- VarRefManager.cs
- ElementAction.cs
- __TransparentProxy.cs
- GeneralTransform3DGroup.cs
- Command.cs
- TextBoxDesigner.cs
- FontFamilyValueSerializer.cs
- ChameleonKey.cs
- DataGridColumnCollection.cs
- TextFormatter.cs
- VisualStyleRenderer.cs
- DataGridViewCheckBoxCell.cs
- ToolboxItemAttribute.cs
- RangeContentEnumerator.cs
- Triangle.cs
- XmlWhitespace.cs
- MailDefinition.cs
- HttpServerVarsCollection.cs
- TypeSemantics.cs
- WsdlBuildProvider.cs
- SchemaElementLookUpTable.cs
- TextSpanModifier.cs
- SqlMethodAttribute.cs
- DataGridCell.cs
- LayoutEditorPart.cs
- Ref.cs
- Point3DValueSerializer.cs
- SchemaImporterExtension.cs
- SqlResolver.cs
- MissingManifestResourceException.cs
- GCHandleCookieTable.cs
- InheritanceAttribute.cs
- DriveInfo.cs
- CredentialCache.cs
- DiscreteKeyFrames.cs
- DoubleLink.cs
- DataGridDetailsPresenter.cs
- ProcessThreadCollection.cs
- PathParser.cs
- path.cs
- CaseInsensitiveHashCodeProvider.cs
- TakeQueryOptionExpression.cs
- DynamicMethod.cs
- AnyAllSearchOperator.cs
- LongCountAggregationOperator.cs
- UIElement3D.cs
- CheckedListBox.cs
- DBConcurrencyException.cs
- AsyncDataRequest.cs
- EntityContainer.cs
- ProfileBuildProvider.cs
- TypeReference.cs
- ToolStripButton.cs
- ParsedAttributeCollection.cs
- XmlResolver.cs
- DiscoveryEndpointElement.cs
- TypeTypeConverter.cs
- SplashScreenNativeMethods.cs
- SourceInterpreter.cs
- ToolStripSystemRenderer.cs