April 13th, 2012

Requesting a Token from ADFS 2.0 using WS-Trust with Username and Password

In a previous post I showed how to request tokens to ADFS using WS-Trust based on the identity of the user that requests the token.

Due to I’ve received a lot of requests on the subject, here’s the code to do the same but using username and password, I mean request tokens from ADFS 2.0 using username and password based identity.

var stsEndpoint = "https://[server]/adfs/services/trust/13/UsernameMixed";
var relayPartyUri = "https://localhost:8080/WebApp";

var factory = new WSTrustChannelFactory(
    new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
    new EndpointAddress(stsEndpoint));

factory.TrustVersion = TrustVersion.WSTrust13;

// Username and Password here...
factory.Credentials.UserName.UserName = user;
factory.Credentials.UserName.Password = password;

var rst = new RequestSecurityToken 
    RequestType = RequestTypes.Issue,
    AppliesTo = new EndpointAddress(relayPartyUri),
    KeyType = KeyTypes.Bearer,

var channel = factory.CreateChannel();

SecurityToken token = channel.Issue(rst);

I hope you find it useful!

  • Dinesh Kumar
  • Sajudeen Kassim

    Getting error Could not establish trust relationship for the SSL/TLS secure channel .Any idea

    • It sounds like your server HTTPS certificate is not a valid SSL certificate. You can ignore that with this line of code `ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; ` but have in mind that for production that’s not secure at all.

      • Sajudeen Kassim

        Thank u it is fixed

      • Sajudeen Kassim

        Getting an error at least one secutiy message could not be verified. Please explin how we can debug this error

    • Sajudeen Kassim

      This error was fixed. Because the user name without domain name.Thanks