SessionAuthenticationModule Classe
Definição
Implementa um módulo do ASP.NET que processa os cookies de sessão em cenários de Web Services Federation.Implements an ASP.NET module that processes session cookies in WS-Federation scenarios.
public ref class SessionAuthenticationModule : System::IdentityModel::Services::HttpModuleBase
public class SessionAuthenticationModule : System.IdentityModel.Services.HttpModuleBase
type SessionAuthenticationModule = class
inherit HttpModuleBase
Public Class SessionAuthenticationModule
Inherits HttpModuleBase
- Herança
Exemplos
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
//SUBSCRIBE TO SAM EVENTS
FederatedAuthentication.SessionAuthenticationModule.SessionSecurityTokenCreated += new EventHandler<SessionSecurityTokenCreatedEventArgs>(SessionAuthenticationModule_SessionSecurityTokenCreated);
FederatedAuthentication.SessionAuthenticationModule.SessionSecurityTokenReceived += new EventHandler<SessionSecurityTokenReceivedEventArgs>(SessionAuthenticationModule_SessionSecurityTokenReceived);
FederatedAuthentication.SessionAuthenticationModule.SigningOut += new EventHandler<SigningOutEventArgs>(SessionAuthenticationModule_SigningOut);
FederatedAuthentication.SessionAuthenticationModule.SignedOut += new EventHandler(SessionAuthenticationModule_SignedOut);
FederatedAuthentication.SessionAuthenticationModule.SignOutError += new EventHandler<ErrorEventArgs>(SessionAuthenticationModule_SignOutError);
}
void SessionAuthenticationModule_SignOutError(object sender, ErrorEventArgs e)
{
System.Diagnostics.Trace.WriteLine("Handling SignOutError event");
}
void SessionAuthenticationModule_SignedOut(object sender, EventArgs e)
{
System.Diagnostics.Trace.WriteLine("Handling SignedOut event");
}
void SessionAuthenticationModule_SigningOut(object sender, SigningOutEventArgs e)
{
System.Diagnostics.Trace.WriteLine("Handling SigningOut event");
}
void SessionAuthenticationModule_SessionSecurityTokenReceived(object sender, SessionSecurityTokenReceivedEventArgs e)
{
System.Diagnostics.Trace.WriteLine("Handling SessionSecurityTokenReceived event");
}
void SessionAuthenticationModule_SessionSecurityTokenCreated(object sender, SessionSecurityTokenCreatedEventArgs e)
{
System.Diagnostics.Trace.WriteLine("Handling SessionSecurityTokenCreated event");
//Store session on the server-side token cache instead writing the whole token to the cookie.
//It may improve throughput but introduces server affinity that may affect scalability
FederatedAuthentication.SessionAuthenticationModule.IsReferenceMode = true;
}
O XML a seguir mostra como configurar o SAM no pipeline ASP.NET.The following XML shows how to configure the SAM in the ASP.NET pipeline. Muitos outros elementos que estão presentes em uma configuração típica são omitidos aqui para fins de brevidade.Many other elements that are present in a typical configuration are omitted here for brevity.
<configuration>
<system.webServer>
<modules>
<!--WIF 4.5 modules -->
<add name="SessionAuthenticationModule" type="System.IdentityModel.Services.SessionAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<add name="WsFederationAuthenticationModule" type="System.IdentityModel.Services.WSFederationAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</modules>
</system.webServer>
</configuration>
Comentários
Quando presente no pipeline do ASP.NET, o SessionAuthenticationModule (Sam) processa cookies de sessão em cenários de WS-Federation.When present in the ASP.NET pipeline, the SessionAuthenticationModule (SAM) processes session cookies in WS-Federation scenarios. Ele usa o manipulador de cookies especificado pela CookieHandler propriedade para ler o cookie de sessão bruto da solicitação HTTP e gravá-lo na resposta http.It uses the cookie handler specified by the CookieHandler property to read the raw session cookie from the HTTP request and write it to the HTTP response. Ele usa o SessionSecurityTokenHandler que está configurado para um aplicativo desserializar o cookie de sessão bruto em SessionSecurityToken objetos.It uses the SessionSecurityTokenHandler that is configured for an application to deserialize the raw session cookie into SessionSecurityToken objects. O token de segurança de sessão contém as declarações ( Claim ) e principal ( ClaimsPrincipal ) associadas à entidade para a qual a solicitação está sendo atendida.The session security token contains the claims (Claim) and principal (ClaimsPrincipal) associated with the entity for which the request is being served.
O SAM adiciona seu OnAuthenticateRequest manipulador de eventos ao HttpApplication.AuthenticateRequest evento no pipeline ASP.net.The SAM adds its OnAuthenticateRequest event handler to the HttpApplication.AuthenticateRequest event in the ASP.NET pipeline. Esse manipulador intercepta solicitações de entrada e, se houver um cookie de sessão, o desserializa em um token de sessão e define as Thread.CurrentPrincipal HttpContext.User Propriedades e para a entidade de declarações contida no token de sessão.This handler intercepts sign-in requests, and, if there is a session cookie, deserializes it into a session token, and sets the Thread.CurrentPrincipal and HttpContext.User properties to the claims principal contained in the session token. Ele invoca vários dos outros métodos expostos pelo SAM durante esse processo.It invokes several of the other methods exposed by the SAM during this process.
O SignOut método pode ser invocado para conectar o usuário de uma sessão (por exemplo, em um arquivo code-behind. aspx. cs de saída).The SignOut method can be invoked to sign the user out of a session (for example, in a SignOut.aspx.cs code-behind file).
O SAM expõe vários eventos que fornecem acesso ao seu pipeline de processamento.The SAM exposes several events that provide access to its processing pipeline. Os SessionSecurityTokenReceived SessionSecurityTokenCreated eventos e permitem que você modifique os tokens de sessão que são lidos de cookies ou criados durante o processamento.The SessionSecurityTokenReceived and SessionSecurityTokenCreated events enable you to modify session tokens that are read from cookies or created during processing. Normalmente, isso é feito para adicionar, remover ou transformar declarações no token ou ajustar seu tempo de expiração.Typically, this is done to add, remove, or transform claims in the token or to adjust its expiration time. Os SigningOut SignedOut eventos, e SignOutError fornecem ganchos no processamento de solicitações de saída.The SigningOut, SignedOut, and SignOutError events provide hooks into the processing of sign-out requests. Para muitos cenários, simplesmente adicionar manipuladores para esses eventos, geralmente ao arquivo global. asax. cs, será suficiente.For many scenarios, simply adding handlers for these events, often to the global.asax.cs file, will be sufficient.
Para cenários mais complicados, você pode derivar de SessionAuthenticationModule para implementar um Sam personalizado.For more complicated scenarios, you can derive from SessionAuthenticationModule to implement a custom SAM. Para esse fim, muitos dos métodos que são invocados durante OnAuthenticateRequest e SignOut são expostos para que você possa fornecer um comportamento personalizado em estágios específicos do ciclo de vida de processamento da sessão.To this end, many of the methods that are invoked during OnAuthenticateRequest and SignOut are exposed so that you can provide custom behavior at specific stages of the session processing lifecycle.
Você pode adicionar o SAM ao pipeline ASP.NET em um arquivo de configuração adicionando-o aos módulos HTTP sob o <system.webServer> elemento do IIS versão 7 e posterior ou sob o <system.web> elemento para versões anteriores ao IIS 7.You can add the SAM to the ASP.NET pipeline in a configuration file by adding it to the HTTP modules under either the <system.webServer> element for IIS version 7 and later or under the <system.web> element for versions prior to IIS 7. O manipulador de cookies usado pelo SAM pode ser configurado com o elemento < cookieHandler > .The cookie handler used by the SAM can be configured with the <cookieHandler> element.
Construtores
| SessionAuthenticationModule() |
Inicializa uma nova instância da classe SessionAuthenticationModule.Initializes a new instance of the SessionAuthenticationModule class. |
Propriedades
| ContextSessionSecurityToken |
Obtém o SessionSecurityToken ativo para o HttpContext atual.Gets the active SessionSecurityToken for the current HttpContext. |
| CookieHandler |
Obtém o manipulador de cookie usado para ler, gravar e excluir cookies de sessão.Gets the cookie handler that is used to read, write, and delete session cookies. |
| FederationConfiguration |
Obtém ou define o objeto FederationConfiguration que está em vigor para o módulo atual.Gets or sets the FederationConfiguration object that is in effect for the current module. (Herdado de HttpModuleBase) |
| IsReferenceMode |
Obtém ou define um valor que especifica se as informações da sessão (valores de declaração, etc.) devem ser armazenadas em um cookie de sessão ou se o conteúdo da sessão deve ser armazenado no lado do servidor, usando o cookie para armazenar apenas uma referência.Gets or sets a value that specifies whether the session information (claim values, etc.) should be stored in the session cookie or whether the session content should be stored on the server side, using the cookie to store just a reference. |
Métodos
| AuthenticateSessionSecurityToken(SessionSecurityToken, Boolean) |
Autentica a solicitação de entrada validando o token da sessão.Authenticates the incoming request by validating the incoming session token. Após a validação bem-sucedida, atualiza o contexto HTTP atual e a entidade de segurança do thread com o SessionSecurityToken especificado.Upon successful validation, it updates the current HTTP context and thread principal with the specified SessionSecurityToken. |
| ContainsSessionTokenCookie(HttpCookieCollection) |
Determina se um cookie de sessão está na coleção de cookies especificada.Determines whether a session cookie is in the specified cookie collection. |
| CreateSessionSecurityToken(ClaimsPrincipal, String, DateTime, DateTime, Boolean) |
Cria um SessionSecurityToken dos parâmetros especificados usando o manipulador do token de sessão configurado.Creates a SessionSecurityToken from the specified parameters by using the configured session token handler. |
| DeleteSessionTokenCookie() |
Exclui o cookie da sessão e o remove do cache.Deletes the session cookie and removes it from the cache. |
| Dispose() |
Libera os recursos (exceto memória) usados pela instância atual da classe HttpModuleBase.Releases the resources (except memory) used by the current instance of the HttpModuleBase class. (Herdado de HttpModuleBase) |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object. (Herdado de Object) |
| GetHashCode() |
Serve como a função de hash padrão.Serves as the default hash function. (Herdado de Object) |
| GetType() |
Obtém o Type da instância atual.Gets the Type of the current instance. (Herdado de Object) |
| Init(HttpApplication) |
Inicializa o módulo HTTP.Initializes the HTTP module. (Herdado de HttpModuleBase) |
| InitializeModule(HttpApplication) |
Inicializa o módulo e o prepara para manipular eventos do objeto de aplicativo ASP.NET do módulo.Initializes the module and prepares it to handle events from the module's ASP.NET application object. |
| InitializePropertiesFromConfiguration() |
Inicializa as propriedades do módulo com base nas definições no arquivo de configuração.Initializes the module properties based on definitions in the configuration file. |
| MemberwiseClone() |
Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object. (Herdado de Object) |
| OnAuthenticateRequest(Object, EventArgs) |
Manipula o AuthenticateRequest evento do pipeline ASP.net.Handles the AuthenticateRequest event from the ASP.NET pipeline. |
| OnPostAuthenticateRequest(Object, EventArgs) |
Manipula o PostAuthenticateRequest evento do pipeline ASP.net.Handles the PostAuthenticateRequest event from the ASP.NET pipeline. |
| OnSessionSecurityTokenCreated(SessionSecurityTokenCreatedEventArgs) |
Aciona o evento SessionSecurityTokenCreated.Raises the SessionSecurityTokenCreated event. |
| OnSessionSecurityTokenReceived(SessionSecurityTokenReceivedEventArgs) |
Aciona o evento SessionSecurityTokenReceived.Raises the SessionSecurityTokenReceived event. |
| OnSignedOut(EventArgs) | |
| OnSigningOut(SigningOutEventArgs) |
Aciona o evento SigningOut.Raises the SigningOut event. |
| OnSignOutError(ErrorEventArgs) |
Aciona o evento SignOutError.Raises the SignOutError event. |
| ReadSessionTokenFromCookie(Byte[]) |
Lê um SessionSecurityToken do cookie de sessão especificado.Reads a SessionSecurityToken from the specified session cookie. |
| SetPrincipalFromSessionToken(SessionSecurityToken) |
Define a entidade de segurança no HttpContext e Thread como a entidade de segurança contida no token de sessão especificado.Sets the principal on the HttpContext and Thread to the principal that is contained in the specified session token. |
| SignOut() |
Desconecta o usuário atual e gera os eventos associados.Signs the current user out and raises the associated events. |
| ToString() |
Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object. (Herdado de Object) |
| TryReadSessionTokenFromCookie(SessionSecurityToken) |
Tenta ler um SessionSecurityToken de um cookie de sessão e retorna um valor que indica se o cookie de sessão foi lido com êxito.Attempts to read a SessionSecurityToken from a session cookie and returns a value that indicates whether the session cookie was successfully read. |
| ValidateSessionToken(SessionSecurityToken) |
Valida o SessionSecurityToken especificado e retorna suas identidades.Validates the specified SessionSecurityToken and returns its identities. |
| WriteSessionTokenToCookie(SessionSecurityToken) |
Grava o SessionSecurityToken especificado em um cookie de sessão.Writes the specified SessionSecurityToken to a session cookie. |
Eventos
| SessionSecurityTokenCreated |
Ocorre quando um token de segurança de sessão foi criado.Occurs when a session security token has been created. |
| SessionSecurityTokenReceived |
Ocorre quando um token de segurança de sessão foi lido de um cookie.Occurs when a session security token has been read from a cookie. |
| SignedOut |
Ocorre após o usuário ser desconectado.Occurs after the user is signed out. |
| SigningOut |
Ocorre antes de excluir a sessão de entrada.Occurs before deleting the sign-in session. |
| SignOutError |
Ocorre quando há um erro durante a saída.Occurs when there is an error during sign-out. |