Code:
/ Dotnetfx_Win7_3.5.1 / Dotnetfx_Win7_3.5.1 / 3.5.1 / DEVDIV / depot / DevDiv / releases / Orcas / NetFXw7 / ndp / fx / src / xsp / System / Web / Extensions / ApplicationServices / AuthenticationService.cs / 1 / AuthenticationService.cs
//------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//-----------------------------------------------------------------------------
namespace System.Web.ApplicationServices {
using System;
using System.Diagnostics.CodeAnalysis;
using System.Security.Permissions;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Web;
using System.Web.Management;
using System.Web.Resources;
using System.Web.Security;
///
/// Implements login service contract to be exposed as a WCF service. Uses Membership provider
/// or custom authentication login in the Authenticating event. Also uses Forms.SetAuthCookie() or
/// custom cookie generation via the CreatingCookie event.
///
[
AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required),
AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal),
AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal),
ServiceContract(Namespace="http://asp.net/ApplicationServices/v200"),
ServiceBehavior(Namespace="http://asp.net/ApplicationServices/v200", InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)
]
public class AuthenticationService {
///
/// Raised to authenticate the user . The event handler sets the e.AuthenticationIsComplete flag to true
/// and e.Authenticated to the result.
///
private static object _authenticatingEventHandlerLock = new object();
private static EventHandler _authenticating;
public static event EventHandler Authenticating {
add {
lock (_authenticatingEventHandlerLock) {
_authenticating += value;
}
}
remove {
lock (_authenticatingEventHandlerLock) {
_authenticating -= value;
}
}
}
///
/// Raised to create and set the cookie. The event handler shouldset the e.CookieIsSet flag to true, if it is
/// setting the cookie.
///
private static object _creatingCookieEventHandlerLock = new object();
private static EventHandler _creatingCookie;
public static event EventHandler CreatingCookie {
add {
lock (_creatingCookieEventHandlerLock) {
_creatingCookie += value;
}
}
remove {
lock (_creatingCookieEventHandlerLock) {
_creatingCookie -= value;
}
}
}
//hiding constructors
internal AuthenticationService() {
}
///
/// Raises the AuthentincatingEvent if atleast one handler is assigned.
///
private void OnAuthenticating(AuthenticatingEventArgs e) {
EventHandler handler = _authenticating;
if (null != handler) {
handler(this, e);
}
}
///
/// Raises the CreatingCookieEvent if atleast one handler is assigned.
///
private void OnCreatingCookie(CreatingCookieEventArgs e) {
EventHandler handler = _creatingCookie;
if (null != handler) {
handler(this, e);
}
}
///
/// Validates user credentials,without actually setting the FormAuth cookie
///
/// Username of the account
/// Password of the account
/// Any misc. string to be used by custom authentication logic
/// True, if credentials are valid, otherwise false
[OperationContract]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId="username", Justification="consistent with Whidbey")]
public bool ValidateUser(string username, string password, string customCredential) {
ApplicationServiceHelper.EnsureAuthenticationServiceEnabled(HttpContext.Current, true);
return LoginInternal(username, password, customCredential, false, false);
}
///
/// Validates user credentials,and sets the FormAuth cookie if the credentials are valid.
///
/// Username of the account
/// Password of the account
/// Any misc. string to be used by custom authentication logic
/// If true the persistant cookie is generated.
/// True, if credentials are valid, otherwise false
[OperationContract]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId="username", Justification="consistent with Whidbey")]
public bool Login(string username, string password, string customCredential, bool isPersistent) {
ApplicationServiceHelper.EnsureAuthenticationServiceEnabled(HttpContext.Current, true);
return LoginInternal(username, password, customCredential, isPersistent, true);
}
///
/// Checks whether the Forms Authentication cookie attached to the request is valid.
///
[OperationContract]
public bool IsLoggedIn() {
ApplicationServiceHelper.EnsureAuthenticationServiceEnabled(HttpContext.Current, true);
return HttpContext.Current.User.Identity.IsAuthenticated;
}
///
/// Clears the Forms Authentication cookie
///
[OperationContract]
public void Logout() {
ApplicationServiceHelper.EnsureAuthenticationServiceEnabled(HttpContext.Current, false);
FormsAuthentication.SignOut();
}
///
/// Validates the user credentials.
///
///
///
///
///
/// If this is true, CreatingCookie event is raised, and cookie is set in HttpResponse
///
private bool LoginInternal(string username, string password, string customCredential, bool isPersistent, bool setCookie) {
if (null == username) {
throw new ArgumentNullException("username");
}
if (null == password) {
throw new ArgumentNullException("password");
}
AuthenticatingEventArgs authEventArgs = new AuthenticatingEventArgs(username, password, customCredential);
try {
OnAuthenticating(authEventArgs);
if (!authEventArgs.AuthenticationIsComplete) {
MembershipValidate(authEventArgs);
}
if (!authEventArgs.Authenticated) {
Logout();
}
if (authEventArgs.Authenticated && setCookie) {
CreatingCookieEventArgs cookieEventArgs = new CreatingCookieEventArgs(username, password, isPersistent, customCredential);
OnCreatingCookie(cookieEventArgs);
if (!cookieEventArgs.CookieIsSet) {
SetCookie(username, isPersistent);
}
}
}
catch (Exception e) {
LogException(e);
throw;
}
return authEventArgs.Authenticated;
}
private static void MembershipValidate(AuthenticatingEventArgs e) {
e.Authenticated = Membership.ValidateUser(e.UserName, e.Password);
}
private static void SetCookie(string username, bool isPersistent) {
FormsAuthentication.SetAuthCookie(username, isPersistent);
}
private void LogException(Exception e) {
WebServiceErrorEvent errorevent = new WebServiceErrorEvent(AtlasWeb.UnhandledExceptionEventLogMessage, this, e);
errorevent.Raise();
}
}
}
// File provided for Reference Use Only by Microsoft Corporation (c) 2007.
//------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//-----------------------------------------------------------------------------
namespace System.Web.ApplicationServices {
using System;
using System.Diagnostics.CodeAnalysis;
using System.Security.Permissions;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Web;
using System.Web.Management;
using System.Web.Resources;
using System.Web.Security;
///
/// Implements login service contract to be exposed as a WCF service. Uses Membership provider
/// or custom authentication login in the Authenticating event. Also uses Forms.SetAuthCookie() or
/// custom cookie generation via the CreatingCookie event.
///
[
AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required),
AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal),
AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal),
ServiceContract(Namespace="http://asp.net/ApplicationServices/v200"),
ServiceBehavior(Namespace="http://asp.net/ApplicationServices/v200", InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)
]
public class AuthenticationService {
///
/// Raised to authenticate the user . The event handler sets the e.AuthenticationIsComplete flag to true
/// and e.Authenticated to the result.
///
private static object _authenticatingEventHandlerLock = new object();
private static EventHandler _authenticating;
public static event EventHandler Authenticating {
add {
lock (_authenticatingEventHandlerLock) {
_authenticating += value;
}
}
remove {
lock (_authenticatingEventHandlerLock) {
_authenticating -= value;
}
}
}
///
/// Raised to create and set the cookie. The event handler shouldset the e.CookieIsSet flag to true, if it is
/// setting the cookie.
///
private static object _creatingCookieEventHandlerLock = new object();
private static EventHandler _creatingCookie;
public static event EventHandler CreatingCookie {
add {
lock (_creatingCookieEventHandlerLock) {
_creatingCookie += value;
}
}
remove {
lock (_creatingCookieEventHandlerLock) {
_creatingCookie -= value;
}
}
}
//hiding constructors
internal AuthenticationService() {
}
///
/// Raises the AuthentincatingEvent if atleast one handler is assigned.
///
private void OnAuthenticating(AuthenticatingEventArgs e) {
EventHandler handler = _authenticating;
if (null != handler) {
handler(this, e);
}
}
///
/// Raises the CreatingCookieEvent if atleast one handler is assigned.
///
private void OnCreatingCookie(CreatingCookieEventArgs e) {
EventHandler handler = _creatingCookie;
if (null != handler) {
handler(this, e);
}
}
///
/// Validates user credentials,without actually setting the FormAuth cookie
///
/// Username of the account
/// Password of the account
/// Any misc. string to be used by custom authentication logic
/// True, if credentials are valid, otherwise false
[OperationContract]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId="username", Justification="consistent with Whidbey")]
public bool ValidateUser(string username, string password, string customCredential) {
ApplicationServiceHelper.EnsureAuthenticationServiceEnabled(HttpContext.Current, true);
return LoginInternal(username, password, customCredential, false, false);
}
///
/// Validates user credentials,and sets the FormAuth cookie if the credentials are valid.
///
/// Username of the account
/// Password of the account
/// Any misc. string to be used by custom authentication logic
/// If true the persistant cookie is generated.
/// True, if credentials are valid, otherwise false
[OperationContract]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId="username", Justification="consistent with Whidbey")]
public bool Login(string username, string password, string customCredential, bool isPersistent) {
ApplicationServiceHelper.EnsureAuthenticationServiceEnabled(HttpContext.Current, true);
return LoginInternal(username, password, customCredential, isPersistent, true);
}
///
/// Checks whether the Forms Authentication cookie attached to the request is valid.
///
[OperationContract]
public bool IsLoggedIn() {
ApplicationServiceHelper.EnsureAuthenticationServiceEnabled(HttpContext.Current, true);
return HttpContext.Current.User.Identity.IsAuthenticated;
}
///
/// Clears the Forms Authentication cookie
///
[OperationContract]
public void Logout() {
ApplicationServiceHelper.EnsureAuthenticationServiceEnabled(HttpContext.Current, false);
FormsAuthentication.SignOut();
}
///
/// Validates the user credentials.
///
///
///
///
///
/// If this is true, CreatingCookie event is raised, and cookie is set in HttpResponse
///
private bool LoginInternal(string username, string password, string customCredential, bool isPersistent, bool setCookie) {
if (null == username) {
throw new ArgumentNullException("username");
}
if (null == password) {
throw new ArgumentNullException("password");
}
AuthenticatingEventArgs authEventArgs = new AuthenticatingEventArgs(username, password, customCredential);
try {
OnAuthenticating(authEventArgs);
if (!authEventArgs.AuthenticationIsComplete) {
MembershipValidate(authEventArgs);
}
if (!authEventArgs.Authenticated) {
Logout();
}
if (authEventArgs.Authenticated && setCookie) {
CreatingCookieEventArgs cookieEventArgs = new CreatingCookieEventArgs(username, password, isPersistent, customCredential);
OnCreatingCookie(cookieEventArgs);
if (!cookieEventArgs.CookieIsSet) {
SetCookie(username, isPersistent);
}
}
}
catch (Exception e) {
LogException(e);
throw;
}
return authEventArgs.Authenticated;
}
private static void MembershipValidate(AuthenticatingEventArgs e) {
e.Authenticated = Membership.ValidateUser(e.UserName, e.Password);
}
private static void SetCookie(string username, bool isPersistent) {
FormsAuthentication.SetAuthCookie(username, isPersistent);
}
private void LogException(Exception e) {
WebServiceErrorEvent errorevent = new WebServiceErrorEvent(AtlasWeb.UnhandledExceptionEventLogMessage, this, e);
errorevent.Raise();
}
}
}
// 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
- IPPacketInformation.cs
- SerializationUtilities.cs
- ReliabilityContractAttribute.cs
- HttpStaticObjectsCollectionWrapper.cs
- coordinator.cs
- RequestNavigateEventArgs.cs
- Variant.cs
- GridViewItemAutomationPeer.cs
- ListDictionaryInternal.cs
- Localizer.cs
- WriteTimeStream.cs
- EpmSourceTree.cs
- StaticFileHandler.cs
- SingleStorage.cs
- ToolZone.cs
- SecurityTokenException.cs
- SimpleMailWebEventProvider.cs
- CipherData.cs
- LayoutExceptionEventArgs.cs
- SendKeys.cs
- DataGridRelationshipRow.cs
- OpCopier.cs
- IMembershipProvider.cs
- ADConnectionHelper.cs
- AnnouncementEndpoint.cs
- AssemblyHash.cs
- HyperLinkField.cs
- DescendentsWalker.cs
- EntityDataReader.cs
- dataprotectionpermission.cs
- RuntimeArgumentHandle.cs
- WeakReferenceKey.cs
- SQLString.cs
- SessionIDManager.cs
- CroppedBitmap.cs
- MD5HashHelper.cs
- SHA1CryptoServiceProvider.cs
- GetCertificateRequest.cs
- OperationPickerDialog.cs
- Calendar.cs
- Listener.cs
- Logging.cs
- HwndMouseInputProvider.cs
- WhereQueryOperator.cs
- ObjectMaterializedEventArgs.cs
- RijndaelCryptoServiceProvider.cs
- LocalizationCodeDomSerializer.cs
- SqlInternalConnectionSmi.cs
- MsmqIntegrationProcessProtocolHandler.cs
- DefaultTextStore.cs
- TopClause.cs
- DockPatternIdentifiers.cs
- InstanceHandleConflictException.cs
- SecurityContextSecurityTokenAuthenticator.cs
- HyperLinkStyle.cs
- StreamSecurityUpgradeAcceptor.cs
- HashStream.cs
- PcmConverter.cs
- SystemIPv6InterfaceProperties.cs
- Adorner.cs
- ZoomPercentageConverter.cs
- DateRangeEvent.cs
- SafeNativeMethodsCLR.cs
- RequestTimeoutManager.cs
- InputLanguageManager.cs
- HtmlTableRow.cs
- SqlBooleanizer.cs
- WebSysDisplayNameAttribute.cs
- StandardMenuStripVerb.cs
- ConnectivityStatus.cs
- SlipBehavior.cs
- ForEachAction.cs
- WebPartsSection.cs
- RectangleGeometry.cs
- CryptoConfig.cs
- DelegatedStream.cs
- Baml2006SchemaContext.cs
- ToolStripControlHost.cs
- ProxyGenerator.cs
- HtmlTable.cs
- NamedPermissionSet.cs
- ConsoleKeyInfo.cs
- EntityDataSourceDesignerHelper.cs
- ByteStack.cs
- MaskedTextBox.cs
- WindowsIPAddress.cs
- DataGridViewRowPrePaintEventArgs.cs
- UiaCoreProviderApi.cs
- HyperLinkStyle.cs
- DeflateEmulationStream.cs
- InputQueue.cs
- Signature.cs
- ZipFileInfoCollection.cs
- AxHostDesigner.cs
- SafeNativeMethodsOther.cs
- ToolStripSplitStackLayout.cs
- WebPartConnectionCollection.cs
- WebSysDefaultValueAttribute.cs
- ObjectPropertyMapping.cs
- CodeGen.cs