【发布时间】:2015-08-30 22:01:53
【问题描述】:
我有一个使用 ADFS 2.0 进行身份验证的 ASP.NET MVC Web 应用程序。一些 MVC 控制器操作充当通用 Web 服务端点,接收和提供 JSON。我想构建一个自动执行某些应用程序功能的客户端应用程序。为此,我正在构建一个 API 访问库,它将向 Web 服务发出 HTTP 请求以完成其工作。
我一直在尝试进行身份验证。我正在为 ADFS 2.0 使用表单身份验证,所以我不应该能够简单地使用有效的用户名和密码模拟表单帖子以生成令牌吗?我没有收到令牌,而是得到了登录页面。我不确定我还需要做什么才能验证我的请求。我的代码粘贴在下面……但也许我做错了,还有一些我不知道的事情?
string postData = string.Empty;
postData += "ctl00$ContentPlaceHolder1$UsernameTextBox=" + username + "&";
postData += "ctl00$ContentPlaceHolder1$PasswordTextBox=" + password;
postData += "&AuthMethod=FormsAuthentication";// Submit the data back
string url = "{url of website}";
HttpWebRequest getTokenRequest = WebRequest.Create(url) as HttpWebRequest;
getTokenRequest.CookieContainer = cookies;
getTokenRequest.ContentType = "application/x-www-form-urlencoded";
getTokenRequest.ContentLength = postData.Length;
getTokenRequest.Method = "POST";
// post the data to the request
using (StreamWriter sw = new StreamWriter(getTokenRequest.GetRequestStream()))
{
sw.Write(postData);
sw.Flush();
sw.Close();
}
HttpWebResponse getTokenResponse = (HttpWebResponse)getTokenRequest.GetResponse();
string responseString = ResponseToString(getTokenResponse);
我也尝试了另一种方法,但也不起作用。这使用 WCF。我得到了错误:
无法打开安全通道,因为与 远程端点失败。这可能是由于不存在或错误 EndpointAddress 中指定的 EndpointIdentity 用于创建 渠道。请验证指定或暗示的 EndpointIdentity EndpointAddress 正确识别远程端点。
const string relyingPartyId = "[ID]"; //ID of the relying party in AD FS
const string adfsEndpoint = "https://[server]/adfs/services/trust/13/usernamemixed"; //url to hit - username & pw?
const string certSubject = "[subject]"; //?
//Setup the connection to ADFS
var factory = new Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannelFactory(
new WindowsWSTrustBinding(SecurityMode.TransportWithMessageCredential),
new EndpointAddress(adfsEndpoint));
factory.TrustVersion = TrustVersion.WSTrust13;
factory.Credentials.UserName.UserName = "[un]";
factory.Credentials.UserName.Password = "[pw]";
//Setup the request object
var rst = new Microsoft.IdentityModel.Protocols.WSTrust.RequestSecurityToken
{
RequestType = Microsoft.IdentityModel.SecurityTokenService.RequestTypes.Issue,
KeyType = Microsoft.IdentityModel.SecurityTokenService.KeyTypes.Bearer,
AppliesTo = new EndpointAddress(relyingPartyId)
};
//Open a connection to ADFS and get a token for the logged in user
var channel = factory.CreateChannel();
//added to solve a trust certificate issue - bad from a security perspective
System.Net.ServicePointManager.ServerCertificateValidationCallback +=
(se, cert, chain, sslerror) =>
{
return true;
};
var genericToken = channel.Issue(rst) as GenericXmlSecurityToken;
【问题讨论】:
标签: asp.net asp.net-mvc wcf forms-authentication adfs2.0