使用usernamemixed从ADFS请求令牌

时间:2016-02-26 06:06:20

标签: asp.net-web-api

我正在尝试从.net web api获取来自ADFS服务器的令牌,同时请求我获得低于异常的内部Windows身份验证。

  

类型&System; Service.ServiceModel.Security.MessageSecurityException'发生在   mscorlib.dll但未在用户代码中处理附加信息:   客户端身份验证方案禁止HTTP请求   '匿名'

获取令牌的代码如下

  var trustChannelFactory = new WSTrustChannelFactory(new UserNameWSTrustBinding(
                System.ServiceModel.SecurityMode.TransportWithMessageCredential),
                new System.ServiceModel.EndpointAddress(new Uri("https://ADFSSERVER/adfs/services/trust/13/usernamemixed")))
            {
                TrustVersion = TrustVersion.WSTrust13,
                Credentials = { UserName = { UserName = "DCK", Password = "gfgfg" } },               
            };

            var requestSecurityToken = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                KeyType = KeyTypes.Bearer,
                AppliesTo = new EndpointReference("urn:feedbackapp")   

            };

            RequestSecurityTokenResponse response;
            var securityToken = trustChannelFactory.CreateChannel().Issue(requestSecurityToken, out response);
            return securityToken;
你可以帮助我继续获取令牌吗

1 个答案:

答案 0 :(得分:0)

var binding = WSTrust13Bindings.UsernameMixed;
var serviceUri = new Uri(_config.StsUri, "/adfs/services/trust/13/usernamemixed");
using (var factory = new WSTrustChannelFactory(binding, serviceUri.AbsoluteUri))
{
    factory.TrustVersion = TrustVersion.WSTrust13;
    factory.Credentials.UserName.UserName = userName;
    factory.Credentials.UserName.Password = password;

    RequestSecurityTokenResponse response;
    var channel = factory.CreateChannel();
    channel.Issue(new RequestSecurityToken()
    {
        RequestType = RequestTypes.Issue,
        AppliesTo = new EndpointReference(_config.ResourceUri.ToString()),
        KeyType = KeyTypes.Bearer
    }, out response);

    var sb = new StringBuilder();
    var ser = new WSTrust13ResponseSerializer();
    using (var sw = new StringWriter(sb, CultureInfo.InvariantCulture))
    {
        var xw = XmlTextWriter.Create(sw, new XmlWriterSettings() { OmitXmlDeclaration = true });
        ser.WriteXml(response, xw, new WSTrustSerializationContext(factory.SecurityTokenHandlerCollectionManager));
        xw.Flush();
    }
    return sb.ToString();
}