Code:
/ Dotnetfx_Vista_SP2 / Dotnetfx_Vista_SP2 / 8.0.50727.4016 / DEVDIV / depot / DevDiv / releases / whidbey / NetFxQFE / ndp / fx / src / xsp / System / Web / Security / PassportAuthenticationModule.cs / 1 / PassportAuthenticationModule.cs
//------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//-----------------------------------------------------------------------------
/*
* PassportAuthenticationModule class
*
* Copyright (c) 1999 Microsoft Corporation
*/
namespace System.Web.Security {
using System.Web;
using System.Security.Principal;
using System.Web.Configuration;
using System.Web.Handlers;
using System.Globalization;
using System.Security.Permissions;
using System.Web.Management;
///
/// This
/// module provides a wrapper around passport authentication services.
///
[AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)]
public sealed class PassportAuthenticationModule : IHttpModule {
private PassportAuthenticationEventHandler _eventHandler;
private static bool _fAuthChecked = false;
private static bool _fAuthRequired = false;
private static String _LoginUrl = null;
///
///
/// Initializes a new instance of the
/// class.
///
///
[SecurityPermission(SecurityAction.Demand, Unrestricted=true)]
public PassportAuthenticationModule() {
}
////////////////////////////////////////////////////////////
// AddOnAuthenticate and RemoveOnAuthenticate: Use these
// methods to hook up event handlers to handle the
// OnAuthenticate Event
///
/// This is a global.asax event that must be
/// named PassportAuthenticate_OnAuthenticate event.
///
public event PassportAuthenticationEventHandler 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);
app.EndRequest += new EventHandler(this.OnLeave);
}
////////////////////////////////////////////////////////////
// OnAuthenticate: Custom Authentication modules can override
// this method to create a custom IPrincipal object from
// a PassportIdentity
///
/// Calls the
/// PassportAuthentication_OnAuthenticate handler, if one exists.
///
void OnAuthenticate(PassportAuthenticationEventArgs e) {
////////////////////////////////////////////////////////////
// If there are event handlers, invoke the handlers
if (_eventHandler != null) {
_eventHandler(this, e);
if (e.Context.User == null && e.User != null)
{
InternalSecurityPermissions.ControlPrincipal.Demand();
e.Context.User = e.User;
}
}
////////////////////////////////////////////////////////////
// Default Implementation: If IPrincipal has not been created,
// create a PassportUser
if (e.Context.User == null)
{
InternalSecurityPermissions.ControlPrincipal.Demand();
e.Context.User = new PassportPrincipal(e.Identity, new String[0]);
}
}
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Methods for internal implementation
///
///
///
void OnEnter(Object source, EventArgs eventArgs) {
if (_fAuthChecked && !_fAuthRequired)
return;
HttpApplication app;
HttpContext context;
app = (HttpApplication)source;
context = app.Context;
if (!_fAuthChecked) {
AuthenticationSection settings = RuntimeConfig.GetAppConfig().Authentication;
settings.ValidateAuthenticationMode();
_fAuthRequired = (settings.Mode == AuthenticationMode.Passport);
_LoginUrl = settings.Passport.RedirectUrl;
_fAuthChecked = true;
}
if (!_fAuthRequired)
return;
////////////////////////////////////////////////////////
// Step 1: See if this request is valid or not
// VSWhidbey 442515: We no longer need to do this check, always proceed
////////////////////////////////////////////////////////
// Step 2: Create a Passport Identity from the credentials
// from IIS
PassportIdentity identity = new PassportIdentity();
////////////////////////////////////////////////////////
// Step 4: Call OnAuthenticate virtual method to create
// an IPrincipal for this request
OnAuthenticate( new PassportAuthenticationEventArgs(identity, context) );
////////////////////////////////////////////////////////
// Skip AuthZ if accessing the login page
context.SetSkipAuthorizationNoDemand(AuthenticationConfig.AccessingLoginPage(context, _LoginUrl), false /*managedOnly*/);
if (!context.SkipAuthorization) {
context.SkipAuthorization = AssemblyResourceLoader.IsValidWebResourceRequest(context);
}
}
void OnLeave(Object source, EventArgs eventArgs) {
HttpApplication app;
HttpContext context;
app = (HttpApplication)source;
context = app.Context;
if (!_fAuthChecked || !_fAuthRequired || context.User == null || context.User.Identity == null || !(context.User.Identity is PassportIdentity))
return;
PassportIdentity id = (PassportIdentity) context.User.Identity;
if (context.Response.StatusCode != 401 || id.WWWAuthHeaderSet)
return;
if ( _LoginUrl==null || _LoginUrl.Length < 1 || String.Compare(_LoginUrl, "internal", StringComparison.Ordinal) == 0) {
context.Response.Clear();
context.Response.StatusCode = 200;
if (!ErrorFormatter.RequiresAdaptiveErrorReporting(context)) {
String strUrl = context.Request.Url.ToString();
int iPos = strUrl.IndexOf('?');
if (iPos >= 0) {
strUrl = strUrl.Substring(0, iPos);
}
String strLogoTag = id.LogoTag2(HttpUtility.UrlEncode(strUrl, context.Request.ContentEncoding));
String strMsg = SR.GetString(SR.PassportAuthFailed, strLogoTag);
context.Response.Write(strMsg);
}
else {
ErrorFormatter errorFormatter = new PassportAuthFailedErrorFormatter();
context.Response.Write(errorFormatter.GetAdaptiveErrorMessage(context, true));
}
}
else {
////////////////////////////////////////////////////////////
// Step 1: Get the redirect url
String redirectUrl = AuthenticationConfig.GetCompleteLoginUrl(context, _LoginUrl);
////////////////////////////////////////////////////////////
// Step 2: Check if we have a valid url to the redirect-page
if (redirectUrl == null || redirectUrl.Length <= 0)
throw new HttpException(SR.GetString(SR.Invalid_Passport_Redirect_URL));
////////////////////////////////////////////////////////////
// Step 3: Construct the redirect-to url
String strUrl = context.Request.Url.ToString();
String strRedirect;
int iIndex;
String strSep;
if (redirectUrl.IndexOf('?') >= 0)
strSep = "&";
else
strSep = "?";
strRedirect = redirectUrl + strSep + "ReturnUrl=" + HttpUtility.UrlEncode(strUrl, context.Request.ContentEncoding);
////////////////////////////////////////////////////////////
// Step 4: Add the query-string from the current url
iIndex = strUrl.IndexOf('?');
if (iIndex >= 0 && iIndex < strUrl.Length-1)
strRedirect += "&" + strUrl.Substring(iIndex+1);
////////////////////////////////////////////////////////////
// Step 5: Do the redirect
context.Response.Redirect(strRedirect, false);
}
}
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// ErrorFormatter for generating adaptive error for mobile devices
internal class PassportAuthFailedErrorFormatter : ErrorFormatter {
protected override string ErrorTitle {
get { return SR.GetString(SR.PassportAuthFailed_Title);}
}
protected override string Description {
get { return SR.GetString(SR.PassportAuthFailed_Description);}
}
protected override string MiscSectionTitle {
get { return SR.GetString(SR.Assess_Denied_Title);}
}
protected override string MiscSectionContent {
get { return null;}
}
protected override string ColoredSquareTitle {
get { return null;}
}
protected override string ColoredSquareContent {
get { return null;}
}
protected override bool ShowSourceFileInfo {
get { return false;}
}
}
}
// File provided for Reference Use Only by Microsoft Corporation (c) 2007.
//------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//-----------------------------------------------------------------------------
/*
* PassportAuthenticationModule class
*
* Copyright (c) 1999 Microsoft Corporation
*/
namespace System.Web.Security {
using System.Web;
using System.Security.Principal;
using System.Web.Configuration;
using System.Web.Handlers;
using System.Globalization;
using System.Security.Permissions;
using System.Web.Management;
///
/// This
/// module provides a wrapper around passport authentication services.
///
[AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)]
public sealed class PassportAuthenticationModule : IHttpModule {
private PassportAuthenticationEventHandler _eventHandler;
private static bool _fAuthChecked = false;
private static bool _fAuthRequired = false;
private static String _LoginUrl = null;
///
///
/// Initializes a new instance of the
/// class.
///
///
[SecurityPermission(SecurityAction.Demand, Unrestricted=true)]
public PassportAuthenticationModule() {
}
////////////////////////////////////////////////////////////
// AddOnAuthenticate and RemoveOnAuthenticate: Use these
// methods to hook up event handlers to handle the
// OnAuthenticate Event
///
/// This is a global.asax event that must be
/// named PassportAuthenticate_OnAuthenticate event.
///
public event PassportAuthenticationEventHandler 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);
app.EndRequest += new EventHandler(this.OnLeave);
}
////////////////////////////////////////////////////////////
// OnAuthenticate: Custom Authentication modules can override
// this method to create a custom IPrincipal object from
// a PassportIdentity
///
/// Calls the
/// PassportAuthentication_OnAuthenticate handler, if one exists.
///
void OnAuthenticate(PassportAuthenticationEventArgs e) {
////////////////////////////////////////////////////////////
// If there are event handlers, invoke the handlers
if (_eventHandler != null) {
_eventHandler(this, e);
if (e.Context.User == null && e.User != null)
{
InternalSecurityPermissions.ControlPrincipal.Demand();
e.Context.User = e.User;
}
}
////////////////////////////////////////////////////////////
// Default Implementation: If IPrincipal has not been created,
// create a PassportUser
if (e.Context.User == null)
{
InternalSecurityPermissions.ControlPrincipal.Demand();
e.Context.User = new PassportPrincipal(e.Identity, new String[0]);
}
}
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Methods for internal implementation
///
///
///
void OnEnter(Object source, EventArgs eventArgs) {
if (_fAuthChecked && !_fAuthRequired)
return;
HttpApplication app;
HttpContext context;
app = (HttpApplication)source;
context = app.Context;
if (!_fAuthChecked) {
AuthenticationSection settings = RuntimeConfig.GetAppConfig().Authentication;
settings.ValidateAuthenticationMode();
_fAuthRequired = (settings.Mode == AuthenticationMode.Passport);
_LoginUrl = settings.Passport.RedirectUrl;
_fAuthChecked = true;
}
if (!_fAuthRequired)
return;
////////////////////////////////////////////////////////
// Step 1: See if this request is valid or not
// VSWhidbey 442515: We no longer need to do this check, always proceed
////////////////////////////////////////////////////////
// Step 2: Create a Passport Identity from the credentials
// from IIS
PassportIdentity identity = new PassportIdentity();
////////////////////////////////////////////////////////
// Step 4: Call OnAuthenticate virtual method to create
// an IPrincipal for this request
OnAuthenticate( new PassportAuthenticationEventArgs(identity, context) );
////////////////////////////////////////////////////////
// Skip AuthZ if accessing the login page
context.SetSkipAuthorizationNoDemand(AuthenticationConfig.AccessingLoginPage(context, _LoginUrl), false /*managedOnly*/);
if (!context.SkipAuthorization) {
context.SkipAuthorization = AssemblyResourceLoader.IsValidWebResourceRequest(context);
}
}
void OnLeave(Object source, EventArgs eventArgs) {
HttpApplication app;
HttpContext context;
app = (HttpApplication)source;
context = app.Context;
if (!_fAuthChecked || !_fAuthRequired || context.User == null || context.User.Identity == null || !(context.User.Identity is PassportIdentity))
return;
PassportIdentity id = (PassportIdentity) context.User.Identity;
if (context.Response.StatusCode != 401 || id.WWWAuthHeaderSet)
return;
if ( _LoginUrl==null || _LoginUrl.Length < 1 || String.Compare(_LoginUrl, "internal", StringComparison.Ordinal) == 0) {
context.Response.Clear();
context.Response.StatusCode = 200;
if (!ErrorFormatter.RequiresAdaptiveErrorReporting(context)) {
String strUrl = context.Request.Url.ToString();
int iPos = strUrl.IndexOf('?');
if (iPos >= 0) {
strUrl = strUrl.Substring(0, iPos);
}
String strLogoTag = id.LogoTag2(HttpUtility.UrlEncode(strUrl, context.Request.ContentEncoding));
String strMsg = SR.GetString(SR.PassportAuthFailed, strLogoTag);
context.Response.Write(strMsg);
}
else {
ErrorFormatter errorFormatter = new PassportAuthFailedErrorFormatter();
context.Response.Write(errorFormatter.GetAdaptiveErrorMessage(context, true));
}
}
else {
////////////////////////////////////////////////////////////
// Step 1: Get the redirect url
String redirectUrl = AuthenticationConfig.GetCompleteLoginUrl(context, _LoginUrl);
////////////////////////////////////////////////////////////
// Step 2: Check if we have a valid url to the redirect-page
if (redirectUrl == null || redirectUrl.Length <= 0)
throw new HttpException(SR.GetString(SR.Invalid_Passport_Redirect_URL));
////////////////////////////////////////////////////////////
// Step 3: Construct the redirect-to url
String strUrl = context.Request.Url.ToString();
String strRedirect;
int iIndex;
String strSep;
if (redirectUrl.IndexOf('?') >= 0)
strSep = "&";
else
strSep = "?";
strRedirect = redirectUrl + strSep + "ReturnUrl=" + HttpUtility.UrlEncode(strUrl, context.Request.ContentEncoding);
////////////////////////////////////////////////////////////
// Step 4: Add the query-string from the current url
iIndex = strUrl.IndexOf('?');
if (iIndex >= 0 && iIndex < strUrl.Length-1)
strRedirect += "&" + strUrl.Substring(iIndex+1);
////////////////////////////////////////////////////////////
// Step 5: Do the redirect
context.Response.Redirect(strRedirect, false);
}
}
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// ErrorFormatter for generating adaptive error for mobile devices
internal class PassportAuthFailedErrorFormatter : ErrorFormatter {
protected override string ErrorTitle {
get { return SR.GetString(SR.PassportAuthFailed_Title);}
}
protected override string Description {
get { return SR.GetString(SR.PassportAuthFailed_Description);}
}
protected override string MiscSectionTitle {
get { return SR.GetString(SR.Assess_Denied_Title);}
}
protected override string MiscSectionContent {
get { return null;}
}
protected override string ColoredSquareTitle {
get { return null;}
}
protected override string ColoredSquareContent {
get { return null;}
}
protected override bool ShowSourceFileInfo {
get { return false;}
}
}
}
// File provided for Reference Use Only by Microsoft Corporation (c) 2007.
Link Menu

This book is available now!
Buy at Amazon US or
Buy at Amazon UK
- IDQuery.cs
- CacheForPrimitiveTypes.cs
- InkCanvasFeedbackAdorner.cs
- ItemsPresenter.cs
- EDesignUtil.cs
- RegexMatchCollection.cs
- SqlWebEventProvider.cs
- DebuggerService.cs
- MetadataProperty.cs
- CultureTable.cs
- DesignerSerializationOptionsAttribute.cs
- BufferedWebEventProvider.cs
- EditorAttribute.cs
- WindowsProgressbar.cs
- VersionedStreamOwner.cs
- EmptyControlCollection.cs
- CompositeControlDesigner.cs
- NameValuePermission.cs
- MetadataHelper.cs
- diagnosticsswitches.cs
- QuadraticBezierSegment.cs
- TypedReference.cs
- SemaphoreFullException.cs
- MarkupObject.cs
- SystemIcmpV6Statistics.cs
- PropertyEntry.cs
- HandlerBase.cs
- HtmlInputHidden.cs
- InstanceCreationEditor.cs
- ServiceMemoryGates.cs
- SqlCrossApplyToCrossJoin.cs
- IsolatedStorageFileStream.cs
- XmlText.cs
- SymLanguageType.cs
- DataPagerFieldCollection.cs
- ClientTargetSection.cs
- XmlIncludeAttribute.cs
- IpcManager.cs
- SecurityState.cs
- ScriptingScriptResourceHandlerSection.cs
- RegexGroup.cs
- TrackingWorkflowEventArgs.cs
- WebPartConnectionsEventArgs.cs
- SessionStateContainer.cs
- ActivityDesignerLayoutSerializers.cs
- GridViewPageEventArgs.cs
- XmlSchemaChoice.cs
- Type.cs
- AnnotationAuthorChangedEventArgs.cs
- TextFormatter.cs
- Pair.cs
- RenderOptions.cs
- Animatable.cs
- SyndicationCategory.cs
- Odbc32.cs
- EmptyEnumerable.cs
- SpotLight.cs
- EditorPartCollection.cs
- HttpResponse.cs
- AttachedPropertyBrowsableWhenAttributePresentAttribute.cs
- ShapingWorkspace.cs
- CatalogPartChrome.cs
- ClientScriptManager.cs
- BulletedListEventArgs.cs
- LocalizabilityAttribute.cs
- BinaryOperationBinder.cs
- DataServiceHost.cs
- ScriptingRoleServiceSection.cs
- DiscoveryReference.cs
- ClockController.cs
- EntityDataSourceWizardForm.cs
- FontStyleConverter.cs
- PostBackTrigger.cs
- PowerStatus.cs
- WebPartManagerInternals.cs
- PolicyLevel.cs
- GradientStopCollection.cs
- Deserializer.cs
- CompiledRegexRunner.cs
- ResourceWriter.cs
- SqlColumnizer.cs
- GeneralTransformGroup.cs
- XsdValidatingReader.cs
- Bezier.cs
- VSDExceptions.cs
- ListGeneralPage.cs
- TreeViewItemAutomationPeer.cs
- WebBrowserSiteBase.cs
- Sql8ConformanceChecker.cs
- FileSystemInfo.cs
- EventManager.cs
- IUnknownConstantAttribute.cs
- ICollection.cs
- InputReportEventArgs.cs
- ContentValidator.cs
- ReadOnlyDictionary.cs
- StylusEventArgs.cs
- DynamicQueryableWrapper.cs
- CodeAccessSecurityEngine.cs
- ServicePointManagerElement.cs