场景如下:我需要对用户(使用他的大学帐户)在他的大学Sharepoint网站上执行联合身份验证,以获取FedAuth和rtFa cookie(我必须将其传递给SharePoint REST Web服务,以便访问资源)。
我尝试过一些方法,但每种方法都存在至少一个问题:
1)使用Microsoft.SharePoint.Client库
ClientContext context = new ClientContext(host);
SharePointOnlineCredentials creds = new SharePointOnlineCredentials(user, passw);
context.Credentials = creds;
Uri sharepointuri = new Uri(host);
string authCookie = creds.GetAuthenticationCookie(sharepointuri);
Web web = context.Web;
context.Load(web, w=>w.Lists);
context.ExecuteQuery();
fedAuthString = authCookie.Replace("SPOIDCRL=", string.Empty);
我成功获取了FedAuth cookie,但是无法获取rtFa cookie.
此时如何获取rtFa cookie? 我能拦截涉及此操作的HTTP请求(即context.ExecuteQuery()),该请求是否包含标头中的rtFa cookie? 或者,我是否仅依靠FedAuth cookie就能获取rtFa cookie?
2)使用MsOnlineClaimsHelper
这是一个可以在互联网上找到的帮助类(例如,在此处http://blog.kloud.com.au/tag/msonlineclaimshelper/)。这个类,在正常身份验证情况下工作,但是在联合身份验证下失败了。
因此,我进行了调整,以使其在这种情况下工作。 只要我理解,步骤如下:
- 使用用户名和密码对大学的STS ADFS服务(“联盟方”或ISSUER)进行身份验证 - 这里Relying Party是Sharepoint O365 STS(“https://login.microsoftonline.com/extSTS.srf”)
- 如果验证成功,则会收到包含声明和安全令牌的SAML断言
- 现在,我通过传递安全令牌来对SharePoint站点进行身份验证
- 如果令牌得到识别,则会收到一个响应,其中包含两个Cookie(FedAuth和rtFa)
我不是这方面的专家,我写了以下代码:
这是调用上述方法并尝试从两步骤中的凭据获取FedAuth和rtFa的代码(步骤1:从联盟方获取SAML令牌;步骤2:将来自联盟方的令牌传递给Sharepoint):
private List<string> GetCookies(){
// 1: GET SAML XML FROM FEDERATED PARTY THE USER BELONGS TO
string samlToken = getResponse_Federation(sts: "https://sts.FEDERATEDDOMAIN.com/adfs/services/trust/13/usernamemixed/",
realm: "https://login.microsoftonline.com/extSTS.srf");
// 2: PARSE THE SAML ASSERTION INTO A TOKEN
var handlers = FederatedAuthentication.ServiceConfiguration.SecurityTokenHandlers;
SecurityToken token = handlers.ReadToken(new XmlTextReader(new StringReader(samlToken )));
// 3: REQUEST A NEW TOKEN BASED ON THE ISSUED TOKEN
GenericXmlSecurityToken secToken = GetO365BinaryTokenFromToken(token);
// 4: NOW, EASY: I PARSE THE TOKEN AND EXTRACT FEDAUTH and RTFA
...............
}
private string getResponse_Federation(string stsUrl, string relyingPartyAddress)
{
var binding = new Microsoft.IdentityModel.Protocols.WSTrust.Bindings.UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential);
binding.ClientCredentialType = HttpClientCredentialType.None;
var factory = new WSTrustChannelFactory(binding, stsUrl);
factory.Credentials.UserName.UserName = "username";
factory.Credentials.UserName.Password = "password";
factory.Credentials.SupportInteractive = false;
factory.TrustVersion = TrustVersion.WSTrust13;
IWSTrustChannelContract channel = null;
try
{
var rst = new RequestSecurityToken
{
RequestType = WSTrust13Constants.RequestTypes.Issue,
AppliesTo = new EndpointAddress(relyingPartyAddress), //("urn:sharepoint:MYFEDERATEDPARTY"),
ReplyTo = relyingPartyAddress,
KeyType = WSTrust13Constants.KeyTypes.Bearer,
TokenType = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0",
RequestDisplayToken = true,
};
channel = (WSTrustChannel)factory.CreateChannel();
RequestSecurityTokenResponse response = null;
SecurityToken st = channel.Issue(rst, out response);
var genericToken = st as GenericXmlSecurityToken;
return genericToken.TokenXml.OuterXml;
}
catch (Exception e)
{
return null;
}
}
private GenericXmlSecurityToken GetO365BinaryTokenFromToken(SecurityToken issuedToken)
{
Uri u = new Uri("https://login.microsoftonline.com/extSTS.srf");
WSHttpBinding binding = new WSHttpBinding(SecurityMode.TransportWithMessageCredential);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
binding.Security.Mode = SecurityMode.TransportWithMessageCredential;
binding.Security.Message.ClientCredentialType = MessageCredentialType.IssuedToken;
Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannelFactory channel =
new Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannelFactory(
binding, new EndpointAddress("https://login.microsoftonline.com/extSTS.srf"));
channel.TrustVersion = TrustVersion.WSTrust13;
channel.Credentials.SupportInteractive = false;
GenericXmlSecurityToken token = null;
try
{
RequestSecurityToken rst = new RequestSecurityToken(WSTrust13Constants.RequestTypes.Issue, WSTrust13Constants.KeyTypes.Bearer)
{
};
rst.AppliesTo = new EndpointAddress("urn:sharepoint:MYFEDERATEDPARTY");
channel.ConfigureChannelFactory();
var chan = (Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannel)channel.CreateChannelWithIssuedToken(issuedToken);
RequestSecurityTokenResponse rstr = null;
token = chan.Issue(rst, out rstr) as GenericXmlSecurityToken;
return token;
}
catch (Exception ex){
Trace.TraceWarning("WebException in getO365BinaryTokenFromADFS: " + ex.ToString());
throw;
}
}
我能够从大学的STS获取回一个SAML令牌。但是,在解析时,生成的SecurityToken没有安全密钥(即SecurityKeys集合为空)。
由于没有密钥,我可以获取GetO365BinaryTokenFromToken(),但是当我尝试将令牌发送到SharePoint身份验证服务时,我会收到以下错误: "签名令牌Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityToken没有密钥。 该安全令牌用于需要执行加密操作的上下文中,但令牌不包含加密密钥。 要么令牌类型不支持加密操作,要么特定的令牌实例不包含加密密钥。 请检查您的配置,以确保在需要执行加密操作的上下文中未指定已禁用加密的令牌类型(例如UserNameSecurityToken)(例如支持背书的令牌)。
我认为在双方(大学STS ADFS和Sharepoint STS)都存在一些我无法直接控制的配置问题。
我希望更有经验的人能够在这个过程中提供更清晰的建议,并甚至提供建议以使此场景实际可行。
文件下载函数
使用以下函数,我能够通过发出 BOTH FedAuth和rtFa cookie(给定URL,如https://myfederatedparty.sharepoint.com/sites/MYSITE/path/myfile.pdf)来下载文件。如果我不传递rtFa cookie,我会收到一个"未授权"的响应。
public static async Task<byte[]> TryRawWsCall(String url, string fedauth, string rtfa, CancellationToken ct, TimeSpan? timeout = null) {
try {
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = new System.Net.CookieContainer();
CookieCollection cc = new CookieCollection();
cc.Add(new Cookie("FedAuth", fedauth));
cc.Add(new Cookie("rtFa", rtfa));
handler.CookieContainer.Add(new Uri(url), cc);
HttpClient _client = new HttpClient(handler);
if (timeout.HasValue)
_client.Timeout = timeout.Value;
ct.ThrowIfCancellationRequested();
var resp = await _client.GetAsync(url);
var result = await resp.Content.ReadAsByteArrayAsync();
if (!resp.IsSuccessStatusCode)
return null;
return result;
}
catch (Exception) { return null; }
}