1

是否可以通过 HttpWebRequest 传递 Sitecore 凭据?下面的代码效果很好,除了被调用的 asmx 以匿名用户身份执行。我希望能够将 sitecore 当前用户凭据传递给我正在调用的页面。

CookieContainer cookieJar = new CookieContainer();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("ttp://localhost/file.asmx");
req.Headers.Add("SOAPAction", "\"h_ttp://tempuri.org/Register\"");
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";
req.ContentLength = 0;
req.CookieContainer = cookieJar;
WebResponse response = req.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader respStrm = new StreamReader(response.GetResponseStream(), System.Text.Encoding.ASCII);
string responseITem = respStrm.ReadToEnd();
HttpContext.Current.Response.Write(responseITem);
HttpContext.Current.Response.End();
4

2 回答 2

3

Sitecore 用户凭据信息存储在 cookie 中。因此,您可以将客户端 cookie 添加到您的 http 请求中:

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.CookieContainer = new CookieContainer();
HttpCookieCollection userCookies = Request.Cookies;
for (int userCookieCount = 0; userCookieCount < userCookies.Count; userCookieCount++)
{
    HttpCookie httpCookie = userCookies.Get(userCookieCount);
    Cookie cookie = new Cookie();
    /*  We have to add the target host because the cookie does not contain the domain information.
        In this case, this behaviour is not a security issue, because the target is our own platform.
        Further informations: http://stackoverflow.com/a/460990 
    */
    cookie.Domain = request.RequestUri.Host;
    cookie.Expires = httpCookie.Expires;
    cookie.Name = httpCookie.Name;
    cookie.Path = httpCookie.Path;
    cookie.Secure = httpCookie.Secure;
    cookie.Value = httpCookie.Value;

    request.CookieContainer.Add(cookie);
}

您还可以查看我们的 Sitecore 错误管理器模块。在那里,我们还创建了发送客户端 cookie 的 http 请求(参见第 149-170 行):

https://github.com/unic/SitecoreErrorManager/blob/master/Modules.ErrorManager/Controls/BaseError.cs

于 2013-03-06T07:37:38.223 回答
2

您需要将当前用户凭据添加到请求中,以便您可以在 asmx Web 服务中检索它们并使用凭据记录用户以便设置上下文。

// add the credentials to the Post method
var credentials = "yourCredentials";
req.ContentLength = credentials.Length;
using (var dataStream = req.GetRequestStream())
{
  dataStream.Write(credentials, 0, credentials.Length);
}

在您的 asmx 网络服务中,您可以仅使用用户名或从请求中检索到的用户名和密码的组合登录。

Sitecore.Security.Authentication.AuthenticationManager.Login(userName);

编辑:以纯文本形式发送凭据时,此处存在安全风险,请至少使用 HTTPS 以使其更安全。

于 2013-03-05T23:07:17.457 回答