Authenticate username and password against remote ADFS 2.0

Posted: September 6, 2013 in .Net/C#
Tags:

Background: one partner requests to login our portal using their ADFS username and password without maintaining two sets of passwords.

Credit: http://leandrob.com/2012/04/requesting-a-token-from-adfs-2-0-using-ws-trust-with-username-and-password/

Preparation: The remote ADFS server need add your site to the trusted relying party list.


using Microsoft.IdentityModel.Protocols.WSTrust;
using Microsoft.IdentityModel.Protocols.WSTrust.Bindings;
using System.ServiceModel;
using System.ServiceModel.Security;
using System.IdentityModel.Tokens;

//you may need add a few references for the above

string stsEndpoint = "https://WIN-2013.win2008.marz.com/adfs/services/trust/13/usernamemixed";
string relyingPartyUri = "https://www.yourrelyingpartyuri.com";

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

factory.TrustVersion = TrustVersion.WSTrust13;

// Username and Password here...
factory.Credentials.UserName.UserName = "remote_user01";
factory.Credentials.UserName.Password = "the_password";

RequestSecurityToken rst = new RequestSecurityToken
{
     RequestType = Microsoft.IdentityModel.Protocols.WSTrust.WSTrust13Constants.RequestTypes.Issue,
     AppliesTo = new EndpointAddress(relyingPartyUri),
     KeyType = Microsoft.IdentityModel.Protocols.WSTrust.WSTrust13Constants.KeyTypes.Bearer,
};

IWSTrustChannelContract channel = factory.CreateChannel();

SecurityToken token = channel.Issue(rst);

//if authentication is failed, exception will be thrown. Error is inside the innerexception.
//Console.WriteLine("Token Id: " + token.Id);
Advertisements
Comments
  1. AKS says:

    Hi, What are the changes I have to do if I have to use ADFS 3.0 instead of ADFS 2.0

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s