我正在使用基于 WIF (.NET 4.0) 的自定义 STS,目前仅用于 SharePoint 应用程序。我在按预期工作的 HTTP 模块中设置了滑动到期代码,但安全令牌的生命周期为 10 小时(默认生命周期)。
/// <summary>
/// Handles the SessionSecurityTokenReceived event of the SingleSignOnModule control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="Microsoft.IdentityModel.Web.SessionSecurityTokenReceivedEventArgs"/> instance containing the event data.</param>
private void SingleSignOnModule_SessionSecurityTokenReceived(Object sender, SessionSecurityTokenReceivedEventArgs e)
{
using (new SPMonitoredScope("SingleSignOnModule-SessionSecurityTokenReceived"))
{
if ((HttpContext.Current != null) && (FederatedAuthentication.SessionAuthenticationModule != null) && (e != null))
{
TimeSpan logonTokenCacheExpirationWindow = TimeSpan.FromSeconds(1);
SPSecurity.RunWithElevatedPrivileges(delegate()
{
logonTokenCacheExpirationWindow = SPSecurityTokenServiceManager.Local.LogonTokenCacheExpirationWindow;
});
DateTime currentDateTime = DateTime.UtcNow;
TimeSpan sessionLifetime = (e.SessionToken.ValidTo - e.SessionToken.ValidFrom);
DateTime sessionValidFrom = e.SessionToken.ValidFrom;
DateTime sessionValidTo = (e.SessionToken.ValidTo - logonTokenCacheExpirationWindow);
if ((currentDateTime < sessionValidTo) && (currentDateTime > sessionValidFrom.AddMinutes(sessionLifetime.TotalMinutes / 2)))
{
e.SessionToken = FederatedAuthentication.SessionAuthenticationModule.CreateSessionSecurityToken(e.SessionToken.ClaimsPrincipal, e.SessionToken.Context, currentDateTime, currentDateTime.AddMinutes(sessionLifetime.TotalMinutes), e.SessionToken.IsPersistent);
e.ReissueCookie = true;
}
}
}
}
最初,我认为这可以由 SPSecurityTokenServiceManager 设置。然而,这并没有改变什么。(PowerShell 片段)
Write-Output("[INFO] Updating the SPSecurityTokenServiceManager")
$stsMgr = Get-SPSecurityTokenServiceConfig
Write-Output("[INFO] Updating the SPSecurityTokenServiceManager to use session cookies.")
$stsMgr.UseSessionCookies = $true; #
Write-Output("[INFO] Updating the SPSecurityTokenServiceManager logon token cache expiration window")
$stsMgr.LogonTokenCacheExpirationWindow = New-TimeSpan -Days 0 -Hours 0 -Minutes 1
Write-Output("[INFO] Updating the SPSecurityTokenServiceManager service token cache expiration window.")
$stsMgr.ServiceTokenCacheExpirationWindow = New-TimeSpan -Days 0 -Hours 0 -Minutes 20
$stsMgr.Update()
我无法设置 SessionSecurityTokenHandler.DefaultLifetime,因为它是只读的并设置为 10 小时。
// Type: Microsoft.IdentityModel.Tokens.SecurityTokenHandler
// Assembly: Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
// Assembly location: C:\Windows\assembly\GAC_MSIL\Microsoft.IdentityModel\3.5.0.0__31bf3856ad364e35\Microsoft.IdentityModel.dll
namespace Microsoft.IdentityModel.Tokens
{
public class SessionSecurityTokenHandler : SecurityTokenHandler
{
public static readonly TimeSpan DefaultLifetime = TimeSpan.FromHours(10.0);
...
}
}
SecurityToken.ValidTo 只有一个 getter 而不是一个 setter。
// Type: System.IdentityModel.Tokens.SecurityToken
// Assembly: System.IdentityModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// Assembly location: C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.0\System.IdentityModel.dll
namespace System.IdentityModel.Tokens
{
/// <summary>
/// Represents a base class used to implement all security tokens.
/// </summary>
/// <filterpriority>2</filterpriority>
public abstract class SecurityToken
{
...
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
///
/// <returns>
/// A <see cref="T:System.DateTime"/> that represents the last instant in time at which this security token is valid.
/// </returns>
/// <filterpriority>2</filterpriority>
public abstract DateTime ValidTo { get; }
...
}
}
我还注意到,在ValidTo 中FederatedAuthentication.SessionAuthenticationModule.CreateSessionSecurityToken
,默认的 ValidTo 属性设置为 ValidFrom + 默认令牌生命周期。我可以看到设置 SecurityToken.ValidTo 的唯一方法是创建安全令牌时。这是否意味着我需要实现一个自定义 SecurityToken 类,或者在 WIF 堆栈中的某个地方我可以拦截令牌的创建?到目前为止,我似乎只找到了以下事件处理程序,FederatedAuthentication.SessionAuthenticationModule.SessionSecurityTokenCreated
但此时令牌已经创建,我可以在其中访问令牌,但正如预期的那样,该SecurityToken.ValidTo
属性只是一个 getter。
<microsoft.identityModel />
配置部分似乎也没有为此设置。有一个 persistenLifeTime 设置,但这仅适用于写入磁盘的 cookie。
<microsoft.identityModel>
<federatedAuthentication>
<wsFederation
persistentCookiesOnPassiveRedirects="true" />
<cookieHandler
persistentSessionLifetime="60.0:0:0" />
</federatedAuthentication>
</microsoft.identityModel>
此外,为了使加密/解密与服务器无关,加密使用证书。为此,我以编程方式将会话安全令牌处理程序添加到我的联合提供程序的 Global.asax 中。我只提到这一点是因为我想知道,如果我需要自定义SecurityToken.ValidTo
,我是否可能需要创建一个自定义安全令牌处理程序类,或者我目前在 Global.asax 中是如何做到这一点的,我需要看看其他地方解决SecurityToken.ValidTo
问题?
<microsoft.identityModel>
<service>
<serviceCertificate>
<certificateReference x509FindType="FindByThumbprint" findValue="myThumbPrint" />
</serviceCertificate>
...
</microsoft.identityModel>
namespace MyCompany.IdentityServer.FederationProvider
{
public class Global : System.Web.HttpApplication
{
/// <summary>
/// Handles the Start event of the Application control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void Application_Start(object sender, EventArgs e)
{
FederatedAuthentication.ServiceConfigurationCreated += OnServiceConfigurationCreated;
}
/// <summary>
/// Called when [service configuration created].
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="Microsoft.IdentityModel.Web.Configuration.ServiceConfigurationCreatedEventArgs"/> instance containing the event data.</param>
private void OnServiceConfigurationCreated(object sender, ServiceConfigurationCreatedEventArgs e)
{
// The session security token handler needs to be overridden so that encryption/decryption is not server dependent via DPAPI.
// We need encryption/decryption to be server agnostic, so we make it certificate based instead.
// See http://blogs.msdn.com/b/distributedservices/archive/2012/10/29/wif-1-0-id1073-a-cryptographicexception-occurred-when-attempting-to-decrypt-the-cookie-using-the-protecteddata-api.aspx
// Use the <serviceCertificate> to protect the cookies that are
// sent to the client.
var sessionTransforms =
new List<CookieTransform>(new CookieTransform[] {
new DeflateCookieTransform(),
new RsaEncryptionCookieTransform(e.ServiceConfiguration.ServiceCertificate),
new RsaSignatureCookieTransform(e.ServiceConfiguration.ServiceCertificate) });
var sessionHandler = new SessionSecurityTokenHandler(sessionTransforms.AsReadOnly());
// This does nothing
//sessionHandler.TokenLifetime = someLifeTime;
e.ServiceConfiguration.SecurityTokenHandlers.AddOrReplace(sessionHandler);
}
}
}
如果我创建一个自定义 securityTokenHandler,我看到我可以指定一个生命周期,但这看起来就像我在上面的 Global.asax 中尝试的那样, sessionHandler.TokenLifetime = ...
<microsoft.identityModel>
<service>
<securityTokenHandlers>
<add type="System.IdentityModel.Tokens.SessionSecurityTokenHandler, System.IdentityModel">
<sessionTokenRequirement lifetime="TimeSpan" />
</add>
</securityTokenHandlers>
...
</service>
</microsoft.identityModel>
我只能假设我错过了一些明显的设置,或者是我唯一的行动方案来定制以获得SecurityToken.ValidTo
我需要的?