Export (0) Print
Expand All

WSFederationAuthenticationModule Class

.NET Framework 4.5

The WSFederationAuthenticationModule is an HTTP module which is used to secure an ASP.NET application by enforcing federated authentication settings on incoming requests. The WSFederationAuthenticationModule is the main module that WIF offers out of the box for handling claims-based identity access in ASP.NET applications.

The WSFederationAuthenticationModule raises several events, which allows ASP.NET developers to change the default behavior and control the details of how authentication and claims processing take place. The WSFederationAuthenticationModule functionality is divided into task-specific methods.

System.Object
  System.IdentityModel.Services.HttpModuleBase
    System.IdentityModel.Services.WSFederationAuthenticationModule

Namespace:  System.IdentityModel.Services
Assembly:  System.IdentityModel.Services (in System.IdentityModel.Services.dll)

type WSFederationAuthenticationModule =  
    class 
        inherit HttpModuleBase 
    end

The WSFederationAuthenticationModule type exposes the following members.

  NameDescription
Public methodWSFederationAuthenticationModuleCalled by constructors in derived classes to initialize the WSFederationAuthenticationModule class.
Top

  NameDescription
Public propertyAuthenticationTypeGets or sets the value of the wauth parameter to use in WS-Federation sign-in requests (“wsignin1.0”).
Public propertyFederationConfigurationGets or sets the FederationConfiguration object that is in effect for the current module. (Inherited from HttpModuleBase.)
Public propertyFreshnessGets or sets the value of the wfresh parameter to use in WS-Federation sign-in requests (“wsignin1.0”).
Public propertyHomeRealmGets or sets the value of the whr parameter to use in WS-Federation sign-in requests (“wsignin1.0”).
Public propertyIssuerGets or sets a URI that identifies the intended issuer of the security token.
Public propertyPassiveRedirectEnabledGets or sets a value that specifies whether the module is enabled to initiate WS-Federation protocol redirects.
Public propertyPersistentCookiesOnPassiveRedirectsGets or sets a value that specifies whether a persistent session cookie is issued on successful authentication.
Public propertyPolicyGets or sets the value of the wp parameter to be used in WS-Federation sign-in requests (“wsignin1.0”).
Public propertyRealmGets or sets the value of the wtrealm parameter to be used for WS-Federation sign-in requests (“wsignin1.0”).
Public propertyReplyGets or sets the value of the wreply parameter to use in WS-Federation sign-in requests (“wsignin1.0”).
Public propertyRequestGets or sets the value of the wreq parameter to use in WS-Federation sign-in requests (“wsignin1.0”).
Public propertyRequestPtrGets or sets the value of the wreqptr parameter to use in WS-Federation sign-in requests (“wsignin1.0”).
Public propertyRequireHttpsGets or sets a value that specifies whether communication with the security token service (STS) must use HTTPS protocol.
Public propertyResourceGet or sets the value of the wres parameter to use in WS-Federation sign-in requests (“wsignin1.0”).
Public propertySignInContextGest or sets an application specific context value to be included in the wctx parameter in WS-Federation sign-in requests.
Public propertySignInQueryStringGets or sets a query string that contains any additional parameters to be sent in WS-Federation sign-in requests (“wsignin1.0”).
Public propertySignOutQueryStringGets or sets a query string that contains any additional parameters to be sent in WS-Federation sign-out requests (“wsignout1.0”).
Public propertySignOutReplyGets or sets the value of the wreply parameter to use during WS-Federation sign-out requests (“wsignout1.0”).
Public propertyXmlDictionaryReaderQuotasGets or sets the XmlDictionaryReaderQuotas object to use when deserializing WS-Federation sign-in response messages to get the token issued by the security token service (STS).
Top

  NameDescription
Public methodCanReadSignInResponse(HttpRequestBase)Returns a value that indicates whether the specified HTTP request is a WS-Federation sign-in response message. If the message is a WS-Federation sign-out clean-up message (“wsignoutcleanup1.0”), this method processes the request.
Public methodCanReadSignInResponse(HttpRequestBase, Boolean)Returns a value that indicates whether the specified HTTP request is a WS-Federation sign-in response message. If the message is a WS-Federation sign-out clean-up message (“wsignoutcleanup1.0”), this method processes the request.
Public methodCreateSignInRequestCreates a WS-Federation sign in request message by using the WS-Federation parameters configured on the module.
Public methodDisposeReleases the resources (except memory) used by the current instance of the HttpModuleBase class. (Inherited from HttpModuleBase.)
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Public methodStatic memberFederatedSignOutSigns out at the specified security token service (STS) by using the WS-Federation protocol.
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodStatic memberGetFederationPassiveSignOutUrlReturns a URL that represents a WS-Federation sign-out request addressed to the specified issuer and that contains the specified wreply parameter and the specified additional parameters.
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Protected methodGetReferencedResultGets the issuance result (typically the issued token) from the specified URL. Resolves the URL specified in the wresultptr parameter in a sign-in response message.
Protected methodGetReturnUrlFromResponseExtracts the URL of the page that was originally requested from the sign-in response.
Public methodGetSecurityToken(HttpRequestBase)Reads a security token from the specified HTTP request.
Public methodGetSecurityToken(SignInResponseMessage)Reads a security token from the specified WS Federation sign-in response message.
Protected methodGetSessionTokenContextGets a string that should be persisted with the session cookie in the SessionSecurityToken.Context property.
Public methodGetSignInResponseMessageReads a SignInResponseMessage object from the form POST represented by the specified HTTP request.
Protected methodGetSignOutRedirectUrlDetermines the URL to which to redirect when processing a WS-Federation sign-out clean-up request (wsignoutcleanup1.0) that contains a wreply parameter.
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodGetXmlTokenFromMessage(SignInResponseMessage)Extracts the issued token from the specified WS-Federation sign-in response message.
Public methodGetXmlTokenFromMessage(SignInResponseMessage, WSFederationSerializer)Extracts the issued token from the specified WS-Federation sign-in response message by using the specified WS-Federation serializer.
Public methodInitInitializes the HTTP module. (Inherited from HttpModuleBase.)
Protected methodInitializeModuleInitializes the module and prepares it to handle events from the module's ASP.NET application object. (Overrides HttpModuleBase.InitializeModule(HttpApplication).)
Protected methodInitializePropertiesFromConfigurationInitializes the module properties based on the configuration specified by the FederationConfiguration property of the module. (Overrides HttpModuleBase.InitializePropertiesFromConfiguration().)
Public methodIsSignInResponseGets a value that indicates whether the specified request is a WS-Federation sign-in response message.
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Protected methodOnAuthenticateRequestHandles the HttpApplication.AuthenticateRequest event from the ASP.NET pipeline.
Protected methodOnAuthorizationFailedRaises the AuthorizationFailed event.
Protected methodOnEndRequestHandles the HttpApplication.EndRequest event from the ASP.NET pipeline.
Protected methodOnPostAuthenticateRequestHandles the HttpApplication.PostAuthenticateRequest event from the ASP.NET pipeline.
Protected methodOnRedirectingToIdentityProviderRaises the RedirectingToIdentityProvider event.
Protected methodOnSessionSecurityTokenCreatedRaises the SessionSecurityTokenCreated event.
Protected methodOnSignedInRaises the SignedIn event.
Protected methodOnSignedOutRaises the SignedOut event.
Protected methodOnSignInErrorRaises the SignInError event.
Protected methodOnSigningOutRaises the SigningOut event.
Protected methodOnSignOutErrorRaises the SignOutError event.
Public methodRedirectToIdentityProviderRedirects the user to the security token service (STS) specified by the Issuer property to obtain a security token using the WS-Federation protocol.
Public methodSetPrincipalAndWriteSessionTokenSets the thread principal and optionally writes the session cookie.
Public methodSignInPerforms sign-in to a security token service (STS) through the WS-Federation protocol.
Public methodSignOut()Signs out of the current session and requests a redirect back to the URL specified in the current HTTP request.
Public methodSignOut(Boolean)Signs out of the current session and raises the appropriate events.
Public methodSignOut(String)Signs out of the current session and requests a redirect back to the specified URL.
Public methodSignOut(String, Boolean)Signs out of the current session and requests a redirect back to the specified URL.
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Public methodVerifyPropertiesVerifies that the Issuer and Realm properties are non-empty, and, that, if the RequireHttps property is true, that the URIs specified for Issuer and Realm are HTTPS-compliant.
Top

  NameDescription
Public eventAuthorizationFailedOccurs when the module is determining whether it should redirect the user to the configured issuer to authenticate.
Public eventRedirectingToIdentityProviderOccurs when the module is going to redirect the user to the identity provider.
Public eventSecurityTokenReceivedOccurs when a security token has been received from a security token service (STS).
Public eventSecurityTokenValidatedOccurs after a security token that was received from the security token service (STS) has been validated but before the session security token is created.
Public eventSessionSecurityTokenCreatedOccurs when a session security token has been created from the security token received from a security token service (STS).
Public eventSignedInOccurs after the user is signed in.
Public eventSignedOutOccurs just after deleting the session during sign-out.
Public eventSignInErrorRaised when an error during sign-in occurs.
Public eventSigningOutOccurs before deleting the session during sign-out.
Public eventSignOutErrorRaised when an error occurs during sign-out.
Top

The WSFederationAuthenticationModule class implements an HTTP module known as the WS-Federation Authentication Module (WSFAM). The WSFAM is implemented out of the box by Windows Identity Foundation (WIF). The WSFAM is added to the ASP.NET pipeline by making an entry in the web.config file. It derives from HttpModuleBase, which implements IHttpModule. It registers with the ASP.NET runtime to listen for the EndRequest and AuthenticateRequest events. Listening to the EndRequest event, lets the WSFAM redirect clients to a security token service (STS) to obtain a security token when authorization fails on a requested resource. Listening to the AuthenticateRequest event enables the WSFAM to monitor HTTP requests for a response from the STS that contains the requested token. When such a token is present and valid, it creates an instance of ClaimsPrincipal for the authenticated user using the claims that are present in the token.

When using the WSFAM, session management is provided by a session authentication module (SAM), which is an instance of the SessionAuthenticationModule class, or a class derived from it. The SAM is also added to the ASP.NET pipeline in the configuration file. The SAM monitors requests for authentication (session) cookies. When these cookies are present and valid, the module extracts the ClaimsPrincipal for the authenticated user from the SessionSecurityToken and sets the HttpContext.User property and the thread principal Thread.CurrentPrincipal properties.

The WSFAM provides:

  • The ability for an ASP.NET application to outsource authentication to a security token service (STS) by using the WS-Federation protocol. Identity can be federated across one or more identity realms and involve multiple STSs.

  • Claims-based identity for ASP.NET applications. During authentication, the WSFAM builds a principal from the claims in the security token sent by the STS and sets this claims principal as the thread principal. You can then use this principal to make further authorization, presentation, and logic decisions about the user it represents in your code.

The WSFAM exposes several properties that provide default message parameters to use on WS-Federation sign-in and sign-out requests. These properties are typically initialized from the <wsFederation> element in a configuration file. The most important of these properties are:

  • The Issuer property, which specifies the address of the security token service (STS) to which to send WS-Federation sign-in and sign-out requests.

  • The Realm property, which specifies the wtrealm parameter to use in WS-Federation sign-in requests. The wtrealm parameter identifies the security realm of the relying party (RP) application to the STS.

Sign-in message parameters can also be changed on a per-request basis by providing an event-handler delegate for the RedirectingToIdentityProvider event.

Two properties control the behavior of the module. Both of these properties are also typically initialized from the <wsFederation> element in configuration.

  • The PassiveRedirectEnabled property specifies whether the module should perform passive redirects to the STS for authentication.

  • The PersistentCookiesOnPassiveRedirects property specifies whether sessions should be persistent. If this property is set true, the SAM is used to write a session cookie to the client. On subsequent requests from the client, the SAM provides authentication by using the token persisted in the session cookie.

The WSFAM raises several events during sign-in and sign-out, which allow ASP.NET developers to change the default behavior of the module and control the details of how authentication and claims processing take place.

The following events are raised before the WS-Federation sign-in request is sent to the STS:

  • AuthorizationFailed: Raised when passive redirect is enabled and authorization fails on a requested resource.

  • RedirectingToIdentityProvider: Raised just before the WSFAM sends the WS-Federation sign-in request to the STS. You can use this event to change the parameters in the sign-in request.

The following events are raised when a sign-in response (issued security token) is received from the STS:

  • SecurityTokenReceived: Raised just after the security token sent by the STS is read from the response.

  • SecurityTokenValidated: Raised just after the token has been validated. You can use this event to filter, transform, or add claims to the claims principal (ClaimsPrincipal) created from the security token.

  • SessionSecurityTokenCreated: Raised just before the session token (SessionSecurityToken) created from the claims principal is used to set the thread principal and current user and is written to the session cookie. Gives you an opportunity to modify the session token or enable or disable writing the session cookie.

  • SignedIn: Raised at the end of the authentication just after the thread principal and current user have been set.

  • SignInError: Raised if an exception occurs during sign-in. You can cancel the request and prevent the exception from being returned to the caller.

When signing out of a session or when processing a WS-Federation sign-out clean-up request (wsignoutcleanup1.0), the following events are raised:

  • SigningOut: Raised just before the session is deleted to enable you to perform any cleanup that might depend on the session or to cancel sign-out.

  • SignedOut: Raised just after the session has been deleted.

  • SignOutError: Raised if an exception occurs during sign-out. You can cancel sign-out and prevent the exception from being returned to the caller.

NoteNote

The sign-out events are not raised when signing out at the STS by calling the FederatedSignOut method.

There are two ways of signing in to an STS using WSFAM. The first is by enabling passive redirects through the PassiveRedirectEnabled property. In this case, when authorization fails on a requested resource, rather than returning a 401:Access Denied response to the client, WSFAM builds a WS-Federation sign-in request message from its properties and redirects the client to the STS to retrieve a security token. The second way is to explicitly redirect the client to the STS by calling the SignIn method from a web page or custom control in your application. The SignIn method also uses the properties of the WSFAM to construct the sign-in request.

Any of the overloaded SignOut methods can be used to sign out of the session. This deletes the session cookie on the client. It does not send a WS-Federation sign-out message (“wsignout1.0”) to the STS. To sign-out at the STS, you must use the FederatedSignOut method.

The WSFAM handles WS-Federation sign-out clean-up requests (“wsignoutcleanup1.0”), by deleting its session with the client. If the wreply parameter in the sign-out clean-up message is not set, the WSFAM returns an image of a green check mark to the STS that sent the message. This feature can be used by an STS as an acknowledgment that the RP has completed its sign-out.

The WSFAM exposes its functionality -- for example, its request processing pipeline -- through several task-specific methods. You can override these methods in derived classes to alter the behavior of the WSFAM.

To be used, the module must be added to the pipeline as in the following XML:

<configuration>
  <system.webServer>
    <modules>
      <add name="WsFederationAuthenticationModule" type="System.IdentityModel.Services.WSFederationAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
    </modules>
  </system.webServer>
</configuration>

Once configured, the WSFederationAuthenticationModule raises events at various stages of processing an HTTP request. ASP.NET developers can handle these events in the global.asax file.


        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup 

            //SUBSCRIBE TO WSFAM EVENTS
            FederatedAuthentication.WSFederationAuthenticationModule.AuthorizationFailed += new EventHandler<AuthorizationFailedEventArgs>(WSFederationAuthenticationModule_AuthorizationFailed);
            FederatedAuthentication.WSFederationAuthenticationModule.RedirectingToIdentityProvider += new EventHandler<RedirectingToIdentityProviderEventArgs>(WSFederationAuthenticationModule_RedirectingToIdentityProvider);
            FederatedAuthentication.WSFederationAuthenticationModule.SecurityTokenReceived += new EventHandler<SecurityTokenReceivedEventArgs>(WSFederationAuthenticationModule_SecurityTokenReceived);
            FederatedAuthentication.WSFederationAuthenticationModule.SecurityTokenValidated += new EventHandler<SecurityTokenValidatedEventArgs>(WSFederationAuthenticationModule_SecurityTokenValidated);
            FederatedAuthentication.WSFederationAuthenticationModule.SessionSecurityTokenCreated += new EventHandler<SessionSecurityTokenCreatedEventArgs>(WSFederationAuthenticationModule_SessionSecurityTokenCreated);
            FederatedAuthentication.WSFederationAuthenticationModule.SignedIn += new EventHandler(WSFederationAuthenticationModule_SignedIn);
        }

        void WSFederationAuthenticationModule_SignedIn(object sender, EventArgs e)
        {
            //Anything that's needed right after succesful session and before hitting the application code goes here
            System.Diagnostics.Trace.WriteLine("Handling SignIn event");
        }

        void WSFederationAuthenticationModule_SessionSecurityTokenCreated(object sender, SessionSecurityTokenCreatedEventArgs e)
        {
            //Manipulate session token here, for example, changing its expiration value
            System.Diagnostics.Trace.WriteLine("Handling SessionSecurityTokenCreated event");
            System.Diagnostics.Trace.WriteLine("Key valid from: " + e.SessionToken.KeyEffectiveTime);
            System.Diagnostics.Trace.WriteLine("Key expires on: " + e.SessionToken.KeyExpirationTime);
        }

        void WSFederationAuthenticationModule_SecurityTokenValidated(object sender, SecurityTokenValidatedEventArgs e)
        {
            //All vlidation SecurityTokenHandler checks are successful
            System.Diagnostics.Trace.WriteLine("Handling SecurityTokenValidated event");
        }

        void WSFederationAuthenticationModule_SecurityTokenReceived(object sender, SecurityTokenReceivedEventArgs e)
        {
            //Augment token validation with your cusotm validation checks without invalidating the token.
            System.Diagnostics.Trace.WriteLine("Handling SecurityTokenReceived event");
        }

        void WSFederationAuthenticationModule_AuthorizationFailed(object sender, AuthorizationFailedEventArgs e)
        {
            //Use this event to report more details regarding the ahorization failure
            System.Diagnostics.Trace.WriteLine("Handling AuthorizationFailed event");

        }

        void WSFederationAuthenticationModule_RedirectingToIdentityProvider(object sender, RedirectingToIdentityProviderEventArgs e)
        {
            //Use this event to programmatically modify the sign-in message to the STS.
            System.Diagnostics.Trace.WriteLine("Handling RedirectingToIdentityProvider event");
        }

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show:
© 2014 Microsoft