EzDevInfo.com

adfs interview questions

Top adfs frequently asked interview questions

How can I imitate Stack Overflows SSO? Particularly where it federates with serverfault.com?

How does Stack Overflow's SSO work? ... whatever it is they are doing it seems to work for all sites in the network.

I'd like to learn what Stack is doing so I can see if it's possible to get a similar registration scheme between http://perfmon.com and http://eventvwr.com under ADFS. I understand that SAML and OpenID are different animals, but the concept of transparent registration should be the same.

Q: How does Stackoverflow "federate" with the other sites such as serverfault?


Source: (StackOverflow)

ADFS v2.0 : Finding errors referenced by the reference number

I get a number of browser error messages using ADFS, all of the form.

There was a problem accessing the site. Try to browse to the site again. If the problem persists, contact the administrator of this site and provide the reference number to identify the problem. Reference number: c14bcf7c-268d-46be-82c3-7c1d873c3df2

I have tried to find these in the event log to no avail.

How do you use the reference number to track down the errors?


Source: (StackOverflow)

Advertisements

What's the difference between ADFS, WIF, WS Federation, SAML, and STS?

These are numerous technologies and buzzwords used for single sign-on with Microsoft services.

Can someone explain ADFS, WIF, WS Federation, SAML, and STS (Security token service), including where and when each is being used.


Source: (StackOverflow)

Using WIF, what is the difference between audienceUris and realm?

We have an ASP.NET application using WIF. Our web.config file has a section like this:

<audienceUris>
    <add value="https://someapp.mycompany.com/App/" />
</audienceUris>
<federatedAuthentication>
    <wsFederation passiveRedirectEnabled="true" issuer="https://adfs.mycompany.com/adfs/ls/" realm="https://someapp.mycompany.com/App/" requireHttps="true" />
    <cookieHandler requireSsl="false" />
</federatedAuthentication>

Every example I see both the audienceUris and realm are the same value. What is the difference between these two? Do we need them both?


Source: (StackOverflow)

URL redirection from ADFS server

I'm using ADFS for authentication in my ASP.net web app. The STS server redirects the browser to https://test.contoso.com. STS doesn't allow any return URL parameter when redirecting the client to STS in the first place.

Would it be possible to redirect the browser from https://test.contoso.com (after redirection from STS) to any other URL, say https://variableName.test1.contoso2.com ?

Any help is much appreciated.


Source: (StackOverflow)

AADSTS50001: Getting exception while trying to access token from Azure AD by using ADAL from Console client

Getting exception while trying to access token from Azure AD by using ADAL from Console client.

Steps:

  1. I have configured Azure AD with my Web API application localhost:44307.
  2. Added the required configuration for Client Id, Client Key.
  3. Followed the work around by changing manifest suggested in this link. https://www.google.com/search?q=AADSTS50001+%2B+azure+AD+athentication&oq=AADSTS50001+%2B+azure+AD+athentication&aqs=chrome..69i57.10202j0j7&sourceid=chrome&espv=210&es_sm=93&ie=UTF-8#q=AADSTS50001&safe=active

ADAL Version Using: Microsoft.IdentityModel.Clients.ActiveDirectory 2.6.0-alpha

Console App Code:

void GetToken()
{
    clientId = "be6b055a-4efc-222a-2187-49657e6f4f1b";
    string ClientKey = "c/uIMlsqn9SzJLKKyBle42Ym+tgcaC2tbMlWxJQawE";
    string ClientCredential clientCred = new ClientCredential(clientId, ClientKey);

    authenticationContext = new AuthenticationContext("https://login.windows.net/MyDevAD.onmicrosoft.com");                
    authenticationResult = authenticationContext.AcquireToken("https://mylocalwebapiapp.com/", clientCred);
    ....
}

====================================================================================================================================================================

Fiddler Input:

POST https: //login.windows.net/MyDevAD.onmicrosoft.com/oauth2/token HTTP/1.1 Content-Type: application/x-www-form-urlencoded client-request-id: 53262b17-1234-4ed9-bdb3-748d332eb44b return-client-request-id: true x-client-SKU: .NET x-client-Ver: 2.6.0.0 x-client-CPU: x64 x-client-OS: Microsoft Windows NT 6.3.9600.0 Host: login.windows.net Content-Length: 185 Expect: 100-continue Connection: Keep-Alive

grant_type=client_credentials&resource=https%3A%2F%2Flocalhost%3A44307%2F&client_id=be6b055a-4efc-408a-8187-42137e6f4f1b&client_secret=c%2FuIMlsqn9SzJLKKyBle123Ym%2BtgcaC3tbMlWxJQawE%3D

==================================================================================================================================================================== Fiddler Output:

HTTP/1.1 400 Bad Request Cache-Control: no-cache, no-store Pragma: no-cache Content-Type: application/json; charset=utf-8 Expires: -1 Set-Cookie: x-ms-gateway-slice=ProductionB; path=/ x-ms-request-id: e89741b2-570d-44f6-9e71-6533b083abcd client-request-id: 35262b17-4771-4ed9-bdb3-748d332eb33b X-Content-Type-Options: nosniff X-Powered-By: ARR/3.0 X-Powered-By: ASP.NET Date: Tue, 01 Apr 2014 19:05:51 GMT Content-Length: 438

{"error":"invalid_resource","error_description":"AADSTS50001: Resource 'https://mylocalwebapiapp.com/' is not registered for the account.\r\nTrace ID: e89741b2-570d-44f6-9e71-6533b083cdad\r\nCorrelation ID: 35262b17-4771-4ed9-cddb3-748d332eb44b\r\nTimestamp: 2014-04-01 19:05:53Z","error_codes":[50001],"timestamp":"2014-04-01 19:05:53Z","trace_id":"e89741b2-570d-44f6-9e71-6533b083cdad","correlation_id":"35262b17-4771-4ed9-bdb3-748d332eb44b"}

==================================================================================================================================================================== Note: Posted URLS and ID's are faked ones.


Source: (StackOverflow)

SAML/ADFS node.js implementation guide?

I'd like to preface this by saying that until now, I hadn't even HEARD of SAML, much less developed a SSO strategy involving it. That, combined with the fact that I've barely been doing node for a year makes for a glorious newbie sandwich. Currently, I have a client who uses SAML and ADFS as their SSO provider. I am already using passport.js for local logins, so using passport-saml seems to be the way to go to implement the SSO using SAML/ADFS. In doing my research, I've found a couple different implementation guides, but since I literally know NOTHING about this process, I could use a few pointers.

In the passport-saml documentation, I found the following for a strategy proven to work with ADFS (according to the docs):

{
  entryPoint: 'https://ad.example.net/adfs/ls/',
  issuer: 'https://your-app.example.net/login/callback',
  callbackUrl: 'https://your-app.example.net/login/callback',
  cert: 'MIICizCCAfQCCQCY8tKaMc0BMjANBgkqh ... W==',
  identifierFormat: null
}

I suppose my main question is where does this cert come from? Is this a cert I generate on my server via SSL? Does the provider provide it?

In my searching, I have also found this: https://github.com/auth0/passport-wsfed-saml2, which is based on passport-saml. The following configuration is suggested for ADFS:

{
  path: '/login/callback',
  realm: 'urn:node:app',
  homeRealm: '', // optionally specify an identity provider 
  identityProviderUrl: 'https://auth10-dev.accesscontrol.windows.net/v2/wsfederation',
  cert: 'MIIDFjCCAf6gAwIBAgIQDRRprj9lv5 ... ='
}

In this example, the path object is obvious, and my provider has already given me an providerURL. But realm makes no sense to me, and there's that darn cert again.

Could someone provide me with an "explain-like-i'm-five" way of implementing SAML/ADFS SSO in a node.js site? Or help me make heads or tails of the argument objects requested by the two solutions I've outlined? Much appreciated in advance!


Source: (StackOverflow)

ADFS (CRM 2011) - Authentication Issue in Microsoft Outlook Client for CRM (Response.Redirect(...) & Window.Open(...))

Before I start, our customers have to connect through AFDS to be able to go on the CRM 2011. So we are talking about an “IFD”-environment.

I’m having a problem when using the “CRM 2011 Outlook Client” and the “Window.Open(…)”-JS function. When they hit a button in the CRM 2011 an ASPX-page fires up and does some stuff with an attachment in the e-mail. It then creates successfully a contact and then afterwards it should redirect to that “Contact”-page. But each time I do a redirect to a “CRM 2011”-page, the user is prompt for his credentials. That’s because the “Window.Open(…)” opens the screen in an new “Browser”-screen and the authentication is lost (because we come from the outlook client).

The above scenario works fine when using the “Web”-based CRM 2011, because you need first to login via ADFS.

Have some of you encountered the above problem and have a great solution to this?

  1. Is there a way to do a “Window.Open(…)” and stay in an “Outlook”-screen? The same as you should double-click a contact in the “CRM 2011 Outlook Client”?
  2. Is there a way while doing a “Redirect”, I can automatically give the credentials to the page, so that it will page will be opened without that the user himself need to enter his credentials? I’ve read something about SignInRequestMessage and FederatedAuthentication, but no clear examples were shown to do this.

I’m hoping that you guys can help me out. At my side, if I find any resolution, I will come back here!

Kind Regards, Frederic


Source: (StackOverflow)

Unexpected end of file. Following elements are not closed: Cookie, SecurityContextToken. Line 1, position 2998

I have implemented ADFS authentication for an asp.net 4.0 application. I have hosted the application in the production environment with webfarm configuration. The website works well and all the images are rendered properly in the IE8 browser. But when I tried to browse the application in the Safari browser the website does not works some times and the images are also not rendered properly.

By using Fiddler I found that the sometimes that images are not rendered properly and it comes with the following error :

Exception information:
Exception type: XmlException
Exception message: Unexpected end of file. Following elements are not closed: Cookie, SecurityContextToken. Line 1, position 2998.

Thread information:
    Thread ID: 12
    Thread account name: CT\acmeweb
    Is impersonating: False
    Stack trace:    at System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, String res, String arg1, String arg2, String arg3)
   at System.Xml.XmlExceptionHelper.ThrowUnexpectedEndOfFile(XmlDictionaryReader reader)
   at System.Xml.XmlBaseReader.MoveToEndOfFile()
   at System.Xml.XmlUTF8TextReader.Read()
   at System.Xml.XmlDictionaryReader.ReadContentAsChars(Char[] chars, Int32 offset, Int32 count)
   at System.Xml.XmlBaseReader.ReadBytes(Encoding encoding, Int32 byteBlock, Int32 charBlock, Byte[] buffer, Int32 offset, Int32 byteCount, Boolean readContent)
   at System.Xml.XmlBaseReader.ReadContentAsBase64(Byte[] buffer, Int32 offset, Int32 count)
   at System.Xml.XmlDictionaryReader.ReadContentAsBytes(Boolean base64, Int32 maxByteArrayContentLength)
   at System.Xml.XmlDictionaryReader.ReadContentAsBase64(Int32 maxByteArrayContentLength, Int32 maxInitialCount)
   at System.Xml.XmlBaseReader.ReadContentAsBase64()
   at System.Xml.XmlDictionaryReader.ReadElementContentAsBase64()
   at Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(XmlReader reader, SecurityTokenResolver tokenResolver)
   at Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(Byte[] token, SecurityTokenResolver tokenResolver)
   at Microsoft.IdentityModel.Web.SessionAuthenticationModule.ReadSessionTokenFromCookie(Byte[] sessionCookie)
   at Microsoft.IdentityModel.Web.SessionAuthenticationModule.TryReadSessionTokenFromCookie(SessionSecurityToken& sessionToken)
   at Microsoft.IdentityModel.Web.SessionAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs eventArgs)
   at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

I then tried to follow the below mentioned link :

http://social.msdn.microsoft.com/Forums/en/Geneva/thread/ea00ec3f-ebdf-427c-929f-d4a196650552

But it also did not worked for me. I then tried to stop one server in the webfarm configuration and then found that the website is working fine in the IE8 and Safari browser. In IE8 browser it works all time and all the images are rendered properly but the Safari browser does not in case when both the servers in the webfarm are turned on.

On analysis I found that from ADFS I am getting some claims information in the form of cookie and the cookie length is more. For IE8 browser the cookie length is more and for Safari the permissible limit is 4097 characters.

Hence I thought of maximizing the limit of cookie for the Safari browser.

Can anyone please help me out to resolve this issue by providing any code sample.

Thanks & Regards, Santosh Kumar Patro


Source: (StackOverflow)

HTTP 400: Bad Request error in ADFS HTTPS Request

I am writing a Node.js app and am trying to integrate an ADFS server to get authentication. For that, I am using wstrust-client, and using the ADFS Server URL as my endpoint. My code so far is:

app.get('/login', function(req, res) {
    trustClient.requestSecurityToken({
        scope: 'https://mycompany.com',
        username: "username",
        password: "password",
        endpoint: 'https://[adfs server]/adfs/services/trust/13/usernamemixed'
    }, function (rstr) {
         // Access the token
        var rawToken = rstr.token;
        console.log('raw: ' + rawToken);
    }, function(error) {
        console.log(error)
    }); 
});    

I am requesting https through wstrust-client

My code in wstrustclient.js so far is:

var req = https.request(post_options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function(data) {
        console.log("Entered res")

        var rstr = {
            token: parseRstr(data),
            response: res,
        };

        callback(rstr);
    }); 
});

req.write(message);
req.end();
req.on('error', function (e) { 
console.log("******************************");
console.log(e);
console.log("******************************");

However, it is throwing this error:

******************************
{ [Error: UNABLE_TO_VERIFY_LEAF_SIGNATURE]
    stack: 'Error: UNABLE_TO_VERIFY_LEAF_SIGNATURE\n   
    at SecurePair.<anonymous> (tls.js:1253:32)\n    
    at SecurePair.EventEmitter.emit (events.js:91:17)\n    
    at SecurePair.maybeInitFinished (tls.js:865:10)\n    
    at CleartextStream.read [as _read] (tls.js:416:15)\n  
    at CleartextStream.Readable.read (_stream_readable.js:231:10)\n  
    at EncryptedStream.write [as _write] (tls.js:329:25)\n  
    at EncryptedStream.Writable.write (_stream_writable.js:176:8)\n  
    at write (_stream_readable.js:496:24)\n 
    at flow (_stream_readable.js:506:7)\n    
    at Socket.pipeOnReadable (_stream_readable.js:538:5)' }
    ******************************
    ******************************
    { [Error: read ECONNRESET]
        stack: 'Error: read ECONNRESET\n   
        at errnoException (net.js:846:11)\n  
        at TCP.onread (net.js:508:19)',
        code: 'ECONNRESET',
        errno: 'ECONNRESET',
        syscall: 'read' }
    ******************************

When I browse the same endpoint URL in a browser, it throws HTTP 400: Bad Request

I know that it's an SSL type error, and that it's from the server-side. However, I don't know why it's throwing the error and what might be wrong server-side. What do I need to change?


Source: (StackOverflow)

How can I find out what my 'On-Premises Authority' url is?

I'm setting up a new .NET MVC project and want to use my local ADFS for managing users. I know the IP address of the machine my ADFS is running on and have tried using that for the 'On-Premises Authority' URL, but I got an message stating that it was incorrect.

Is there a command I can run to find the address/url that I should be using for this field?

For reference, this is the menu box I'm talking about: enter image description here


Source: (StackOverflow)

Securing backend WCF service with WIF using ADFS2 as IP

I’m having an issue using ADFS2 to secure a back-end WCF service that is being called from Passively Federated Website. I have the passive federation working on the website, but the back-end service is giving me problems.

The pieces of the puzzle.

  1. Silverlight Client that is being served from Passively Federated Website.
  2. The Silverlight calls a WCF service (App Service), hosted on the passively Federated Website.
  3. I have SaveBootstrapToken set to true in the config.
  4. From the App Service, I want to call a back-end WCF service using BootstrapToken with the ActAs scenarion.
  5. Federated Website and Back-end WCF service are setup as separate RPs in the ADFS2, token encryption is turned on. Both are allowed to delegate.

Back-end Service configuration:

I have WIF incorporated into the pipeline using behavior extension.

<ws2007FederationHttpBinding>
  <binding name="WS2007FederationHttpBinding_IQuoteService">
    <security mode="TransportWithMessageCredential">
      <message establishSecurityContext="false">
        <issuer address="https://myADFSserver/adfs/services/trust/13/issuedtokenmixedsymmetricbasic256">
        </issuer>
        <issuerMetadata address="https://myADFSserver/adfs/services/trust/mex">
        </issuerMetadata>
      </message>
    </security>
  </binding>
</ws2007FederationHttpBinding>


<behaviors>
  <serviceBehaviors>
    <behavior name="">
      <federatedServiceHostConfiguration name="Service.QuoteService" />
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="false" />
      <serviceCredentials>
        <serviceCertificate findValue="000000000000000000000000000000" storeLocation="LocalMachine" storeName="My" x509FindType="FindByThumbprint" />
      </serviceCredentials>
    </behavior>
  </serviceBehaviors>
</behaviors>

<services>
  <service name="Service.QuoteService">
    <endpoint address="" binding="ws2007FederationHttpBinding" contract="Service.IQuoteService" bindingConfiguration="WS2007FederationHttpBinding_IQuoteService" />
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
  </service>
</services>

Client Configuration

When add the service using Add Service Reference tooling, the following config on the client gets created:

<customBinding>
  <binding name="https://myADFSserver/adfs/services/trust/13/issuedtokenmixedsymmetricbasic256">
    <security defaultAlgorithmSuite="Default" authenticationMode="IssuedTokenOverTransport"
      requireDerivedKeys="false" securityHeaderLayout="Strict" includeTimestamp="true"
      keyEntropyMode="CombinedEntropy" messageSecurityVersion="WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10">
      <issuedTokenParameters keySize="256" keyType="SymmetricKey" tokenType="">
        <additionalRequestParameters>
          <trust:SecondaryParameters xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">
            <trust:KeyType>http://docs.oasis-open.org/ws-sx/ws-trust/200512/SymmetricKey</trust:KeyType>
            <trust:KeySize>256</trust:KeySize>
            <trust:KeyWrapAlgorithm>http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p</trust:KeyWrapAlgorithm>
            <trust:EncryptWith>http://www.w3.org/2001/04/xmlenc#aes256-cbc</trust:EncryptWith>
            <trust:SignatureAlgorithm>http://www.w3.org/2000/09/xmldsig#hmac-sha1</trust:SignatureAlgorithm>
            <trust:CanonicalizationAlgorithm>http://www.w3.org/2001/10/xml-exc-c14n#</trust:CanonicalizationAlgorithm>
            <trust:EncryptionAlgorithm>http://www.w3.org/2001/04/xmlenc#aes256-cbc</trust:EncryptionAlgorithm>
          </trust:SecondaryParameters>
        </additionalRequestParameters>
      </issuedTokenParameters>
      <localClientSettings cacheCookies="true" detectReplays="false"
        replayCacheSize="900000" maxClockSkew="00:05:00" maxCookieCachingTime="Infinite"
        replayWindow="00:05:00" sessionKeyRenewalInterval="10:00:00"
        sessionKeyRolloverInterval="00:05:00" reconnectTransportOnFailure="true"
        timestampValidityDuration="00:05:00" cookieRenewalThresholdPercentage="60" />
      <localServiceSettings detectReplays="false" issuedCookieLifetime="10:00:00"
        maxStatefulNegotiations="128" replayCacheSize="900000" maxClockSkew="00:05:00"
        negotiationTimeout="00:01:00" replayWindow="00:05:00" inactivityTimeout="00:02:00"
        sessionKeyRenewalInterval="15:00:00" sessionKeyRolloverInterval="00:05:00"
        reconnectTransportOnFailure="true" maxPendingSessions="128"
        maxCachedCookies="1000" timestampValidityDuration="00:05:00" />
      <secureConversationBootstrap />
    </security>
    <textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16"
      messageVersion="Default" writeEncoding="utf-8">
      <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
    </textMessageEncoding>
    <httpsTransport manualAddressing="false" maxBufferPoolSize="524288"
      maxReceivedMessageSize="65536" allowCookies="false" authenticationScheme="Anonymous"
      bypassProxyOnLocal="false" decompressionEnabled="true" hostNameComparisonMode="StrongWildcard"
      keepAliveEnabled="true" maxBufferSize="65536" proxyAuthenticationScheme="Anonymous"
      realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="false"
      useDefaultWebProxy="true" requireClientCertificate="false" />
  </binding>
</customBinding>


<ws2007FederationHttpBinding>
  <binding name="WS2007FederationHttpBinding_IQuoteService" closeTimeout="00:01:00"
    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
    bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
    maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text"
    textEncoding="utf-8" useDefaultWebProxy="true">
    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
      maxBytesPerRead="4096" maxNameTableCharCount="16384" />
    <reliableSession ordered="true" inactivityTimeout="00:10:00"
      enabled="false" />
    <security mode="Message">
      <message algorithmSuite="Default" issuedKeyType="SymmetricKey"
        negotiateServiceCredential="true">
        <issuer address="https://myADFSserver/adfs/services/trust/13/issuedtokenmixedsymmetricbasic256"
          binding="customBinding" bindingConfiguration="https://myADFSserver/adfs/services/trust/13/issuedtokenmixedsymmetricbasic256" />
        <issuerMetadata address="https://myADFSserver/adfs/services/trust/mex" />
        <tokenRequestParameters>
          <trust:SecondaryParameters xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">
            <trust:KeyType xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">http://docs.oasis-open.org/ws-sx/ws-trust/200512/SymmetricKey</trust:KeyType>
            <trust:KeySize xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">256</trust:KeySize>
            <trust:Claims Dialect="http://schemas.xmlsoap.org/ws/2005/05/identity"
              xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">
              <wsid:ClaimType Uri="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"
                Optional="true" xmlns:wsid="http://schemas.xmlsoap.org/ws/2005/05/identity" />
              <wsid:ClaimType Uri="http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
                Optional="true" xmlns:wsid="http://schemas.xmlsoap.org/ws/2005/05/identity" />
            </trust:Claims>
            <trust:KeyWrapAlgorithm xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p</trust:KeyWrapAlgorithm>
            <trust:EncryptWith xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">http://www.w3.org/2001/04/xmlenc#aes256-cbc</trust:EncryptWith>
            <trust:SignWith xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">http://www.w3.org/2000/09/xmldsig#hmac-sha1</trust:SignWith>
            <trust:CanonicalizationAlgorithm xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">http://www.w3.org/2001/10/xml-exc-c14n#</trust:CanonicalizationAlgorithm>
            <trust:EncryptionAlgorithm xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">http://www.w3.org/2001/04/xmlenc#aes256-cbc</trust:EncryptionAlgorithm>
          </trust:SecondaryParameters>
        </tokenRequestParameters>
      </message>
    </security>
  </binding>
</ws2007FederationHttpBinding>


<client>
  <endpoint address="http://myServiceHost/Service/QuoteService.svc"
    binding="ws2007FederationHttpBinding" bindingConfiguration="WS2007FederationHttpBinding_IQuoteService"
    contract="QuoteService.IQuoteService" name="WS2007FederationHttpBinding_IQuoteService">
    <identity>
      <certificate encodedValue="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" />
    </identity>
  </endpoint>
</client>

Here's the Service Client Code:

List<Quote> quoteList = new List<Quote>();

ClaimsPrincipal myClaimsPrincipal = System.Web.HttpContext.Current.User as ClaimsPrincipal;
SecurityToken bootstrapToken = myClaimsPrincipal.Identities[0].BootstrapToken;
if (bootstrapToken == null)
{
    throw new Exception("bootstrap tokein is null. Logout and try again.");
}

ChannelFactory<IQuoteServiceChannel> factory = new ChannelFactory<IQuoteServiceChannel>("WS2007FederationHttpBinding_IQuoteService");
factory.Credentials.SupportInteractive = false;

factory.Credentials.ServiceCertificate.SetDefaultCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint, "0000000000000000000000000000");
factory.ConfigureChannelFactory();

IQuoteServiceChannel channel;

//Create the channel with the bootstrap token
channel = factory.CreateChannelActingAs(bootstrapToken);

try
{
    quoteList = channel.GetQuotes(quoteUser);
    channel.Close();
}
catch (SecurityAccessDeniedException sadex)
{
    channel.Abort();
    throw;
}
catch (CommunicationException exception)
{
    channel.Abort();
    throw;
}
catch (TimeoutException timeoutEx)
{
    channel.Abort();
    throw;
}
catch (Exception ex)
{
    channel.Abort();
    throw;
}

return quoteList;

This is the exception I get:

System.ServiceModel.Security.SecurityNegotiationException was unhandled by user code
  Message=SOAP security negotiation with 'https://myADFSserver/adfs/services/trust/13/issuedtokenmixedsymmetricbasic256' for target 'https://myADFSserver/adfs/services/trust/13/issuedtokenmixedsymmetricbasic256' failed. See inner exception for more details.
  Source=mscorlib
  StackTrace:
    Server stack trace: 
       at System.ServiceModel.Security.IssuanceTokenProviderBase`1.DoNegotiation(TimeSpan timeout)
       at System.ServiceModel.Security.IssuanceTokenProviderBase`1.GetTokenCore(TimeSpan timeout)
       at System.IdentityModel.Selectors.SecurityTokenProvider.GetToken(TimeSpan timeout)
       at Microsoft.IdentityModel.Protocols.WSTrust.FederatedSecurityTokenProvider.GetTokenCore(TimeSpan timeout)
       at System.IdentityModel.Selectors.SecurityTokenProvider.GetToken(TimeSpan timeout)
       at System.ServiceModel.Security.SecurityProtocol.TryGetSupportingTokens(SecurityProtocolFactory factory, EndpointAddress target, Uri via, Message message, TimeSpan timeout, Boolean isBlockingCall, IList`1& supportingTokens)
       at System.ServiceModel.Security.SymmetricSecurityProtocol.TryGetTokenSynchronouslyForOutgoingSecurity(Message message, SecurityProtocolCorrelationState correlationState, Boolean isBlockingCall, TimeSpan timeout, SecurityToken& token, SecurityTokenParameters& tokenParameters, SecurityToken& prerequisiteWrappingToken, IList`1& supportingTokens, SecurityProtocolCorrelationState& newCorrelationState)
       at System.ServiceModel.Security.SymmetricSecurityProtocol.SecureOutgoingMessageCore(Message& message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState)
       at System.ServiceModel.Security.MessageSecurityProtocol.SecureOutgoingMessage(Message& message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState)
       at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)
       at System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.DoOperation(SecuritySessionOperation operation, EndpointAddress target, Uri via, SecurityToken currentToken, TimeSpan timeout)
       at System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.GetTokenCore(TimeSpan timeout)
       at System.IdentityModel.Selectors.SecurityTokenProvider.GetToken(TimeSpan timeout)
       at System.ServiceModel.Security.SecuritySessionClientSettings`1.ClientSecuritySessionChannel.OnOpen(TimeSpan timeout)
       at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
       at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
       at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
       at System.ServiceModel.Channels.ServiceChannel.CallOpenOnce.System.ServiceModel.Channels.ServiceChannel.ICallOnce.Call(ServiceChannel channel, TimeSpan timeout)
       at System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan timeout, CallOnceManager cascade)
       at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
       at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
       at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
    Exception rethrown at [0]: 
       at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
       at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
       at OMG.Admin.DemoApp.Business.QuoteService.IQuoteService.GetQuotes(User quoteUser)
       at OMG.Admin.DemoApp.Business.QuoteServiceClient.GetQuotes(User quoteUser) in C:\OMG_TFS01\OMG.Admin\OMG.Admin.DemoApp\OMG.Admin.DemoApp.Business\QuoteServiceClient.cs:line 131
       at OMG.Admin.DemoApp.Business.QuoteBO.GetQuoteList() in C:\OMG_TFS01\OMG.Admin\OMG.Admin.DemoApp\OMG.Admin.DemoApp.Business\QuoteBO.cs:line 26
       at OMG.Admin.DemoApp.Web.Services.DemoAppService.GetQuotes() in C:\OMG_TFS01\OMG.Admin\OMG.Admin.DemoApp\OMG.Admin.DemoApp.Web\Services\DemoAppService.svc.cs:line 27
       at SyncInvokeGetQuotes(Object , Object[] , Object[] )
       at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
       at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
  InnerException: System.InvalidOperationException
       Message=The address of the security token issuer is not specified. An explicit issuer address must be specified in the binding for target 'https://myADFSserver/adfs/services/trust/13/issuedtokenmixedsymmetricbasic256' or the local issuer address must be configured in the credentials.
       Source=mscorlib
       StackTrace:
         Server stack trace: 
            at System.ServiceModel.ClientCredentialsSecurityTokenManager.CreateIssuedSecurityTokenProvider(InitiatorServiceModelSecurityTokenRequirement initiatorRequirement)
            at System.ServiceModel.ClientCredentialsSecurityTokenManager.CreateSecurityTokenProvider(SecurityTokenRequirement tokenRequirement, Boolean disableInfoCard)
            at Microsoft.IdentityModel.Protocols.WSTrust.FederatedClientCredentialsSecurityTokenManager.CreateSecurityTokenProvider(SecurityTokenRequirement tokenRequirement)
            at System.ServiceModel.Security.SecurityProtocol.AddSupportingTokenProviders(SupportingTokenParameters supportingTokenParameters, Boolean isOptional, IList`1 providerSpecList)
            at System.ServiceModel.Security.SecurityProtocol.OnOpen(TimeSpan timeout)
            at System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan timeout)
            at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
            at System.ServiceModel.Channels.SecurityChannelFactory`1.ClientSecurityChannel`1.OnOpen(TimeSpan timeout)
            at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
            at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
            at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
         Exception rethrown at [0]: 
            at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
            at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
            at System.ServiceModel.ICommunicationObject.Open(TimeSpan timeout)
            at System.ServiceModel.Security.IssuanceTokenProviderBase`1.DoNegotiation(TimeSpan timeout)
       InnerException:

I'm sure I'm missing something in the configuration and/or code can someone help me out?


Source: (StackOverflow)

Windows Presentation Foundation (WPF) + Windows Identity Foundation (WIF)

Scenario: I need to configure a WPF application to send credentials from integrated security to an ADFS server and receive tokens back. I can't find guides describing in detail how to do this. The focus seems to be on web applications, web services, & WCF.

What are the steps to configure a WPF client? Is it possible to setup through a config file the same way a web app is configured?


Source: (StackOverflow)

Authenticating against AD FS from a .Net 4.5 Console App

I'm in the process of getting my head round using AD FS to authenticate a user in a .NET 4.5 app. I can't find any examples of requesting/receiving the token from a console app and converting that token into a ClaimsPrinciple. The only examples I can find are WCF configuration based and I would really like to see the actual code that can do this in it's simplest form.

I've installed AD FS and think I've got it configured ready to receive requests. I've created a relying party, given it a key and assigned a couple of claims to it.

Can anyone point me in the right direction or what I need to do now in my console app to send authentication requests to it?

Thanks


Source: (StackOverflow)

How to validate ADFS SAML token

I am currently generating SAML tokens from ADFS like this:

 WSTrustChannelFactory factory = null;
        try
        {
            // use a UserName Trust Binding for username authentication
            factory = new WSTrustChannelFactory(
                new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                 new EndpointAddress("https://adfs.company.com/adfs/services/trust/13/usernamemixed"));

            factory.TrustVersion = TrustVersion.WSTrust13;

            factory.Credentials.UserName.UserName = "user";
            factory.Credentials.UserName.Password = "pw";


            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo = new EndpointReference(relyingPartyId),
                KeyType = KeyTypes.Bearer
            };
            IWSTrustChannelContract channel = factory.CreateChannel();
              GenericXmlSecurityToken genericToken = channel.Issue(rst) 
               as     GenericXmlSecurityToken;
         }
        finally
        {
            if (factory != null)
            {
                try
                {
                    factory.Close();
                }
                catch (CommunicationObjectFaultedException)
                {
                    factory.Abort();
                }
            }
        }

Now let's say I build a web application that uses these tokens for authentication. As far as I know the workflow should be like this:

  • Generate token
  • client gets generated token (after valid login)
  • client caches token
  • client uses token for next login
  • web application validates token, does not have to call ADFS

How can I validate that the token the client presents is valid? Do I need the certificate of the ADFS server to decrypt the token?


Source: (StackOverflow)