Friday 16 August 2019

SharePoint On premises People Picker with Azure AD Graph Api

Search Users and Groups From Azure AD


Requirement:

We have to integrate our SharePoint on premises People Picker with Azure AD, so user can search users/groups coming from Azure AD.

Steps:


  1. Graph API
  2. Inherit web part with SPClaimsProvider class
  3. Call Graph API in FillSearchMethod
  4. Deployment

1: Graph API

To find Azure AD users, groups, All users/ groups etc we have to use Graph API provided by Microsoft. In simple language if developer requires to search something from Azure AD Graph Api full fill this requirements. To read more about available Graph APIs please visit Microsoft documentation.
URL Graph API Documentation: https://docs.microsoft.com/en-us/graph/use-the-api

Following APIs will be used to search users and groups from Azure AD for People Picker:
  • Create Authentication Token: https://login.microsoftonline.com/{TenantID}/oauth2/token
    Example: https://login.microsoftonline.com/2909k32e-b3db-4aad-86o4-n3f7b65t235h/oauth2/token
    Response in Postman:
  • Search User: 
    https://graph.microsoft.com/v1.0/users?$filter=displayName eq 'Derrick Ramirez'
    Response in Postman:
  • Search Group: 
    https://graph.microsoft.com/v1.0/groups/?$filter=startswith(displayName,'aa_azureapps')
    Response in Postman:

2: Inherit web part with SPClaimProvider class

  • Create a Empty web part using visual studio (Farm solution or Sandbox)
  • Inherit class like this public class ClaimProvider : SPClaimProvider
  • Implement this class just by right clicking on SPClaimProvider, it will generate multiple methods FillClaimsForEntity, FillResolve, FillEntityTypes, FillSearch for now we just have to add code in FillSearch Method protected override void FillSearch(Uri context, string[] entityTypes, string searchPattern, string hierarchyNodeID, int maxCount, SPProviderHierarchyTree searchTree) { //Call Graph API here }

3: Call Graph API in FillSearchMethod

  1. Customize FillSearch Method: Your FillSearch Method should look like this: protected override void FillSearch(Uri context, string[] entityTypes, string searchPattern, string hierarchyNodeID, int maxCount, SPProviderHierarchyTree searchTree) { try { string NameOfUserOrGroup = searchPattern.ToLower(); APIResponseObject usersgroups = new APIResponseObject(); usersgroups = SearchUsersGroupFromAzureAD(NameOfUserOrGroup, "SecretKey", "GraphApiUrl", "ClientId"); //Get these keys from Azure Portal // string claimType = GenerateClaimType.GetClaimType("Email"); foreach (var user in usersgroups.value) { PickerEntity entity = CreatePickerEntity(); //If its group name because Azure AD doesn't have UPN So if (user.userPrincipalName == null || user.userPrincipalName == "") { //entity.Claim = CreateClaimForSTS(claimType, user.displayName); entity.Description = user.displayName; entity.DisplayText = user.displayName; entity.EntityData[PeopleEditorEntityDataKeys.DisplayName] = user.displayName; entity.EntityType = SPClaimEntityTypes.SecurityGroup; } //else its user name else { //entity.Claim = CreateClaimForSTS(claimType, user.mail); entity.Description = user.mail; entity.DisplayText = user.displayName; entity.EntityData[PeopleEditorEntityDataKeys.DisplayName] = user.mail; entity.EntityType = SPClaimEntityTypes.User; entity.EntityType = SPClaimEntityTypes.FormsRole; } entity.IsResolved = true; searchTree.AddEntity(entity); } } catch (Exception ex) { } }
  2. Call Graph API Method
    Here you can call Graph API the way which suits you just like to call Rest API using C# webclient. Note: To Call Graph API first we have create token using /oauth2/token api. public RootObject SearchUsersGroupFromAzureAD(string SearchPattern, string ClientSecret, string GraphApiUrl, string ClientId) { try { var client = new WebClient(); byte[] byteArray = Encoding.ASCII.GetBytes(""); //Call this API https://graph.microsoft.com/v1.0/users?$filter=displayName eq 'Derrick Ramirez' string Url = "https://graph.microsoft.com/v1.0/users?$filter=displayName eq 'SearchPattern'"; var allAdUsers = client.DownloadData(new Uri(Url)); if(allAdUsers != null || allAdUsers !=""){ string encodeUsers = Encoding.ASCII.GetString(allAdUsers); JavaScriptSerializer serilizeObject = new JavaScriptSerializer(); RootObject Users = serilizeObject.Deserialize<RootObject>(encodeUsers); return Users;} else{ //Call this API https://graph.microsoft.com/v1.0/groups/?$filter=startswith(displayName,'aa_azureapps') string Url = "https://graph.microsoft.com/v1.0/groups/?$filter=startswith(displayName,'SearchPattern')"; var allAdUsers = client.DownloadData(new Uri(Url)); string encodeUsers = Encoding.ASCII.GetString(allAdUsers); JavaScriptSerializer serilizeObject = new JavaScriptSerializer(); RootObject Users = serilizeObject.Deserialize<RootObject>(encodeUsers); return Users; } } catch (Exception ex) { throw; } }
  3. Convert API response to Deserialize Object

public class Value { //public List<object> businessPhones { get; set; } public string displayName { get; set; } public string givenName { get; set; } public string jobTitle { get; set; } public string mail { get; set; } public string mobilePhone { get; set; } public string officeLocation { get; set; } public object preferredLanguage { get; set; } public string surname { get; set; } public string userPrincipalName { get; set; } public string id { get; set; } } public class RootObject { public List<Value> value { get; set; }

}
Deployment: Just add, install and enable this web part and enjoy to fetch Azure AD users and Groups. Unit Test:

After Deployment visit web application depends you have enabled this feature for farm level or specific web application then go to Site permissions and enter user email or group name. It will return you result from Azure AD. If you have any query feel free to comment, i will try my best to resolve on my earliest. Thanks
Search Users and Groups From Azure AD



Thursday 8 August 2019

Single sign on SharePoint with Azure


Single Sign On (SSO) with Azure AD and SharePoint Server




Version 1.0





Contents


We are going integrate SharePoint On premises with Azure AD using Claims(Claims outputs provided by any 3rd party). we will cover Authentication of users from Azure AD groups too.

  1.     Prerequisite
    To enable bridge between Azure AD and On premises SharePoint you need have following items already configured.
    a.       Azure Subscription
    b.      SharePoint server any version
    c.       Azure AD users synced or non-synced 
  2.     Overview
    This configuration consists of two main platforms.
    1.       Azure AD with enterprise application
    2.       SharePoint 2010 server identity provider

    We have to configure Azure AD in such a way so SharePoint can be accessed via Azure AD users and enable SSO experience for SharePoint by authenticating users from Azure AD.
    First, we will configure azure with SAML base authentication and will add users to provide access to this newly created azure application for SSO. You can configure these users later but its compulsory step.
    Second, we will configure SharePoint on premises server in such a way so it can communicate with Azure AD by creating Claim base authentication.

  3.     Azure AD with Enterprise application
     First login to Azure Portal using this URL: https://portal.azure.com/
    To connect SharePoint on premises with Azure AD first we have to add SharePoint on premises application from gallery to our application list.







     3.1 Steps to add SharePoint on premises application
1: From the left navigation of Azure portal click Azure Active Directory Icon.

2: Click Enterprise Applications and then select All Applications.


   Select All applications:








         
3: Add new application by clicking on New Application Button just beside columns button.

        4: In add from gallery search box type “SharePoint On premises” Just click on this                     application and provide name to this application if you want to change name by default           name “SharePoint on-premises” then click add.


    3.2 Configure Azure AD SSO:

    1: Just after completion of app creation navigate to Single Sign-on as showing in following       image:
       2: Select Single Sign-on Method SAML



      3: Set up Single Sign-On with SAML screen, click Edit icon to open Basic SAML                        Configuration dialog. In this page enter SharePoint on premises configurations.


      4: On the basic SAML configuration screen, do the following steps

a: Identifier (Entity ID) in this text box type URL with this pattern urn:sharepoint:federation for example urn:sharepoint:OnPremisiseSharePointUrl.com i.e.

b: Reply URL in this text box type URL with this pattern: https://<YourSharePointServerURL>/_trust/default.aspx
For example https://OnPremisiseSharePointUrl.com/_trust/default.aspx

c: Sign-on URL in this text box, type a URL using the following pattern:

https://<YourSharePointServerURL>/_trust/default.aspx


Note for Point b and c:
It should be with https not http else our redirection to SharePoint site will not work and URL should contain /_trust/ why we are using this, will discuss during SharePoint identity provider configuration steps.

After these configurations save this screen and back to Set up Sign-On with SAML Screen.

5: The screen we discussed at point 3 should be in front of you. From the SAML Signing Certificate portion download the Certificate (Base64). We will be using this certificate during SharePoint on premises server configuration.




6: From portion 4 copy these values save some in notepad.




Note: Login URL you will get will be like this: https://login.microsoftonline.com/638dc12b-863f-4882-a2f8-a3f6d9cli75v/saml2 just replace saml2 with wsfed and save this final URL in your personal notepad file. Final URL should be like this: https://login.microsoftonline.com/638dc12b-863f-4882-a2f8-a3f6d9cli75v/wsfed


7: Before leaving Azure Portal you should have following items in your system:
          i: Base64 Certificate downloaded at point 5.
         ii: Entity Identifier value set at point 4 sub point a.
        iii: Login and Logout URL discussed at point 6.

4:   SharePoint on-premises Single Sign-On Configurations


In following configurations, we will configure SharePoint on premises environment to create Identity provider to communicate with Azure AD.

4.1 Configure Identity Provider

1: Login to Server where you have installed SharePoint.

2: Configure new Trusted Identity Provider in SharePoint Server using the following PowerShell script:
                Just update three values in this script then happy to execute script$realm = 'urn:sharepoint:onPremisesSharePointWebUrl.com'

$wsfedurl= 'https://login.microsoftonline.com/638dc12b-863f-4882-a2f8-a3f6d9cli75v/wsfed'

$filepath= 'C:/temp/SharePoint SSO.cer'

$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($filepath)New-SPTrustedRootAuthority -Name "AzureSSOPortal" -Certificate $cert

$map = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name" -IncomingClaimTypeDisplayName "name" -LocalClaimType "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn"

$map2 = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname" -IncomingClaimTypeDisplayName "GivenName" -SameAsIncoming

$map3 = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname" -IncomingClaimTypeDisplayName "SurName" -SameAsIncoming

$map4 = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" -IncomingClaimTypeDisplayName "Email" -SameAsIncoming

$map5 = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" -IncomingClaimTypeDisplayName "Role" -SameAsIncoming

$ap = New-SPTrustedIdentityTokenIssuer -Name "AzureAD" -Description "SharePoint secured by AzureSSOPortal" -realm $realm -ImportTrustCertificate $cert -ClaimsMappings $map,$map2,$map3,$map4,$map5 -SignInUrl $wsfedurl -IdentifierClaim "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"

$realm in this variable put entity identifier value copied from Azure.
$wsfedurl in this variable put login URL copied from Azure don’t forget to replace saml with wsfed.
$filepath give path where you have pasted Base64 certificated downloaded from Azure.


3: Sometimes by default Claim providers are not enabled in SharePoint for this you have to run following script:
           $setcba = Get-SPWebApplication "http://OnPremisesSharePointWebApplicationURL.com/"
$setcba.UseClaimsAuthentication = 1;
$setcba.Update()

 4.2 Activate Identity Provider SharePoint On Premises

1: In Central Administration, navigate to Manage Web Application and select the web application that you wish to secure with Azure AD.

2: In the ribbon, click Authentication Providers and choose the zone that you wish to use.
3: Select Trusted Identity provider and select the identify provider you just registered named AzureAD.
4: On the sign-in page URL setting, select Custom sign in page and provide the value “/_trust/”.
5: Click OK.
Note: “/_trust/” we are using this so we can redirect to Microsoft Login page as we defined in Azure SSO configuration.

Now final Step
Go to: IIS-> Web application -> Authentication -> Enable Anonymous Authentication & Forms Authentication and Disable windows Authentication on all servers for this specific web application.  

5: Test SSO Configurations

In our scenario because users are synced with Azure AD so we don’t have to create manual user in Azure AD. Just go to SharePoint web application where you have applied Identity provider then navigate to Permission policy and add user as per Azure AD user and give controls you want to give.
In alternative mapping select your web application and add same http url with https with default zone.




After this just visit web application it will redirect you to Microsoft Login enter your credentials and enjoy.
          Microsoft Login Page should appear with following parameters
1: In your URL there should be your tenant ID 638dc12b-863f-4882-a2f8-a3f6d9cli75v
2: URN entity identifier should be there in URL which shows our redirection is fine.

If you unable to login please use following step:
1: Enter your credentials as per the user defined in Azure AD. If user failed to login on the same screen it will give you four values Request ID, Correlation ID, Time Stamp and Message Error.
Just copy these values and paste on azure portal test application screen.


Note for future Blogs:
1: In People Picker all users and groups will be resolved it can be solved by developing Custom Claims Provider.
Follow this link to fetch users and groups from Azure AD:
https://sharepointenvironment.blogspot.com/2019/08/sharepoint-on-premises-people-picker.html

2: To Resolve audience issue UPS should be synced with Claims provider i will write blog on this.

3: To revert changes back to windows authentication first remove trust integration by vising CA-> Web applications -> Select Web application and uncheck the trust provider then save. After this run this script:
  $setcba = Get-SPWebApplication "http://OnPremisesSharePointWebApplicationURL.com/"
  $setcba.UseClaimsAuthentication = 0;
  $setcba.Update()

4: Sign Out and Sign in as a different URL can be set using IIS using Rewrite URL will write Blog on this.

5: Custom Claims Provider integration with Graph API will write Blog on this.
Follow this link to integrate Graph API:
https://sharepointenvironment.blogspot.com/2019/08/sharepoint-on-premises-people-picker.html

6: Add new claims in current Claims will write blog on this soon.

If you need any assistance please feel free to comment i will resolve your problem. Thanks for reading.