【发布时间】:2013-03-03 06:02:27
【问题描述】:
我正在使用基于 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 sn-p)
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; }
...
}
}
我还注意到,在FederatedAuthentication.SessionAuthenticationModule.CreateSessionSecurityToken 中,默认的 ValidTo 属性设置为 ValidFrom + 默认令牌生命周期。我可以看到设置 SecurityToken.ValidTo 的唯一方法是创建安全令牌时。这是否意味着我需要实现自定义 SecurityToken 类或者是否存在
在 WIF 堆栈的某个地方我可以拦截令牌的创建吗?到目前为止,我似乎只找到了以下事件处理程序FederatedAuthentication.SessionAuthenticationModule.SessionSecurityTokenCreated,但此时令牌已经创建,我可以在其中访问令牌,但正如预期的那样,SecurityToken.ValidTo 属性只是一个吸气剂。
<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?
【问题讨论】:
-
为什么不在 STS 中设置生命周期?
-
发现它隐藏在 STS 的自定义 SecurityTokenServiceConfiguration 类中。它被硬编码为 10 小时。谢谢多米尼克。
-
我在stackoverflow.com/questions/17099727/… 发布了一个答案,显示了如何从依赖方内部覆盖 SAML 的“ValidTo”。以防万一您无法直接更改 STS。
标签: asp.net sharepoint-2010 wif federation