ASP.NET Server Side SDK

Summary

In this topic you will get an overview how to use the ASP.NET Server Side SDK to connect to The Identity Hub.

Contents

  • Installing the SDK
  • Configuring the SDK WS-Federation
  • Authentication using WS-Federation
  • Configuring the SDK OAuth 2.0
  • Authentication using OAuth 2.0
  • Getting Profile Information from Claims
  • Initialize the Identity Service
  • Set AccessToken
  • Getting Profile Information
  • Getting Friends Information
  • Api

Installing the SDK

To install the TheIdentityHub.AspNet NuGet package, run the following command in the Package Manager Console (Tools | Library Package Manager | Package Manager Console)


Install-Package TheIdentityHub.AspNet
 

Configuring the SDK WS-Federation

To configure the SDK, add the following configuration to the web.config:

        <configuration>
            <configSections>
                <section name="system.identityModel" type="System.IdentityModel.Configuration.SystemIdentityModelSection, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
                <section name="system.identityModel.services" type="System.IdentityModel.Services.Configuration.SystemIdentityModelServicesSection, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
            </configSections>
            <location path="FederationMetadata">
                <system.web>
                    <authorization>
                        <allow users="*" />
                    </authorization>
                </system.web>
            </location>
            <system.web>
                <authorization>
                    <deny users="?" />
                </authorization>
                <authentication mode="None" />
                <compilation targetFramework="4.5" />
                <httpRuntime targetFramework="4.5" requestValidationMode="4.5" />
            </system.web>
            <system.webServer>
                <modules>
                    <remove name="FormsAuthentication" />
                    <add name="WSFederationAuthenticationModule" type="System.IdentityModel.Services.WSFederationAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
                    <add name="SessionAuthenticationModule" type="System.IdentityModel.Services.SessionAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
                </modules>
            </system.webServer>
            <system.identityModel>
                <identityConfiguration>
                    <audienceUris>
                        <add value="[Relying Party Realm]" />
                    </audienceUris>
                    <issuerNameRegistry type="System.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
                        <trustedIssuers>
                            <add name="[Trusted Issuer Id]" thumbprint="[Token Signing Certificate Thumbprint]" />
                        </trustedIssuers>
                    </issuerNameRegistry>
                </identityConfiguration>
            </system.identityModel>
            <system.identityModel.services>
                <federationConfiguration>
                    <serviceCertificate><certificateReference x509FindType="FindBySubjectDistinguishedName" findValue="[Relying Party Certificate Subject Distinguished Name]" storeLocation="LocalMachine" storeName="My" /></serviceCertificate>
                    <cookieHandler requireSsl="true" />
                    <wsFederation passiveRedirectEnabled="true" issuer="https://www.theidentityhub.com/[Tenant Url]/wsfed" realm="[Relying Party Realm]" reply="https://[Website Reply Url]" requireHttps="true" />
                </federationConfiguration>
            </system.identityModel.services>
        </configuration>
                 
Example configurations are available for ASP.NET System.IdentityModel and ASP.NET Microsoft.IdentityModel on the App detail page in the “WS-Federation Web Applications and Relying Parties” section

Authentication using WS-Federation

When the web application requires authentication the SDK will automatically redirect the user to The Identity Hub to provide his or her credentials through one of the available identity providers.

Configuring the SDK OAuth 2.0

To configure the SDK, add the following configuration to the web.config:

        <configuration>
            <appSettings>
                <!-- THE IDENTITY HUB SPECIFIC CONFIG -->
                <add key="TIH_baseUrl" value="[The Identity Hub Tenant url]" />
                <add key="TIH_clientId" value="[The application Client Id]" />
                <add key="TIH_clientSecret" value="[The application Client Secret]" />
                <add key="TIH_redirectUri" value="[The web application url]" />
                <add key="TIH_identificationExpires" value="[Number of minutes identification is valid]" />
                <add key="TIH_useSession" value="[true or false]" />
                <add key="TIH_useIdentification" value="[true or false]" />
            </appSettings>
            <system.webServer>
                <modules>
                    <!-- THE IDENTITY HUB SPECIFIC CONFIG -->
                    <remove name="FormsAuthentication" />
                    <add name="HubAuthenticationModule" ty-pe="TheIdentityHub.HubAuthenticationModule, TheIdentityHub, Version=1.3.0.0, Culture=neutral, PublicKeyToken=25fd43e98a2121e5" />
                </modules>
            </system.webServer>
        </configuration>
            
An example config file per specific application can be downloaded from The Identity Hub application detail page (in the “Web Applications” Section).

Configuration options

TIH_baseUrl

Thr url of the tenant https://www.theidentityhub.com/{tenant}

TIH_clientId

The Client Id of the App as configured in the tenant.

TIH_clientSecret

The Client Secret of the App as configured in the tenant.

TIH_redirectUri

The web application url to return to after authentication.

TIH_useIdentification

If set to true, will keep the identification of the user upon next visit (not authorized). Default is false.

TIH_identificationExpires

How long (in minutes) to keep the identification of the user upon next visit (not authorized). Default is 480 (8 hours).

TIH_useSession

If set to true, will store a cookie and keep the user authorized in next browsing sessions. Default is true.

Authentication using OAuth 2.0

When the web application requires authentication the SDK will automatically redirect the user to The Identity Hub to provide his or her credentials through one of the available identity providers. In ASP.NET MVC for instance the authentication can be required by using the [Authorize] attribute (https://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute.aspx)

Getting Profile Information from Claims

If your ASP.NET site you can use the following code to get the profile information. See API documentation at the end for more extension methods.

using TheIdentityHub;
var displayName = this.User.DisplayName();
var smallPicture = this.User.SmallPicture();
var emailAddresses = this.User.EmailAddresses();
...
             

Initialize the Identity Service


// Initialize
var identityService = new IdentityService();
                     
If you use the constructor as done above, the SDK will us the configuration as set in the web.config file and try to get the Access Token from the access token claim on the current principal. If no such claim is found, an error will be thrown.

If you want to specify your own token, base url and client id, use the constructor as shown below.

Set AccessToken


// Your ClientId
var clientId = "4a-aez54e6a4z65ed$";
// Your base URL
var baseUrl = new Uri("https://www.theidentityhub.com/[TenantUrl]");
// Access Token
var accessToken = "546465qzer-Lm";
// Initialize
var identityService = new IdentityService(clientId, baseUrl, accessToken);
                     

Role Support

The SDK also supports the IsInRole method and thus role based authorization (https://msdn.microsoft.com/en-us/library/system.security.principal.iprincipal.isinrole.aspx)

Getting Profile Information


// Get profile info.
var profile = await identityService.GetProfileAsync();
                     

Updating Profile Information


// Update profile info.
await identityService.UpdateProfileAsync(profile);
                     

Getting Friends Information


// Get friends info.
var friends = await identityService.GetFriendsAsync();
                     

Api

TheIdentityHub.Account

Represents an account belonging to an identity.

Name Value Description
AccountId System.String Gets the account identifier
AccountPrivatePersonalIdentifier System.String The account private personal identifier
DisplayName System.String Gets the display name.
EmailAddress System.String Gets the email address.
PictureUrl System.String Gets the picture URL.

TheIdentityHub.AccountProvider

Represents an account provider.

Name Value Description
AccountProviderId System.String Gets the account provider identifier
Accounts TheIdentityHub.Account[] Gets the accounts.
DisplayName System.String Gets the display name.
ProviderImageUrl System.String Gets the provider image URL.

TheIdentityHub.Friend

Represents a friend.

Name Value Description
DisplayName System.String Gets the display name of the friend.
IdentityId System.String Gets the identifier of the friend.
LargePictures System.String[] Gets the large pictures of the friend.
MediumPictures System.String[] Gets the medium pictures of the friend.
SmallPicture System.String Gets the first small picture of the friend.
SmallPictures System.String[] Gets the small pictures of the friend.

TheIdentityHub.HubAuthenticationModule

Http modul to facilitates sign-in and sign-out

Name Description
SignOut Redirect the browser to link an account to the current identity.
CreateAuthenticateRedirectUrl(HttpRequestBase httpRequest, Uri replyUrl, string accountProviderId) Creates an URL to redirect and start the login flow.

TheIdentityHub.IdentityExtensions

Provides extension methods for principal objects to retrieve The Identity Hub provided claims.

Name Description
AccessToken Gets an OAuth 2.0 Access Token for the specified principal, that can be used to call The Identity Hub API to get more information about the identity.
DisplayName Gets the display name for the specified principal.
EmailAddress Gets the e-mail address of the specified principal.
EmailAddresses Gets the e-mail address of the specified principal.
IdentityId Gets the identity identifier for the specified principal.
LargePicture Gets the url of a large identity picture for the specified principal.
LargePictures Gets the url of the large identity pictures for the specified principal.
MediumPicture Gets the url of a medium identity picture for the specified principal.
MediumPictures Gets the url of the medium identity pictures for the specified principal.
Name Gets the unique identifier for the specified principal.
Roles Gets the roles for the specified principal.
SmallPicture Gets the url of a small identity picture for the specified principal.
SmallPictures Gets the url of a small identity pictures for the specified principal.

TheIdentityHub.IdentityHubError

Represents error information when a The Identity Hub API call fails.

Name Value Description Remarks
ErrorDetails TheIdentityHub.IdentityHubErrorDetail[] An array of TheIdentityHub.IdentityHubErrorDetail instances containing detailed error information.
Message String A general error message.

TheIdentityHub.IdentityHubErrorDetail

Represents detailed error information when a The Identity Hub API call fails.

Name Value Description Remarks
Id String Error identifier
Message String A detailed error message.
Name Description
ToString Returns a String that contains the detailed error information.

TheIdentityHub.IdentityHubException

Represents an exception thrown when a The Identity Hub API call fails.

Name Value Description Remarks
IdentityHubError TheIdentityHub.IdentityHubError A TheIdentityHub.IdentityHubError instance containing error information.

TheIdentityHub.IdentityService

Provides methods to query an identity's profile.

Name Description
IdentityService(string, Uri) Initializes a new instance of the TheIdentityHub.IdentityService class for the given client indentifier and base URL
IdentityService(string, Uri, string) Initializes a new instance of the TheIdentityHub.IdentityService class for the given client indentifier, base URL and Access Token
Name Value Description Remarks
AccessToken String The access token.
BaseUrl System.Uri Gets the base URL.
ClientId System.String Gets the client identifier.
Name Description
AddAccount Redirect the browser to link an account to the current identity.
DeleteProfileAsync Deletes the profile of the current identity.
GetAccountProvidersAsync Gets the account providers.
GetAccountProvidersAsync(long identityId) Gets the account providers of specified user.
GetFriendsAsync Gets the friends.
GetFriendsAsync(long identityId) Gets the friends of the specified user.
GetProfileAsync Gets the profile.
GetProfileAsync(long identityId) Gets the profile of the specified user.
GetRolesAsync Gets the roles.
GetRolesAsync(long identityId) Gets the roles of the specified user.
RequireTwoFactorAuthenticationAsync Indicates wether or not the user was authenticated using two-factor authentication. If not redirects the browser to let the current identity perform two-factor authentication.
UpdateProfileAsync Updates the profile.

TheIdentityHub.Profile

Represents an identity.

Name Value Description
Disabled System.Bool Gets a value indicating whether the identity has been disabled.
DisplayName System.String Gets the display name of the identity.
EmailAddress System.String Gets the email address of the identity.
EmailAddressVerified System.Bool Gets a value indicating whether the email address of the identity has been verified.
GivenName System.String Gets the name of the given of the identity.
IdentityId System.String Gets the identifier of the identity.
LargePictures System.String[] Gets the large pictures of the identity.
MediumPictures System.String[] Gets the medium pictures of the identity.
OldIdentityIds System.String[] Gets the identity id(s) of the identities that were merged
Picture System.Uri Gets the primary picture of the identity.
Properties System.Collections.Generic.Dictionary<string, string[]> Gets a dictionary of properties of the identity.
SmallPictures System.String[] Gets the small pictures of the identity.
Surname System.String Gets the surname of the identity.

TheIdentityHub.Role

Represents a role.

Name Value Description
Name System.String Gets the name of the role.