Send a Request for a
Security Token with C#
To send a request for a security token, the
sample specifies username and password assertions to satisfy the security
policy, creates a request token, and calls the
Issue
method. The following
sequence shows these operations.
- Create theSTSServiceclient-side object. This object provides access to vCenter Single Sign-On request objects and methods.
- Specify the URL of the vCenter Single Sign-On server.
- Create aSoapContextobject for the security headers.
- Specify username and password assertions to satisfy the security policy.
- Provide a remote certificate validation callback. The sample version of this callback does not validate the certificate; it just returns atruevalue.This is suitable for a development environment, but you should implement certificate validation for a production environment.
- Create a token request (RequestSecurityTokenType) and set the token request fields:
- Lifetime – Creation and expiration times.
- Token type – urn:oasis:names:tc:SAML:2.0:assertion.
- Request type – http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue.
- Key type – http://docs.oasis-open.org/ws-sx/ws-trust/200512/PublicKey (for holder-of-key token type).
- Signature algorithm – http://www.w3.org/2001/04/xmldsig-more#rsa-sha256.
- Renewable status.
- Call theIssuemethod. The SSO server returns a response structure that contains the token.
The following example shows C# code that
performs these operations.
Acquiring a vCenter Single Sign-On Token –
Sending the Request
public static XmlElement GetToken(String[] args) { // 1. Create an SSO server client-side object service = new STSService(); // 2. Set the SSO server URL service.Url = args[0]; // 3. SOAP Request Context - Required to add secruity headers SoapContext requestContext = service.RequestSoapContext; // 4. Create a CustomSecurityAssertion object that specifies username and password CustomSecurityAssertion objCustomSecurityAssertion = new CustomSecurityAssertion(); objCustomSecurityAssertion.Username = args[1].Trim(); objCustomSecurityAssertion.Password = args[2].Trim(); // Use the assertions to set the policy Policy policy = new Policy(); policy.Assertions.Add(objCustomSecurityAssertion); service.SetPolicy(policy); // 5. Establish a validation callback for the token certificate ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateRemoteCertificate); // 6. Create a token request RequestSecurityTokenType tokenType = new RequestSecurityTokenType(); // Specify the token type, request type, key type, and signature algorithm tokenType.TokenType = TokenTypeEnum.urnoasisnamestcSAML20assertion; tokenType.RequestType = RequestTypeEnum.httpdocsoasisopenorgwssxwstrust200512Issue; tokenType.KeyType = KeyTypeEnum.httpdocsoasisopenorgwssxwstrust200512PublicKey; tokenType.SignatureAlgorithm = SignatureAlgorithmEnum.httpwwww3org200104xmldsigmorersasha256; // Set the token creation date/time LifetimeType lifetime = new LifetimeType(); AttributedDateTime created = new AttributedDateTime(); String createdDate = XmlConvert.ToString(System.DateTime.Now, XmlDateTimeSerializationMode.Utc); created.Value = createdDate; lifetime.Created = created; // Set the token expiration time AttributedDateTime expires = new AttributedDateTime(); TimeSpan duration = new TimeSpan(1, 10, 10); String expireDate = XmlConvert.ToString(DateTime.Now.Add(duration), XmlDateTimeSerializationMode.Utc); expires.Value = expireDate; lifetime.Expires = expires; tokenType.Lifetime = lifetime; RenewingType renewing = new RenewingType(); renewing.Allow = true; renewing.OK = true; tokenType.Renewing = renewing; // 7. Call Issue try { RequestSecurityTokenResponseCollectionType responseToken = service.Issue(tokenType); RequestSecurityTokenResponseType rstResponse = responseToken.RequestSecurityTokenResponse; return rstResponse.RequestedSecurityToken; } catch (Exception ex) { Console.WriteLine(ex.ToString()); throw ex; } }
A vCenter Single Sign-On client provides a
custom output filter for the custom security assertion. The
CustomSecurityClientOutputFilter
class provides
three methods:
- CustomSecurityClientOutputFilterconstructor – Creates a token for the username and password. It also calls theGetSecurityTokenmethod and creates a message signature for the security token.
- SecureMessage– An override method for the .NET methodSendSecurityFilter.SecureMessage. The override method adds tokens and the message signature to the .NET Security element.
- GetSecurityToken– creates an X509 security token from a PFX certificate file. PFX is a Public-Key Cryptography Standard format that is used to store a private key and the corresponding X509 certificate.
The following code example shows the custom
output filter for the custom security assertion.
Custom Output Filter
internal class CustomSecurityClientOutputFilter : SendSecurityFilter { UsernameToken userToken = null; X509SecurityToken signatureToken = null; MessageSignature sig = null; public CustomSecurityClientOutputFilter(CustomSecurityAssertion parentAssertion) : base(parentAssertion.ServiceActor, true) { userToken = new UsernameToken(parentAssertion.Username.Trim(), parentAssertion.Password.Trim(), PasswordOption.SendPlainText); signatureToken = GetSecurityToken(); sig = new MessageSignature(signatureToken); } /// SecureMessage public override void SecureMessage(SoapEnvelope envelope, Security security) { security.Tokens.Add(userToken); security.Tokens.Add(signatureToken); security.Elements.Add(sig); } /// GetSecurityToken - creates the security token from certificate from pfx file internal static X509SecurityToken GetSecurityToken() { X509Certificate2 certificateToBeAdded = new X509Certificate2(); string certificateFile = ConfigurationManager.AppSettings["PfxCertificateFile"]; certificateToBeAdded.Import(certificateFile, "", X509KeyStorageFlags.MachineKeySet); return new X509SecurityToken(certificateToBeAdded); } }