Get email address from SAML Response using Single

2019-02-19 16:17发布

问题:

I am in the process of setting up a single sign on (SSO) system using ADFS and SAML 2.0. I have to following scenario that I am stuck on:

1) User attempts to access web resource, is not logged in so is directed to ADFS SSO service.

2) User successfully authenticates against ADFS.

3) ADFS passes SAML Response back to web resource.

4) The web resource itself has a user database but the user does not exist here.

5) So, the web resource must create the user account silently. To do this I need the email address.

So, is it possible to configure ADFS to return the email address of the user in a successful SAML response message?

回答1:

You can configure ADFS to return an Email claim, provided ADFS has some way of getting this (Active Directory or some other attribute store, maybe a database it can access?) and provided your application is set up to decrypt the returned token to read the claims inside.

Assuming this is ADFS 2.0:

  1. Set up your web resource as a Relying Party Trust (sounds like you've done this)
  2. Right-click the RP and choose Edit Claim Rules...
  3. On the Issuance Transform Rules tab, add a new rule for Email address

If you can get the email from Active Directory because your users are authenticating through a domain, then you can choose the "Send LDAP Attributes as Claims" rule template.

Otherwise, you'll have to pick "Send Claims Using a Custom Rule" and set up a custom attribute store (to the database or whatever it is) and go through the motions of writing a claim rule to do it.

Once you have that set up, in your ASP.NET app you'll need to configure it to use ADFS as your token issuer. This is accomplished with the Windows Identity Framework Microsoft.IdentityModel.dll and associated configuration. If you've installed the WIF SDK, you should have some extra options in Visual Studio, namely if you right-click your web project there should be an "Add STS Reference" option. This will run FedUtil which is a wizard that will automatically set up your web.config appropriately. Google around for how to set things up.

Now that your site is using ADFS for claims, you'll need to make a few changes. Under the <microsoft.identityModel> section in your web.config, ensure that you have set it to save the bootstrap token (<service saveBootstrapTokens="true">). In your code, you can now access the email claim whenever you need it by doing:

string email = (User.Identity as IClaimsIdentity).Claims.Where(c => c.ClaimType == ClaimTypes.Email).FirstOrDefault().Value;

If you don't set it to save the bootstrap token, then the Claims collection there will be empty.

There's potentially a lot of other factors that can mess things up along the way, though. Hopefully this will get you on the right track.