The OpenID Connect Handbook

TL;DR: In August 2019, Auth0 published an ebook called The OpenID Connect Handbook to help developers leverage this modern identity layer to provide an easy and secure authentication mechanism to their users. This ebook covers all the main concepts that you must know to integrate your app with OpenID Connect providers. If you are in a hurry and would like to dive right into the content of the ebook, follow this link to get your free copy. The rest of this article will summarize the content of the ebook so you can take a glimpse of what you will learn about on the ebook.

The Contents of the OpenID Connect Handbook

As of October 2019, the handbook covers six main areas related to OpenID Connect. Each area has a chapter of its own that is subdivided into other sections to help you understand OpenID Connect, how this identity layer was born, and how to use it to secure your applications:

  1. Introduction
  2. OpenID Connect Introduction
  3. OpenID Connect in Action
  4. OpenID Connect and Traditional Web Applications
  5. Traditional Web Apps and the Delegated Authorization Flow
  6. OpenID Connect and Single-Page Applications

The following sections will cover each one of these chapters separately, so you can learn what to expect on them. Hopefully, if you are looking to learn about a topic in particular, you will be able to download the free ebook and dive right into it.

Introduction

The Introduction chapter of this handbook disserts about topics that are not part of OpenID Connect per se, but that are important for you to grasp before you start learning about it. In this chapter, you will learn about the terms Entity and Identity and you will learn about how they are interconnected. There, you will learn that an entity has multiple identities and that people, or other entities, perceive entities through their identities.

Every entity have multiple identities that others use to perceive them.

After that, you will learn about the terms Authentication and Authorization. More specifically, you will learn how these terms are related, how one thing can lead to another, and how they differ. Authentication vs. Authorization is an important topic that causes great confusion, even on members of the IT workforce around the world.

Authentication and authorization are topics that cause confusion and that are often used interchangeably by mistake.

OpenID Connect Introduction

After learning about the conceptual topics that preamble this ebook, you will start learning about OpenID Connect. This chapter will begin by guiding you through a ten-thousand-foot overview of how an OpenID Connect authentication transaction works. After that, you will briefly read about other authentication mechanisms and how the IT community went from simple usernames and passwords, to Kerberos, to SAML, and OpenID Connect.

A brief illustration that shows how SAML works.

The chapter will then move into more details about the OpenID Connect specification and will talk about OAuth 2.0, the underlying technology that the identity layer builds on top. In the end, you will read about some OpenID Connect use cases so you can learn when this technology can be helpful.

OpenID Connect in Action

The next chapter on the ebook, called OpenID Connect in Action, will start to teach you the inner workings of the OpenID Connect specification. There, you will set up an OpenID Connect provider that you will use through the hands-on exercises, and you will prepare your local environment to run the samples that you will learn about. As the goal of the ebook is to show, step by step, how you can secure your applications with OpenID Connect, the exercises will use the most popular programming language in the world (i.e., JavaScript) to lower the barrier.

Creating an OpenID Connect provider to use throughout the handbook exercises

OpenID Connect and Traditional Web Applications

Having created your OpenID Connect provider and prepared your local development environment, the next chapter will be the first hands-on activity of the ebook. However, besides being a hands-on activity, the chapter will also teach about important topics such as the authentication flows. You will find a few other useful resources on the internet that inform you about OpenID Connect. The main problem with them, which this ebook aims at solving, is that they introduce a lot of theory before giving you anything you can use.

In this ebook, you will see that you will learn about the abstract parts of OpenID Connect on the fly. That is, instead of investing time to learn about all the different authentication flows that OpenID Connect supports and about all the abstract terms involved in them, this ebook will briefly teach you about them, then it will use these concepts right away.

For example, after you read about what an authentication flow is, you will jump right into using one. Besides that, you will read and learn how to use Discovery Endpoints, an prominent piece of OpenID Connect providers, right away. You will also learn about other important topics in this chapter like the Authentication Callback and user profiles.

Traditional Web Apps and the Delegated Authorization Flow

After you learn about how OpenID Connect securely promotes end-user authentication, the ebook will continue by teaching you about one of the most prominent scenarios where OpenID Connect and OAuth 2.0 are used: on delegated authorization. The chapter will show you all you need to know about this kind of authorization but, basically speaking, delegate authorization is when you let an app act on your behalf. The example that you will read about everywhere, including in this ebook, is when a third-party application wants to help you schedule tweets. In this scenario, this third-party app will have to ask you for permission to tweet on your behalf on the date and time you configure it. When this app issues a request to Twitter to create the tweet, the app will be acting on your behalf.

Delegated authorization sample where the app wants to tweet on behalf of the user.

OpenID Connect and Single-Page Applications

The last chapter of the handbook (so far, because we will publish more chapters soon) talks about how to secure Single-Page Applications with OpenID Connect. In the modern internet, most popular apps (and those that are not popular also) are using this approach to promote a better user experience to their customers. Therefore, it wouldn’t make sense to have an ebook that does not cover the most popular paradigm when it comes to web development.

In this chapter, you will learn about terms like PKCE (Proof of Key for Code Exchange) while integrating a single-page app with your OpenID Connect provider. Besides that, you will also take a look at a popular alternative called the Implicit Grant and why this approach is not encouraged anymore. As SPAs are usually hosted as static files in a cloud provider, you will also use delegated authorization in this chapter. That is, you will have an API that contains data that belong to users and you will make the SPA ask users permission to consume this API on their behalf.

Single-Page Apps can securely authenticate end-users with OpenID Connect providers by using PKCE.

Conclusion

As you can see, if you are interested in learning about OpenID Connect and how this technology can help you secure your applications, you came to the right place. In this ebook, you will learn everything you need to make your apps behave as OpenID Connect clients and how to make them consume APIs on their users behalf. Another interesting thing that you will learn in this handbook is about how popular and official SDKs (like the ones supported by Auth0) can help you be more efficient. That is, the ebook will show you everything you need to code in any application to make it integrate with an OpenID Connect provider, but it will also show you a more straightforward way to achieve your goals. With this, you will have both the tools to debug any misconfiguration and to be as focused as possible on what makes your app unique.

If you need help with any matter related to the OpenID Connect Handbook or to identity, authentication, and authorization, let us know in the comment box below.

#web-development #security #OpenID

What is GEEK

Buddha Community

The OpenID Connect Handbook

PostgreSQL Connection Pooling: Part 4 – PgBouncer vs. Pgpool-II

In our previous posts in this series, we spoke at length about using PgBouncer  and Pgpool-II , the connection pool architecture and pros and cons of leveraging one for your PostgreSQL deployment. In our final post, we will put them head-to-head in a detailed feature comparison and compare the results of PgBouncer vs. Pgpool-II performance for your PostgreSQL hosting !

The bottom line – Pgpool-II is a great tool if you need load-balancing and high availability. Connection pooling is almost a bonus you get alongside. PgBouncer does only one thing, but does it really well. If the objective is to limit the number of connections and reduce resource consumption, PgBouncer wins hands down.

It is also perfectly fine to use both PgBouncer and Pgpool-II in a chain – you can have a PgBouncer to provide connection pooling, which talks to a Pgpool-II instance that provides high availability and load balancing. This gives you the best of both worlds!

Using PgBouncer with Pgpool-II - Connection Pooling Diagram

PostgreSQL Connection Pooling: Part 4 – PgBouncer vs. Pgpool-II

CLICK TO TWEET

Performance Testing

While PgBouncer may seem to be the better option in theory, theory can often be misleading. So, we pitted the two connection poolers head-to-head, using the standard pgbench tool, to see which one provides better transactions per second throughput through a benchmark test. For good measure, we ran the same tests without a connection pooler too.

Testing Conditions

All of the PostgreSQL benchmark tests were run under the following conditions:

  1. Initialized pgbench using a scale factor of 100.
  2. Disabled auto-vacuuming on the PostgreSQL instance to prevent interference.
  3. No other workload was working at the time.
  4. Used the default pgbench script to run the tests.
  5. Used default settings for both PgBouncer and Pgpool-II, except max_children*. All PostgreSQL limits were also set to their defaults.
  6. All tests ran as a single thread, on a single-CPU, 2-core machine, for a duration of 5 minutes.
  7. Forced pgbench to create a new connection for each transaction using the -C option. This emulates modern web application workloads and is the whole reason to use a pooler!

We ran each iteration for 5 minutes to ensure any noise averaged out. Here is how the middleware was installed:

  • For PgBouncer, we installed it on the same box as the PostgreSQL server(s). This is the configuration we use in our managed PostgreSQL clusters. Since PgBouncer is a very light-weight process, installing it on the box has no impact on overall performance.
  • For Pgpool-II, we tested both when the Pgpool-II instance was installed on the same machine as PostgreSQL (on box column), and when it was installed on a different machine (off box column). As expected, the performance is much better when Pgpool-II is off the box as it doesn’t have to compete with the PostgreSQL server for resources.

Throughput Benchmark

Here are the transactions per second (TPS) results for each scenario across a range of number of clients:

#database #developer #performance #postgresql #connection control #connection pooler #connection pooler performance #connection queue #high availability #load balancing #number of connections #performance testing #pgbench #pgbouncer #pgbouncer and pgpool-ii #pgbouncer vs pgpool #pgpool-ii #pooling modes #postgresql connection pooling #postgresql limits #resource consumption #throughput benchmark #transactions per second #without pooling

Ian  Robinson

Ian Robinson

1623250560

An Introduction To Data Connectivity and Data Connectivity Solutions

In this article, we discuss facts about data connectivity, the related concepts, its benefits, as well as a discussion on some data connectivity solutions.

Introduction

In today’s world, data is the crux of major business decisions used by organizations all over the world. As such, it is imperative that the organizations have access to the right data and be able to analyze and make business decisions proactively. This article talks about data connectivity, the related concepts, its benefits, as well as a discussion on some data connectivity solutions.

#big data #data connectivity #data connectivity solutions #connectivity

The OpenID Connect Handbook

TL;DR: In August 2019, Auth0 published an ebook called The OpenID Connect Handbook to help developers leverage this modern identity layer to provide an easy and secure authentication mechanism to their users. This ebook covers all the main concepts that you must know to integrate your app with OpenID Connect providers. If you are in a hurry and would like to dive right into the content of the ebook, follow this link to get your free copy. The rest of this article will summarize the content of the ebook so you can take a glimpse of what you will learn about on the ebook.

The Contents of the OpenID Connect Handbook

As of October 2019, the handbook covers six main areas related to OpenID Connect. Each area has a chapter of its own that is subdivided into other sections to help you understand OpenID Connect, how this identity layer was born, and how to use it to secure your applications:

  1. Introduction
  2. OpenID Connect Introduction
  3. OpenID Connect in Action
  4. OpenID Connect and Traditional Web Applications
  5. Traditional Web Apps and the Delegated Authorization Flow
  6. OpenID Connect and Single-Page Applications

The following sections will cover each one of these chapters separately, so you can learn what to expect on them. Hopefully, if you are looking to learn about a topic in particular, you will be able to download the free ebook and dive right into it.

Introduction

The Introduction chapter of this handbook disserts about topics that are not part of OpenID Connect per se, but that are important for you to grasp before you start learning about it. In this chapter, you will learn about the terms Entity and Identity and you will learn about how they are interconnected. There, you will learn that an entity has multiple identities and that people, or other entities, perceive entities through their identities.

Every entity have multiple identities that others use to perceive them.

After that, you will learn about the terms Authentication and Authorization. More specifically, you will learn how these terms are related, how one thing can lead to another, and how they differ. Authentication vs. Authorization is an important topic that causes great confusion, even on members of the IT workforce around the world.

Authentication and authorization are topics that cause confusion and that are often used interchangeably by mistake.

OpenID Connect Introduction

After learning about the conceptual topics that preamble this ebook, you will start learning about OpenID Connect. This chapter will begin by guiding you through a ten-thousand-foot overview of how an OpenID Connect authentication transaction works. After that, you will briefly read about other authentication mechanisms and how the IT community went from simple usernames and passwords, to Kerberos, to SAML, and OpenID Connect.

A brief illustration that shows how SAML works.

The chapter will then move into more details about the OpenID Connect specification and will talk about OAuth 2.0, the underlying technology that the identity layer builds on top. In the end, you will read about some OpenID Connect use cases so you can learn when this technology can be helpful.

OpenID Connect in Action

The next chapter on the ebook, called OpenID Connect in Action, will start to teach you the inner workings of the OpenID Connect specification. There, you will set up an OpenID Connect provider that you will use through the hands-on exercises, and you will prepare your local environment to run the samples that you will learn about. As the goal of the ebook is to show, step by step, how you can secure your applications with OpenID Connect, the exercises will use the most popular programming language in the world (i.e., JavaScript) to lower the barrier.

Creating an OpenID Connect provider to use throughout the handbook exercises

OpenID Connect and Traditional Web Applications

Having created your OpenID Connect provider and prepared your local development environment, the next chapter will be the first hands-on activity of the ebook. However, besides being a hands-on activity, the chapter will also teach about important topics such as the authentication flows. You will find a few other useful resources on the internet that inform you about OpenID Connect. The main problem with them, which this ebook aims at solving, is that they introduce a lot of theory before giving you anything you can use.

In this ebook, you will see that you will learn about the abstract parts of OpenID Connect on the fly. That is, instead of investing time to learn about all the different authentication flows that OpenID Connect supports and about all the abstract terms involved in them, this ebook will briefly teach you about them, then it will use these concepts right away.

For example, after you read about what an authentication flow is, you will jump right into using one. Besides that, you will read and learn how to use Discovery Endpoints, an prominent piece of OpenID Connect providers, right away. You will also learn about other important topics in this chapter like the Authentication Callback and user profiles.

Traditional Web Apps and the Delegated Authorization Flow

After you learn about how OpenID Connect securely promotes end-user authentication, the ebook will continue by teaching you about one of the most prominent scenarios where OpenID Connect and OAuth 2.0 are used: on delegated authorization. The chapter will show you all you need to know about this kind of authorization but, basically speaking, delegate authorization is when you let an app act on your behalf. The example that you will read about everywhere, including in this ebook, is when a third-party application wants to help you schedule tweets. In this scenario, this third-party app will have to ask you for permission to tweet on your behalf on the date and time you configure it. When this app issues a request to Twitter to create the tweet, the app will be acting on your behalf.

Delegated authorization sample where the app wants to tweet on behalf of the user.

OpenID Connect and Single-Page Applications

The last chapter of the handbook (so far, because we will publish more chapters soon) talks about how to secure Single-Page Applications with OpenID Connect. In the modern internet, most popular apps (and those that are not popular also) are using this approach to promote a better user experience to their customers. Therefore, it wouldn’t make sense to have an ebook that does not cover the most popular paradigm when it comes to web development.

In this chapter, you will learn about terms like PKCE (Proof of Key for Code Exchange) while integrating a single-page app with your OpenID Connect provider. Besides that, you will also take a look at a popular alternative called the Implicit Grant and why this approach is not encouraged anymore. As SPAs are usually hosted as static files in a cloud provider, you will also use delegated authorization in this chapter. That is, you will have an API that contains data that belong to users and you will make the SPA ask users permission to consume this API on their behalf.

Single-Page Apps can securely authenticate end-users with OpenID Connect providers by using PKCE.

Conclusion

As you can see, if you are interested in learning about OpenID Connect and how this technology can help you secure your applications, you came to the right place. In this ebook, you will learn everything you need to make your apps behave as OpenID Connect clients and how to make them consume APIs on their users behalf. Another interesting thing that you will learn in this handbook is about how popular and official SDKs (like the ones supported by Auth0) can help you be more efficient. That is, the ebook will show you everything you need to code in any application to make it integrate with an OpenID Connect provider, but it will also show you a more straightforward way to achieve your goals. With this, you will have both the tools to debug any misconfiguration and to be as focused as possible on what makes your app unique.

If you need help with any matter related to the OpenID Connect Handbook or to identity, authentication, and authorization, let us know in the comment box below.

#web-development #security #OpenID

App Only Authentication in SharePoint Online using PnP PowerShell

Azure AD App only authencitation is being used for authenticating to M365 services and doing some operations like read the data, upload the data or to do some backend jobs via automation scripts.  Microsoft encourages to use certificate-based authentication for your applications registered in Azure AD to authenticate to the M365 or any cloud services. CBA is an extremely robust and secure mechanism for validating user’s identity. 

In this article, I want to discuss about the use case that I came across recently. Previously I am using SharePoint App Only authentication which is the concept from ACS (Azure Control services) where the Site Collection can admin can create Client ID and Client Secret by appending /_layouts/appregnew.aspx in the site collection thus by using the client credentials in application. However, there are few issues using this ACS app-only access token method

  • The authentication is not secure. MSFT encourages to switch to Azure AD App only authentication.
  • If you want your application to talk to multiple site collections, it is required to create multiple client ID and secrets which becomes cumbersome to deal with.

More about the ACS Token based-authentication can be referred in the references section.

The good news is that in the Azure AD App, the API permissions for the SharePoint have come with new permissions called “Sites.Selected”, which will allow your Azure AD App to authenticate to multiple site collection using single Client and certificate details. 

Before going to this Azure AD App only authentication using certificates, we will try to understand what is Certificate Based Authentication (aka CBA) in Azure AD. There are 2 types of CBA in Azure AD. 

  1. Certificate-based authentication with Federated AD FS
  2. Azure AD Certificate-based authentication

Certificate-based authentication with Federated AD FS

Previously in order to implement the CBA, ADFS services needs to be deployed between users and Azure AD. CBA with ADFS uses X.509 certificates to authenticate against azure AD.

  • Here user signs to application with their credentials and also with certificate installed on their devices.
  • ADFS validates the user credentials and certificate and on success passes Access tokens to the user to access the applications.

Azure AD certificate-based authentication

The latest version which is Azure AD CBA doesn’t need configuration and deploying of AD FS. The users can directly interact with Azure AD and authenticate against the applications.

For more details on CBA with AD FS and Azure AD CBA you can go through the articles mentioned in the references section.

Pre-requisites

  • PnP.Powershell version 1.10.0. Note that the authentication using CBA is updated in this version.

  • PowerShell version 5.1 or later
  • The account used to run the PowerShell commands should have ‘Global Admin’ rights.

Create Azure AD App

Now we will go through the steps to create Azure AD App, with API permissions “Sites. Selected” of type “Application”. Then use this Azure AD App to authenticate to multiple site collections.In order to successfully follow the article it is required to have the latest PnP Powershell version installed.

Step 1

Open the PowerShell ISE or command windows as administrator.

Step 2

Register the application by running the below PS command. Make sure the account that is running the below commands should have ‘Global Admin’ rights. Follow the prompts if the account has MFA (Multi-Factor Authentication Enabled)

Register-PnPAzureADApp -ApplicationName SPSitesSelected -Tenant contosodev.onmicrosoft.com -Store CurrentUser -SharePointApplicationPermissions "Sites.Selected" -Interactive

Certificate Based Authentication To Connect To SharePoint Online Sites

Certificate Based Authentication To Connect To SharePoint Online Sites

Step 3

On successful authentication, you will be getting the below message which says to wait for 60 seconds to check for required artifacts and start the consent flow.

Certificate Based Authentication To Connect To SharePoint Online Sites

Step 4

You will be asked to authenticate one more time to register the App and then to create certificate and thumbprint. Follow the prompts again

Certificate Based Authentication To Connect To SharePoint Online Sites

Step 5

Now you will have the consent pop up on successful authentication similar to below. It shows the App name (In this case it is SPSites Selected), and options to Accept and cancel.

Certificate Based Authentication To Connect To SharePoint Online Sites

You can also verify the app details by clicking on the ‘App Info’.

Step 6

After agreeing to consent by clicking on ‘Accept’ you should see following information from the command output window.

Certificate Based Authentication To Connect To SharePoint Online Sites

You will have following values,

  • Pfx file: it includes both public and private key information associated to certificated. This should not be shared outside your organization.
  • Cer file: it has public key and some information about the device (in this case the server). This is typically exchanged with partners.
  • Thumbprint: A secure key associated with certificate used to authenticate to application.
  • Base64Encoded: This is the certificate information in ascii string format.

You need to make note of only Client ID, Thumbprint, and the location of the Pfx and Cer files.

The above steps confirms that Azure AD application is created with required permissions which is ‘Sites.Selected’. This means the Azure AD app can be now configured to authenticate to only specific sites.

Granting Access to Azure AD App

Now for granting access to Azure AD App, run the following set of commands.

Step 1

Login to SharePoint admin URL for your tenant using PnP PowerShell Module with Global Admin credentials.

Connect-PnPOnline -Url "https://contoso-admin.sharepoint.com" -Interactive

Certificate Based Authentication To Connect To SharePoint Online Sites

Step 2

On authentication you will be getting the following information, about the permissions on what the PnP Management shell could do.

Here you can consent on behalf of organization or leave it unchecked. If you checked ‘Consent on behalf of your organization’ no other user will be prompted for consent.

Step 3

Grant the permission to the app by running the following command. Please note that there is only 2 set of permissions you can grant to app, which is ‘Read’ or ‘Write’.

Grant-PnPAzureADAppSitePermission -AppId 'YOUR APP ID HERE' -DisplayName 'APP DISPLAY NAME HERE' -Site 'https://contosodev.sharepoint.com/sites/CBADemo1' -Permissions Write

Certificate Based Authentication To Connect To SharePoint Online Sites

Validation

Step 1

Validate the access to the app by connecting to sites that are granted permissions. You should see the content without any issue. In this case, disconnect from the previous PnP connections if there are any previous connections existing.

Disconnect-PnPOnline

Step 2

Validate there is no other PnP connection existing by typing the below command.

Get-PnPConnection

You should see the error says ‘The current connection holds no SharePoint context’.

Certificate Based Authentication To Connect To SharePoint Online Sites

Step 3

Now connect to the SharePoint site by using Azure AD App credentials.

Connect-PnPOnline -Url "https://contosodev.sharepoint.com/sites/CBADemo2" -ClientId "AZURE AD APP ID" -Thumbprint "CERT THUMP PRINT" -Tenant "YOUR TENANT DOMAIN"

Note that the App ID (Client ID) and Thumbprint values are generated at Step 6 in ‘Create Azure AD App’ section. You can also get the details from your Azure AD by logging into Azure AD Portal and check your App under ‘Enterprise Applications’.

Certificate Based Authentication To Connect To SharePoint Online Sites

Similarly, the tenant domain can be obtained by clicking on ‘Azure Active Directory’ from quick launch and look for ‘Primary domain’ value.

Certificate Based Authentication To Connect To SharePoint Online Sites

Step 4

Now check for which site the app is connected to by running below command.

Get-PnPSite

Step 5

Now get the list of all lists in this site collection by running below command.

Get-PnPList

Certificate Based Authentication To Connect To SharePoint Online Sites

You can run the same commands for any other site collection for which the Azure AD App needs to access.

Step 6

Validate the access to the app by connecting to sites that are not being granted access. You should see 403 forbidden error.

Connect-PnPOnline -Url "https://contosodev.sharepoint.com/sites/M365POC" -ClientId "YOUR CLIENT ID" -Thumbprint "CERT THUMP PRINT" -Tenant "contosodev.onmicrosoft.com"

Certificate Based Authentication To Connect To SharePoint Online Sites

You might have noticed that it is not throwing any error while connecting to the site using the Client ID and certificate thump print, however it is throwing error when getting the site details or list content.

Complete Script

#Creating Azure AD App with Certificate Thumbprint.
Register-PnPAzureADApp -ApplicationName SPSitesSelected -Tenant contosodev.onmicrosoft.com -Store CurrentUser -SharePointApplicationPermissions "Sites.Selected" -Interactive
#Connecting to SharePoint online Admin center using Global Admin Credentials
Connect-PnPOnline -Url "https://contosodev-admin.sharepoint.com" -Interactive
#Granting Access to Azure AD App for specific sites
Grant-PnPAzureADAppSitePermission -AppId 'bf8f7d56-c37f-44d6-abcb-670832e49b9c' -DisplayName 'SPSitesSelected' -Site 'https://contosodev.sharepoint.com/sites/CBADemo1' -Permissions Write
Grant-PnPAzureADAppSitePermission -AppId 'bf8f7d56-c37f-44d6-abcb-670832e49b9c' -DisplayName 'SPSitesSelected' -Site 'https://contosodev.sharepoint.com/sites/CBADemo2' -Permissions Write
#Disconnecting the previous connections
Disconnect-PnPOnline
#Validating the connection
Get-PnPConnection
#Connecting to SPO site using Azure AD App
Connect-PnPOnline -Url "https://contosodev.sharepoint.com/sites/CBADemo1" -ClientId "bf8f7d56-c37f-44d6-abcb-670832e49b9c" -Thumbprint "6A506565EABCD759C204C8517955301420A0C02D" -Tenant "contosodev.onmicrosoft.com"
#Gettting site details
Get-PnPSite
#Getting the list content
Get-PnPList
#Disconnecting from the Azure AD App connection
Disconnect-PnPOnline
#Connecting to SPO site using Azure Ad App with other site where access is not being granted.
Connect-PnPOnline -Url "https://contosodev.sharepoint.com/sites/M365POC" -ClientId "bf8f7d56-c37f-44d6-abcb-670832e49b9c" -Thumbprint "6A506565EABCD759C204C8517955301420A0C02D" -Tenant "contosodev.onmicrosoft.com"
#Get the site details
Get-PnPSite
#Get list content for site
Get-PnPList

Conclusion

Thus, in this article, we have learned about

  • what is Azure AD Certificate Based Authentication and
  • the different types of authentication
  • using PnP module to generate Azure AD App with ‘Sites.Selected” api permissions.
  • Granting access to Azure AD App and then validating the access.

References

 This story was originally published at https://www.c-sharpcorner.com/article/certificate-based-authentication-to-connect-to-sharepoint-online-sites/

#authentic #sharepoint #azure 

Saul  Alaniz

Saul Alaniz

1655722800

Autenticación Solo De Aplicaciones En SharePoint online Mediante PnP

La autenticación solo de aplicaciones de Azure AD se usa para autenticarse en los servicios de M365 y realizar algunas operaciones, como leer los datos, cargar los datos o realizar algunos trabajos de back-end a través de scripts de automatización. Microsoft recomienda utilizar la autenticación basada en certificados para sus aplicaciones registradas en Azure AD para autenticarse en el M365 o en cualquier servicio en la nube. CBA es un mecanismo extremadamente robusto y seguro para validar la identidad del usuario. 

En este artículo, quiero hablar sobre el caso de uso que encontré recientemente. Anteriormente, estaba usando la autenticación de solo aplicación de SharePoint, que es el concepto de ACS (servicios de control de Azure), donde el administrador de la colección de sitios puede crear un ID de cliente y un secreto de cliente agregando /_layouts/appregnew.aspx en la colección de sitios y usando las credenciales del cliente. en aplicación. Sin embargo, hay algunos problemas al usar este método de token de acceso de solo aplicación de ACS.

  • La autenticación no es segura. MSFT recomienda cambiar a la autenticación de solo aplicación de Azure AD.
  • Si desea que su aplicación se comunique con múltiples colecciones de sitios, es necesario crear múltiples ID de cliente y secretos, lo que se vuelve engorroso de manejar.

Puede consultar más información sobre la autenticación basada en token de ACS en la sección de referencias.

La buena noticia es que en la aplicación Azure AD, los permisos de API para SharePoint vienen con nuevos permisos llamados "Sitios.Seleccionados", que permitirán que su aplicación Azure AD se autentique en varias colecciones de sitios utilizando un solo cliente y detalles del certificado. 

Antes de pasar a esta autenticación solo de aplicaciones de Azure AD mediante certificados, intentaremos comprender qué es la autenticación basada en certificados (también conocida como CBA) en Azure AD. Hay 2 tipos de CBA en Azure AD. 

  1. Autenticación basada en certificados con AD FS federado
  2. Autenticación basada en certificados de Azure AD

Autenticación basada en certificados con AD FS federado

Anteriormente, para implementar el CBA, los servicios de ADFS deben implementarse entre los usuarios y Azure AD. CBA con ADFS usa certificados X.509 para autenticarse en Azure AD.

  • Aquí el usuario inicia sesión en la aplicación con sus credenciales y también con el certificado instalado en sus dispositivos.
  • ADFS valida las credenciales y el certificado del usuario y, en caso de éxito, pasa tokens de acceso al usuario para acceder a las aplicaciones.

Autenticación basada en certificados de Azure AD

La última versión, que es Azure AD CBA, no necesita configuración ni implementación de AD FS. Los usuarios pueden interactuar directamente con Azure AD y autenticarse en las aplicaciones.

Para obtener más detalles sobre CBA con AD FS y Azure AD CBA, puede consultar los artículos mencionados en la sección de referencias.

requisitos previos

  • PnP.Powershell versión 1.10.0. Tenga en cuenta que la autenticación mediante CBA se actualiza en esta versión.

  • PowerShell versión 5.1 o posterior
  • La cuenta utilizada para ejecutar los comandos de PowerShell debe tener derechos de "Administrador global".

Crear una aplicación de Azure AD

Ahora seguiremos los pasos para crear la aplicación Azure AD, con permisos de API "Sitios. Seleccionado” de tipo “Aplicación”. Luego use esta aplicación de Azure AD para autenticarse en varias colecciones de sitios. Para poder seguir correctamente el artículo, es necesario tener instalada la última versión de PnP Powershell.

Paso 1

Abra PowerShell ISE o las ventanas de comandos como administrador.

Paso 2

Registre la aplicación ejecutando el siguiente comando PS. Asegúrese de que la cuenta que ejecuta los siguientes comandos tenga derechos de 'Administrador global'. Siga las indicaciones si la cuenta tiene MFA (autenticación multifactor habilitada)

Register-PnPAzureADApp -ApplicationName SPSitesSelected -Tenant contosodev.onmicrosoft.com -Store CurrentUser -SharePointApplicationPermissions "Sites.Selected" -Interactive

Autenticación basada en certificados para conectarse a sitios de SharePoint Online

Autenticación basada en certificados para conectarse a sitios de SharePoint Online

Paso 3

En una autenticación exitosa, recibirá el siguiente mensaje que dice que debe esperar 60 segundos para verificar los artefactos requeridos e iniciar el flujo de consentimiento.

Autenticación basada en certificados para conectarse a sitios de SharePoint Online

Paso 4

Se le pedirá que se autentique una vez más para registrar la aplicación y luego para crear un certificado y una huella digital. Siga las instrucciones de nuevo

Autenticación basada en certificados para conectarse a sitios de SharePoint Online

Paso 5

Ahora tendrá una ventana emergente de consentimiento en una autenticación exitosa similar a la siguiente. Muestra el nombre de la aplicación (en este caso, SPSites seleccionado) y opciones para Aceptar y cancelar.

Autenticación basada en certificados para conectarse a sitios de SharePoint Online

También puede verificar los detalles de la aplicación haciendo clic en 'Información de la aplicación'.

Paso 6

Después de aceptar el consentimiento haciendo clic en 'Aceptar', debería ver la siguiente información en la ventana de salida del comando.

Autenticación basada en certificados para conectarse a sitios de SharePoint Online

Tendrás los siguientes valores,

  • Archivo Pfx: incluye información de clave tanto pública como privada asociada al certificado. Esto no debe compartirse fuera de su organización.
  • Archivo cer: tiene clave pública y alguna información sobre el dispositivo (en este caso el servidor). Esto normalmente se intercambia con los socios.
  • Huella digital: una clave segura asociada con el certificado que se utiliza para autenticarse en la aplicación.
  • Base64Encoded: esta es la información del certificado en formato de cadena ASCII.

Debe anotar solo el ID del cliente, la huella digital y la ubicación de los archivos Pfx y Cer.

Los pasos anteriores confirman que la aplicación de Azure AD se crea con los permisos necesarios, que es "Sitios.Seleccionados". Esto significa que la aplicación de Azure AD ahora se puede configurar para autenticarse solo en sitios específicos.

Concesión de acceso a la aplicación Azure AD

Ahora, para otorgar acceso a la aplicación Azure AD, ejecute el siguiente conjunto de comandos.

Paso 1

Inicie sesión en la URL de administración de SharePoint para su arrendatario mediante el módulo PnP PowerShell con credenciales de administrador global.

Connect-PnPOnline -Url "https://contoso-admin.sharepoint.com" -Interactive

Autenticación basada en certificados para conectarse a sitios de SharePoint Online

Paso 2

En la autenticación, obtendrá la siguiente información, sobre los permisos sobre lo que podría hacer el shell de administración de PnP.

Aquí puede dar su consentimiento en nombre de la organización o dejarlo sin marcar. Si marcó 'Consentimiento en nombre de su organización', no se solicitará el consentimiento de ningún otro usuario.

Paso 3

Otorgue el permiso a la aplicación ejecutando el siguiente comando. Tenga en cuenta que solo hay 2 conjuntos de permisos que puede otorgar a la aplicación, que es 'Lectura' o 'Escritura'.

Grant-PnPAzureADAppSitePermission -AppId 'YOUR APP ID HERE' -DisplayName 'APP DISPLAY NAME HERE' -Site 'https://contosodev.sharepoint.com/sites/CBADemo1' -Permissions Write

Autenticación basada en certificados para conectarse a sitios de SharePoint Online

Validación

Paso 1

Valide el acceso a la aplicación conectándose a sitios que tengan permisos. Debería ver el contenido sin ningún problema. En este caso, desconéctese de las conexiones PnP anteriores si existen conexiones anteriores.

Disconnect-PnPOnline

Paso 2

Valide que no exista otra conexión PnP escribiendo el siguiente comando.

Get-PnPConnection

Debería ver el error que dice "La conexión actual no tiene contexto de SharePoint".

Autenticación basada en certificados para conectarse a sitios de SharePoint Online

Paso 3

Ahora conéctese al sitio de SharePoint usando las credenciales de la aplicación Azure AD.

Connect-PnPOnline -Url "https://contosodev.sharepoint.com/sites/CBADemo2" -ClientId "AZURE AD APP ID" -Thumbprint "CERT THUMP PRINT" -Tenant "YOUR TENANT DOMAIN"

Tenga en cuenta que los valores de ID de aplicación (ID de cliente) y Huella digital se generan en el Paso 6 en la sección "Crear aplicación de Azure AD". También puede obtener los detalles de su Azure AD iniciando sesión en Azure AD Portal y revisando su aplicación en 'Aplicaciones empresariales'.

Autenticación basada en certificados para conectarse a sitios de SharePoint Online

De manera similar, el dominio del arrendatario se puede obtener haciendo clic en 'Azure Active Directory' desde el inicio rápido y buscando el valor 'Dominio principal'.

Autenticación basada en certificados para conectarse a sitios de SharePoint Online

Paso 4

Ahora verifique a qué sitio está conectada la aplicación ejecutando el siguiente comando.

Get-PnPSite

Paso 5

Ahora obtenga la lista de todas las listas en esta colección de sitios ejecutando el siguiente comando.

Get-PnPList

Autenticación basada en certificados para conectarse a sitios de SharePoint Online

Puede ejecutar los mismos comandos para cualquier otra colección de sitios a la que necesite acceder la aplicación Azure AD.

Paso 6

Valide el acceso a la aplicación conectándose a sitios a los que no se les otorga acceso. Debería ver el error 403 prohibido.

Connect-PnPOnline -Url "https://contosodev.sharepoint.com/sites/M365POC" -ClientId "YOUR CLIENT ID" -Thumbprint "CERT THUMP PRINT" -Tenant "contosodev.onmicrosoft.com"

Autenticación basada en certificados para conectarse a sitios de SharePoint Online

Es posible que haya notado que no arroja ningún error al conectarse al sitio utilizando la ID del cliente y la impresión del certificado, sin embargo, arroja un error al obtener los detalles del sitio o el contenido de la lista.

Guión completo

#Creating Azure AD App with Certificate Thumbprint.
Register-PnPAzureADApp -ApplicationName SPSitesSelected -Tenant contosodev.onmicrosoft.com -Store CurrentUser -SharePointApplicationPermissions "Sites.Selected" -Interactive
#Connecting to SharePoint online Admin center using Global Admin Credentials
Connect-PnPOnline -Url "https://contosodev-admin.sharepoint.com" -Interactive
#Granting Access to Azure AD App for specific sites
Grant-PnPAzureADAppSitePermission -AppId 'bf8f7d56-c37f-44d6-abcb-670832e49b9c' -DisplayName 'SPSitesSelected' -Site 'https://contosodev.sharepoint.com/sites/CBADemo1' -Permissions Write
Grant-PnPAzureADAppSitePermission -AppId 'bf8f7d56-c37f-44d6-abcb-670832e49b9c' -DisplayName 'SPSitesSelected' -Site 'https://contosodev.sharepoint.com/sites/CBADemo2' -Permissions Write
#Disconnecting the previous connections
Disconnect-PnPOnline
#Validating the connection
Get-PnPConnection
#Connecting to SPO site using Azure AD App
Connect-PnPOnline -Url "https://contosodev.sharepoint.com/sites/CBADemo1" -ClientId "bf8f7d56-c37f-44d6-abcb-670832e49b9c" -Thumbprint "6A506565EABCD759C204C8517955301420A0C02D" -Tenant "contosodev.onmicrosoft.com"
#Gettting site details
Get-PnPSite
#Getting the list content
Get-PnPList
#Disconnecting from the Azure AD App connection
Disconnect-PnPOnline
#Connecting to SPO site using Azure Ad App with other site where access is not being granted.
Connect-PnPOnline -Url "https://contosodev.sharepoint.com/sites/M365POC" -ClientId "bf8f7d56-c37f-44d6-abcb-670832e49b9c" -Thumbprint "6A506565EABCD759C204C8517955301420A0C02D" -Tenant "contosodev.onmicrosoft.com"
#Get the site details
Get-PnPSite
#Get list content for site
Get-PnPList

Conclusión

Por lo tanto, en este artículo, hemos aprendido sobre

  • ¿Qué es la autenticación basada en certificados de Azure AD y
  • los diferentes tipos de autenticación
  • utilizando el módulo PnP para generar la aplicación Azure AD con los permisos de API 'Sitios.Seleccionados'.
  • Otorgar acceso a la aplicación Azure AD y luego validar el acceso.

Referencias

 Esta historia se publicó originalmente en https://www.c-sharpcorner.com/article/certificate-based-authentication-to-connect-to-sharepoint-online-sites/

#authentic #sharepoint #azure