Blogs

Sign-up and sign-in with PayPal using Azure AD B2C

This article describes how to add authentication for a PayPal account to an Azure AD B2C custom policy.

Architecture

The following diagram illustrates the authentication flow for a PayPal account to an Azure AD B2C custom policy.

The authentication flow requires an Azure function that retrieves claims for the authenticated user.

For information about PayPal and OAuth 2.0, see https://developer.paypal.com/docs/log-in-with-paypal/.

Prerequisites

  1. If you don’t already have one, then you must create an Azure AD B2C tenant that is linked to your Azure subscription.
  2. Prepare your Azure AD B2C tenant by creating the token signing and encryption keys and creating the Identity Experience Framework applications.
  3. Download one of the starter packs for Azure AD B2C from Microsoft’s GitHub repository.

Create the Azure function

  1. Create a C# function containing the following code. This implements a GetPayPalClaims function that retrieves flattened claims for the authenticated user. Then publish this C# function to a function app.
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;

namespace SignInWithPayPal
{
    public static class GetPayPalClaims
    {
        private static readonly HttpClient InnerClient = new HttpClient();

        [FunctionName("GetPayPalClaims")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequest request,
            ILogger logger)
        {
            if (!request.Headers.TryGetValue("Authorization", out var authorizationHeaderValues))
            {
                logger.LogError("The Authorization header is missing");
                return new BadRequestResult();
            }

            if (authorizationHeaderValues.Count > 1)
            {
                logger.LogError("The Authorization header is invalid");
                return new BadRequestResult();
            }

            var authorizationHeaderValue = authorizationHeaderValues[0];
            var authorizationHeaderValueParts = authorizationHeaderValue.Split(' ');

            if (authorizationHeaderValueParts.Length != 2 || !authorizationHeaderValueParts[0].Equals("Bearer", StringComparison.OrdinalIgnoreCase))
            {
                logger.LogError("The Authorization header is invalid");
                return new BadRequestResult();
            }

            var innerRequest = new HttpRequestMessage(HttpMethod.Get, "https://api-m.sandbox.paypal.com/v1/identity/oauth2/userinfo?schema=paypalv1.1");
            innerRequest.Headers.Authorization = new AuthenticationHeaderValue(authorizationHeaderValueParts[0], authorizationHeaderValueParts[1]);
            var innerResponse = await InnerClient.SendAsync(innerRequest);

            if (innerResponse.StatusCode != HttpStatusCode.OK)
            {
                return new InternalServerErrorResult();
            }

            var innerResponseModel = await innerResponse.Content.ReadAsJsonAsync<PayPalClaimsResponseModel>();

            var responseModel = new
            {
                id = innerResponseModel.PayerId,
                name = innerResponseModel.Name,
                email = innerResponseModel.Emails?.First(email => email.Primary).Value
            };

            return new OkObjectResult(responseModel);
        }
    }
}

The model classes are implemented as follows.

using System.Collections.Generic;
using Newtonsoft.Json;

namespace SignInWithPayPal
{
    public class PayPalClaimsResponseModel
    {
        [JsonProperty(PropertyName = "emails")]
        public List<PayPalEmailModel> Emails { get; set; }

        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }

        [JsonProperty(PropertyName = "payer_id")]
        public string PayerId { get; set; }
    }

    public class PayPalEmailModel
    {
        [JsonProperty("primary")]
        public bool Primary { get; set; }

        [JsonProperty("value")]
        public string Value { get; set; }
    }
}

The ReadAsJsonAsync extension method is implemented as follows.

using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace SignInWithPayPal
{
    public static class HttpContentExtensions
    {
        public static async Task<T> ReadAsJsonAsync<T>(this HttpContent content)
        {
            if (content == null)
            {
                return default;
            }

            var value = await content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<T>(value);
        }
    }
}

Configure a PayPal application

  1. Log in to https://developer.paypal.com/developer/applications/.
  2. On the My apps & credentials page, select Create App.
  3. On the Create New App page, enter the following fields and then select Create App:
    1. App name
    2. App Type: Merchant
    3. Sandbox Business Account
  4. On the app page, in the Sandbox API Credentials section, copy the Client ID and Secret fields.
  5. On the app page, in the Sandbox App Settings section, enter the following fields, and then select Save:
    1. Return URL: Enter either https://your-tenant-name.b2clogin.com/your-tenant-name.onmicrosoft.com/oauth2/authresp if you use the built-in domain or https://your-domain-name/your-tenant-name.onmicrosoft.com/oauth2/authresp if you use a custom domain for the Return URL field. Replace your-tenant-name with your tenant name and your-domain-name with your custom domain.
    2. App feature options: Deselect all app feature options, select Log in with PayPal, and then enter the following fields:
      1. Personal profile: Full name, Email
      2. Account information: PayPal account ID (payer ID)
      3. Links are shown on the customer consent page: Privacy policy URL, User agreement URL

Add the client secret for the PayPal application as a policy key

  1. Sign in to the Azure AD B2C portal.
  2. Select Identity Experience Framework.
  3. Select Policy keys.
  4. Select Add.
  5. In the Create a key section, enter the following fields and then select Create:
    1. Options: Manual
    2. Name: PayPalClientSecret
    3. Secret: Paste the Client secret field that was copied in the previous section.

Configure PayPal as an identity provider

  1. Open the TrustFrameworkExtensions.xml file.
  2. Find the ClaimsProviders element. If it doesn’t exist, then add it to the TrustFrameworkPolicy element.
  3. Add the following ClaimsProvider element to the ClaimsProviders element. Replace your-paypal-client-id with the Client ID field that was copied in the Configure a PayPal application section. Replace your-function-app-name with the function app name that was created in the Create the Azure function section.
<ClaimsProvider>
  <Domain>paypal.com</Domain>
  <DisplayName>PayPal</DisplayName>
  <TechnicalProfiles>
    <TechnicalProfile Id="PayPal-OAuth2">
      <DisplayName>PayPal</DisplayName>
      <Protocol Name="OAuth2" />
      <Metadata>
        <Item Key="client_id">your-paypal-client-id</Item>
        <Item Key="authorization_endpoint">https://www.sandbox.paypal.com/connect</Item>
        <Item Key="AccessTokenEndpoint">https://api-m.sandbox.paypal.com/v1/oauth2/token</Item>
        <Item Key="ClaimsEndpoint">https://your-function-app-name.azurewebsites.net/api/GetPayPalClaims</Item>
        <Item Key="AdditionalRequestQueryParameters">flowEntry=static</Item>
        <Item Key="scope">openid profile email https://uri.paypal.com/services/paypalattributes</Item>
        <Item Key="HttpBinding">POST</Item>
        <Item Key="token_endpoint_auth_method">client_secret_basic</Item>
        <Item Key="BearerTokenTransmissionMethod">AuthorizationHeader</Item>
        <Item Key="UsePolicyInRedirectUri">false</Item>
      </Metadata>
      <CryptographicKeys>
        <Key Id="client_secret" StorageReferenceId="B2C_1A_PayPalClientSecret" />
      </CryptographicKeys>
      <OutputClaims>
        <OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="socialIdpAuthentication" AlwaysUseDefaultValue="true" />
        <OutputClaim ClaimTypeReferenceId="identityProvider" DefaultValue="paypal.com" AlwaysUseDefaultValue="true" />
        <OutputClaim ClaimTypeReferenceId="issuerUserId" PartnerClaimType="id" />
        <OutputClaim ClaimTypeReferenceId="displayName" PartnerClaimType="name" />
        <OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="email" />
      </OutputClaims>
      <OutputClaimsTransformations>
        <OutputClaimsTransformation ReferenceId="CreateRandomUPNUserName" />
        <OutputClaimsTransformation ReferenceId="CreateUserPrincipalName" />
        <OutputClaimsTransformation ReferenceId="CreateAlternativeSecurityId" />
      </OutputClaimsTransformations>
      <UseTechnicalProfileForSessionManagement ReferenceId="SM-SocialLogin" />
    </TechnicalProfile>
  </TechnicalProfiles>
</ClaimsProvider>

Add a user journey

  1. Open the TrustFrameworkBase.xml file.
  2. Copy the UserJourney element that includes Id="SignUpOrSignIn".
  3. Open the TrustFrameworkExtensions.xml file and find the UserJourneys element. If it doesn’t exist, then add it to the TrustFrameworkPolicy element.
  4. Paste the UserJourney element that was copied in step 2 to the UserJourneys element and replace the Id attribute for this UserJourney element from "SignUpOrSignIn" to "PayPalSignUpOrSignIn".

Add the identity provider to the user journey

  1. Add the claims provider that was configured in the Configure PayPal as an identity provider section to the user journey that was added in the previous section.
<OrchestrationStep Order="1" Type="CombinedSignInAndSignUp" ContentDefinitionReferenceId="api.signuporsignin">
  <ClaimsProviderSelections>
    ...
    <ClaimsProviderSelection TargetClaimsExchangeId="PayPalExchange" />
  </ClaimsProviderSelections>
  ...
</OrchestrationStep>

<OrchestrationStep Order="2" Type="ClaimsExchange">
  ...
  <ClaimsExchanges>
    <ClaimsExchange Id="PayPalExchange" TechnicalProfileReferenceId="PayPal-OAuth2" />
  </ClaimsExchanges>
  ...
</OrchestrationStep>

Configure the relying party policy

  1. Open the SignUpOrSignIn.xml file.
  2. Replace the ReferenceId attribute for the DefaultUserJourney element from "SignUpOrSignIn" to "PayPalSignUpOrSignIn".
<RelyingParty>
  <DefaultUserJourney ReferenceId="PayPalSignUpSignIn" />
  ...
</RelyingParty>

Upload and test the custom policy

  1. Upload all policy files in the following order to your Azure AD B2C tenant:
    1. TrustFrameworkBase.xml
    2. TrustFrameworkLocalization.xml
    3. TrustFrameworkExtensions.xml
    4. SignUpOrSignIn.xml
  2. Test the B2C_1A_signup_signin policy from your Azure AD B2C tenant.
[mailpoet_form id="1"]

Other Recent Blogs

Level 9, 360 Collins Street, 
Melbourne VIC 3000

Level 2, 24 Campbell St,
Sydney NSW 2000

200 Adelaide St,
Brisbane QLD 4000

191 St Georges Terrace
Perth WA 6000

Level 10, 41 Shortland Street
Auckland

Part of

Arinco trades as Arinco (VIC) Pty Ltd and Arinco (NSW) Pty Ltd. © 2023 All Rights Reserved Arinco™ | Privacy Policy
Arinco acknowledges the Traditional Owners of the land on which our offices are situated, and pay our respects to their Elders past, present and emerging.

Get started on the right path to cloud success today. Our Crew are standing by to answer your questions and get you up and running.