2014-11-05 4 views
2

Вот пример получения tokem с использованием WSTrustChannelFactory. From here.Как передать сертификат на WSTrust, чтобы получить токен Saml

var stsBinding = new WS2007HttpBinding(); 
stsBinding.Security.Mode = SecurityMode.TransportWithMessageCredential; 
stsBinding.Security.Message.EstablishSecurityContext = false; 
stsBinding.Security.Message.NegotiateServiceCredential = false; 
stsBinding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate; 


WSTrustChannelFactory trustChannelFactory = new WSTrustChannelFactory(
    stsBinding 
    , new EndpointAddress(tokenurl) 
    ); 
trustChannelFactory.TrustVersion = System.ServiceModel.Security.TrustVersion.WSTrust13; 

X509Store myStore = new X509Store(StoreName.My, StoreLocation.LocalMachine); 
myStore.Open(OpenFlags.ReadOnly); 
X509Certificate2Collection coll = myStore.Certificates.Find(X509FindType.FindBySerialNumber, "MycertSerialNumber", true); 
X509Certificate2 cert = coll[0]; 
trustChannelFactory.Credentials.ClientCertificate.Certificate = cert; 

WSTrustChannel channel = (WSTrustChannel)trustChannelFactory.CreateChannel(); 

RequestSecurityToken rst = new RequestSecurityToken(RequestTypes.Issue, keyType); 
rst.AppliesTo = new EndpointAddress(realm); 
RequestSecurityTokenResponse rstr = null; 
rst.TokenType = SecurityTokenTypes.Saml; 

SecurityToken token = channel.Issue(rst, out rstr); 

У меня нет имени пользователя/пароля, но поставщик предоставил мне сертификат .pfx-файла. Как передать его в WSTrushChannelFactory? Я пробовал использовать CertificateBinding, но не добился успеха.

Обновленный код выше: 11/05/2014:

Получение этой ошибки: ID3242: Маркер безопасности не может быть заверены или уполномоченным.

ответ

1

Используйте ClientCertificate свойства:

var stsBinding = new WS2007HttpBinding(); 
stsBinding.Security.Mode = SecurityMode.TransportWithMessageCredential; 
stsBinding.Security.Message.EstablishSecurityContext = false; 
stsBinding.Security.Message.NegotiateServiceCredential = false; 

// select the authentication mode of Client Certificate 
stsBinding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate; 

var wifChannelFactory = new WSTrustChannelFactory(stsBinding, stsEndpoint); 
wifChannelFactory.TrustVersion = TrustVersion.WSTrust13; 

// Supply the credentials 
wifChannelFactory.Credentials.ClientCertificate.Certificate = config.Certificate; 

В PFX вы можете import to your certificate магазин через certmgr.msc оснастки. Убедитесь, что ваша учетная запись работает как has access to the private key. Вы можете reference it in the store с использованием классов x509certificate2.

+0

Mitch, ваше предложение сделало меня еще дальше, чем я был до этого, но получил эту ошибку сейчас: ID3242: токен безопасности не может быть аутентифицирован или авторизирован. – gbs

+0

@gbs, я полагаю, вы имеете в виду, что получаете эту ошибку, когда пытаетесь использовать полученный токен. ID3242 обычно вызван неправильной аудиторией uri. Убедитесь, что ваш 'AppliesTo' соответствует ожиданиям STS и что RP настроен на прием. Другое дело, что сертификаты подписи или шифрования, настроенные на STS, не соответствуют RP. – Mitch

+0

Не использовать, а запрашивать токен. STS отправляет мне эту ошибку. Я отправил это провайдеру, и они также изучают его. – gbs

0

Здесь вы идете.

private static SecurityToken RequestSecurityToken()  
{  
    // set up the ws-trust channel factory  
    var factory = new WSTrustChannelFactory( 
     new UserNameWSTrustBinding(
      SecurityMode.TransportWithMessageCredential),  
      _idpAddress);  
    factory.TrustVersion = TrustVersion.WSTrust13;    

    var authCertificate = X509.LocalMachine.My.Thumbprint.Find(Properties.Settings.Default.RassCertificateThumbprint).FirstOrDefault(); 
    if (authCertificate == null) 
     throw new InternalException(String.Format("No atuhentication certificate found in store with thumbprint {0}.", Properties.Settings.Default.ClientCertificateThumbprint)); 

    // overenie je na zaklade certifikatu RASS 
    factory.Credentials.ClientCertificate.Certificate = authCertificate; 

    // create token request 
    var rst = new RequestSecurityToken  
    {  
     RequestType = RequestTypes.Issue, 
     KeyType = KeyTypes.Symmetric,  
     AppliesTo = new EndpointReference(_serviceAddress.AbsoluteUri)  
    }; 

    // request token and return 
    return factory.CreateChannel().Issue(rst);  
} 

BTW: @Mitch имеет право доступа к закрытому ключу. Я просто взял ваш метод и заменил несколько строк кода.

+0

pepo, я следую предложению mitch и обновляю свой код выше, но теперь я получаю сообщение об ошибке. – gbs

+0

Где вы можете получить эту ошибку. Это на «SecurityToken token = channel.Issue (rst, out rstr);» или когда вы пытаетесь использовать полученный токен. – pepo

+0

Да на той же линии, на которую вы указали. – gbs

Смежные вопросы