Service | Microsoft Docs article | Related commit history on GitHub | Change details |
---|---|---|---|
active-directory-b2c | Aad Sspr Technical Profile | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory-b2c/aad-sspr-technical-profile.md | |
active-directory-b2c | Access Tokens | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory-b2c/access-tokens.md | |
active-directory-b2c | Active Directory Technical Profile | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory-b2c/active-directory-technical-profile.md | The following settings can be used to configure the error message displayed upon See the following article, for example of using Azure AD technical profile: - [Add claims and customize user input using custom policies in Azure Active Directory B2C](configure-user-input.md)-------------- |
active-directory-b2c | Add Api Connector Token Enrichment | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory-b2c/add-api-connector-token-enrichment.md | |
active-directory-b2c | Add Api Connector | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory-b2c/add-api-connector.md | Last updated 12/20/2022 -+ zone_pivot_groups: b2c-policy-type |
active-directory-b2c | Add Identity Provider | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory-b2c/add-identity-provider.md | |
active-directory-b2c | Add Native Application | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory-b2c/add-native-application.md | |
active-directory-b2c | Add Password Change Policy | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory-b2c/add-password-change-policy.md | |
active-directory-b2c | Add Password Reset Policy | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory-b2c/add-password-reset-policy.md | |
active-directory-b2c | Add Profile Editing Policy | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory-b2c/add-profile-editing-policy.md | Custom policies are a set of XML files you upload to your Azure AD B2C tenant to ## Next steps -* Add a [sign-in with social identity provider](add-identity-provider.md). +* Add a [sign-in with social identity provider](add-identity-provider.md). |
active-directory-b2c | Azure Ad B2c Global Identity Funnel Based Design | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory-b2c/azure-ad-b2c-global-identity-funnel-based-design.md | This use case demonstrates how a user from their home country/region performs a  -1. A user from Europe, Middle East, and Africa (EMEA) attempts to sign up at **myapp.fr**. If the user isn't being sent to their local appication instance, the traffic manager will enforce a redirect. +1. A user from Europe, Middle East, and Africa (EMEA) attempts to sign up at **myapp.fr**. If the user isn't being sent to their local application instance, the traffic manager will enforce a redirect. 1. The user reaches the Global Funnel Azure AD B2C tenant. This tenant is configured to redirect to a regional Azure AD B2C tenant based on defined criteria using OpenId federation. This can be a lookup based on Application clientId. This use case demonstrates how a user re-registering the same email from their o  -1. A user from EMEA attempts to sign up at **myapp.fr**. If the user isn't being sent to their local appication instance, the traffic manager will enforce a redirect. +1. A user from EMEA attempts to sign up at **myapp.fr**. If the user isn't being sent to their local application instance, the traffic manager will enforce a redirect. 1. The user reaches the Global Funnel Azure AD B2C tenant. This tenant is configured to redirect to a regional Azure AD B2C tenant based on some criteria using OpenId federation. This can be a lookup based on Application clientId. This use case demonstrates how a user from their home country/region performs a  -1. A user from EMEA attempts to sign in at **myapp.fr**. If the user isn't being sent to their local appication instance, the traffic manager will enforce a redirect. +1. A user from EMEA attempts to sign in at **myapp.fr**. If the user isn't being sent to their local application instance, the traffic manager will enforce a redirect. 1. The user reaches the global funnel Azure AD B2C tenant. This tenant is configured to redirect to a regional Azure AD B2C tenant based on some criteria using OpenId federation. This can be a lookup based on application clientId. This use case demonstrates how a user can travel across regions and maintain the  -1. A user from North America (NOAM) attempts to sign in at **myapp.fr** while they are on holiday in France. If the user isn't being sent to their local appication instance, the traffic manager will enforce a redirect. +1. A user from North America (NOAM) attempts to sign in at **myapp.fr** while they are on holiday in France. If the user isn't being sent to their local application instance, the traffic manager will enforce a redirect. 1. The user reaches the global funnel Azure AD B2C tenant. This tenant is configured to redirect to a regional Azure AD B2C tenant based on some criteria using OpenId federation. This can be a lookup based on Application clientId. This use case demonstrates how a user can reset their password when they are wit  -1. A user from EMEA attempts to sign in at **myapp.fr**. If the user isn't being sent to their local appication instance, the traffic manager will enforce a redirect. +1. A user from EMEA attempts to sign in at **myapp.fr**. If the user isn't being sent to their local application instance, the traffic manager will enforce a redirect. 1. The user reaches the global funnel Azure AD B2C tenant. This tenant is configured to redirect to a regional Azure AD B2C tenant based on some criteria using OpenId federation. This can be a lookup based on application clientId. This use case demonstrates how a user can reset their password when they're trav  -1. A user from NOAM attempts to sign in at **myapp.fr** since they are on holiday in France. If the user isn't being sent to their local appication instance, the traffic manager will enforce a redirect. +1. A user from NOAM attempts to sign in at **myapp.fr** since they are on holiday in France. If the user isn't being sent to their local application instance, the traffic manager will enforce a redirect. 1. The user reaches the global funnel Azure AD B2C tenant. This tenant is configured to redirect to a regional Azure AD B2C tenant based on some criteria using OpenId federation. This can be a lookup based on application clientId. This use case demonstrates how a user can sign up to the service from their loca  -1. A user from EMEA attempts to sign up at **myapp.fr**. If the user isn't being sent to their local appication instance, the traffic manager will enforce a redirect. +1. A user from EMEA attempts to sign up at **myapp.fr**. If the user isn't being sent to their local application instance, the traffic manager will enforce a redirect. 1. The user reaches the global funnel Azure AD B2C tenant. This tenant is configured to redirect to a regional Azure AD B2C tenant based on some criteria using OpenId federation. This can be a lookup based on application clientId. This use case demonstrates how a user from their local region signs into the ser  -1. A user from EMEA attempts to sign in at **myapp.fr**. If the user isn't being sent to their local appication instance, the traffic manager will enforce a redirect. +1. A user from EMEA attempts to sign in at **myapp.fr**. If the user isn't being sent to their local application instance, the traffic manager will enforce a redirect. 2. The user reaches the global funnel Azure AD B2C tenant. This tenant is configured to redirect to a regional Azure AD B2C tenant based on some criteria using OpenId federation. This can be a lookup based on Application clientId. This use case demonstrates how a user can sign into their account with a federat  -1. A user from NOAM attempts to sign in at **myapp.fr**. If the user isn't being sent to their local appication instance, the traffic manager will enforce a redirect. +1. A user from NOAM attempts to sign in at **myapp.fr**. If the user isn't being sent to their local application instance, the traffic manager will enforce a redirect. 1. The user reaches the global funnel Azure AD B2C tenant. This tenant is configured to redirect to a regional Azure AD B2C tenant based on some criteria using OpenId federation. This can be a lookup based on Application clientId. This use case demonstrates how users are able to perform account linking when ma  -1. A user from EMEA attempts to sign in at **myapp.fr**. If the user isn't being sent to their local appication instance, the traffic manager will enforce a redirect. +1. A user from EMEA attempts to sign in at **myapp.fr**. If the user isn't being sent to their local application instance, the traffic manager will enforce a redirect. 1. The user reaches the global funnel Azure AD B2C tenant. This tenant is configured to redirect to a regional Azure AD B2C tenant based on some criteria using OpenId federation. This can be a lookup based on Application clientId. This use case demonstrates how non-local users are able to perform account linki  -1. A user from NOAM attempts to sign in at **myapp.fr**. If the user isn't being sent to their local appication instance, the traffic manager will enforce a redirect. +1. A user from NOAM attempts to sign in at **myapp.fr**. If the user isn't being sent to their local application instance, the traffic manager will enforce a redirect. 1. The user reaches the Global Funnel Azure AD B2C tenant. This tenant is configured to redirect to a regional Azure AD B2C tenant based on some criteria using OpenId federation. This can be a lookup based on Application clientId. |
active-directory-b2c | Azure Ad B2c Global Identity Proof Of Concept Funnel | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory-b2c/azure-ad-b2c-global-identity-proof-of-concept-funnel.md | The following block diagram shows the proof of concept. The guidance will show h ```xml <TechnicalProfile Id="REST-login-NonInteractive-APAC">- <DisplayName>non interactive authetnication to APAC</DisplayName> + <DisplayName>non interactive authentication to APAC</DisplayName> <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.RestfulProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" /> <Metadata> <Item Key="ServiceUrl">https://login.microsoftonline.com/b2capac.onmicrosoft.com/oauth2/v2.0/token</Item> |
active-directory-b2c | Azure Ad B2c Global Identity Solutions | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory-b2c/azure-ad-b2c-global-identity-solutions.md | The approach you choose will be based on the number of applications you host and The performance advantage of using multiple tenants, in either the regional or funnel-based configuration, will be an improvement over using a single Azure AD B2C tenant for globally operating businesses. -When using the funnel-based approach, the funnel tenant will be located in one specific region and serve users globally. Since the funnel tenants operation utilizes a global component of the Azure AD B2C service, it will maintain a consistant level of performance regardless of where users login from. +When using the funnel-based approach, the funnel tenant will be located in one specific region and serve users globally. Since the funnel tenants operation utilizes a global component of the Azure AD B2C service, it will maintain a consistent level of performance regardless of where users login from.  As shown in the diagram above, the Azure AD B2C tenant in the funnel-based approach will only utilize the Policy Engine to perform the redirection to regional Azure AD B2C tenants. The Azure AD B2C Policy Engine component is globally distributed. Therefore, the funnel isn't constrained from a performance perspective, regardless of where the Azure AD B2C funnel tenant is provisioned. A performance loss is encountered due to the extra redirect between funnel and regional tenants in the funnel-based approach. -In the regional-based approach, since each user is directed to their most local Azure AD B2C, performance is consistant for all users logging in. +In the regional-based approach, since each user is directed to their most local Azure AD B2C, performance is consistent for all users logging in. The regional tenants will perform directory calls into the Directory Store, which is the only regionalized component in both the funnel-based and regional-based architectures. |
active-directory-b2c | Configure Authentication In Azure Static App | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory-b2c/configure-authentication-in-azure-static-app.md | Add the following keys to the app settings: ### 3.1 Add an OpenID Connect identity provider -Once you've added the app ID and secrete, use the following steps to add the Azure AD B2C as OpenId Connect identity provider. +Once you've added the app ID and secret, use the following steps to add the Azure AD B2C as OpenId Connect identity provider. 1. Add an `auth` section of the [configuration file](../static-web-apps/configuration.md) with a configuration block for the OIDC providers, and your provider definition. |
active-directory-b2c | Error Codes | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory-b2c/error-codes.md | The following errors can be returned by the Azure Active Directory B2C service. | `AADB2C90031` | Policy '{0}' does not specify a default user journey. Ensure that the policy or it's parents specify a default user journey as part of a relying party section. | [Default user journey](relyingparty.md#defaultuserjourney) | | `AADB2C90035` | The service is temporarily unavailable. Please retry after a few minutes. | | | `AADB2C90036` | The request does not contain a URI to redirect the user to post logout. Specify a URI in the post_logout_redirect_uri parameter field. | [Send a sign-out request](openid-connect.md#send-a-sign-out-request) |-| `AADB2C90037` | An error occurred while processing the request. Please locate the `CorellationId` from the response. | [Submit a new support request](find-help-open-support-ticket.md), and include the `CorrelationId`. | +| `AADB2C90037` | An error occurred while processing the request. Please locate the `CorrelationId` from the response. | [Submit a new support request](find-help-open-support-ticket.md), and include the `CorrelationId`. | | `AADB2C90039` | The request contains a client assertion, but the provided policy '{0}' in tenant '{1}' is missing a client_secret in RelyingPartyPolicy. | deprecated | | `AADB2C90040` | User journey '{0}' does not contain a send claims step. | [User journey orchestration steps](userjourneys.md#orchestrationsteps) | | `AADB2C90043` | The prompt included in the request contains invalid values. Expected 'none', 'login', 'consent' or 'select_account'. | | |
active-directory-b2c | Language Customization | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory-b2c/language-customization.md | Open the extensions file of your policy. For example, <em>`SocialAndLocalAccount ## Provide language-specific labels -The [LocalizedResources](localization.md#localizedresources) of the `Localization` element contains the list of localized strings. The localized resources element has an identifier that is used to uniquely identify localized resources. This identifer is used later in the [content definition](contentdefinitions.md) element. +The [LocalizedResources](localization.md#localizedresources) of the `Localization` element contains the list of localized strings. The localized resources element has an identifier that is used to uniquely identify localized resources. This identifier is used later in the [content definition](contentdefinitions.md) element. You configure localized resources elements for the content definition and any language you want to support. To customize the unified sign-up or sign-in pages for English and Spanish, you add the following `LocalizedResources` elements after the close of the `</SupportedLanguages>` element. |
active-directory-b2c | Localization String Ids | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory-b2c/localization-string-ids.md | The following example shows the use of some of the user interface elements in th <!-- The following elements will display a message and two links at the bottom of the page. For policies that you intend to show to users in the United States, we suggest displaying the following text. Replace the content of the disclaimer_link_X_url elements with links to your organization's privacy statement and terms and conditions. Uncomment any of these lines to display them. -->- <!-- <LocalizedString ElementType="UxElement" StringId="disclaimer_msg_intro">By providing your phone number, you consent to receiving a one-time passcode sent by text message to help you sign into {insert your application name}. Standard messsage and data rates may apply.</LocalizedString> --> + <!-- <LocalizedString ElementType="UxElement" StringId="disclaimer_msg_intro">By providing your phone number, you consent to receiving a one-time passcode sent by text message to help you sign into {insert your application name}. Standard message and data rates may apply.</LocalizedString> --> <!-- <LocalizedString ElementType="UxElement" StringId="disclaimer_link_1_text">Privacy Statement</LocalizedString> <LocalizedString ElementType="UxElement" StringId="disclaimer_link_1_url">{insert your privacy statement URL}</LocalizedString> --> <!-- <LocalizedString ElementType="UxElement" StringId="disclaimer_link_2_text">Terms and Conditions</LocalizedString> |
active-directory-b2c | Partner Arkose Labs | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory-b2c/partner-arkose-labs.md | The user flow is for sign-up and sign-in, or sign-up. The Arkose Labs user flow 13. In **Use custom page content**, paste your custom HTML URI. 14. (Optional) If you use social identity providers, repeat steps for **Social account sign-up page**. -  +  15. From your user flow, go to **Properties**. 16. Select **Enable JavaScript**. |
active-directory-b2c | Partner F5 | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory-b2c/partner-f5.md | A BIG-IP supports SSO options, but in OAuth client mode the Guided Configuration | Header Operation |Insert| | Header Name | name| | Header Value | `%{session.oauth.client.last.id_token.name}`|-| Header Operation |Inser| +| Header Operation |Insert| |Header Name|agentid| |Header Value | `%{session.oauth.client.last.id_token.extension_AgentGeo}`| |
active-directory-b2c | Partner Ping Identity | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory-b2c/partner-ping-identity.md | You can configure PingFederate as an authentication provider, or a proxy, for up Use this function to contextually, dynamically, or declaratively switch an inbound request to an Azure AD B2C policy. See the following diagram of protocol sequence flow. -  +  ## Prerequisites |
active-directory-b2c | String Transformations | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory-b2c/string-transformations.md | Formats multiple claims according to a provided localized format string. This tr | OutputClaim | outputClaim | string | The claim that is produced after this claims transformation has been invoked. | > [!NOTE]-> String format maximum allowed size is 4000. +> There is no limit to the number of input claims that you can specify, but the maximum length of the formatted string is 4000. To use the FormatLocalizedString claims transformation: |
active-directory-b2c | Technicalprofiles | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory-b2c/technicalprofiles.md | The **Key** element contains the following attribute: | Attribute | Required | Description | | | -- | -- | | Id | No | A unique identifier of a particular key pair referenced from other elements in the policy file. |-| StorageReferenceId | Yes | An identifer of a storage key container referenced from other elements in the policy file. | +| StorageReferenceId | Yes | An identifier of a storage key container referenced from other elements in the policy file. | ## Input claims transformations |
active-directory-b2c | User Flow Custom Attributes | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory-b2c/user-flow-custom-attributes.md | Learn how to [manage extension attributes in your Azure AD B2C tenant](microsoft Unlike built-in attributes, custom attributes can be removed. The extension attributes' values can also be removed. > [!Important]-> Before you remove the custom attribute, for each account in the directory, set the extension attribute value to `null`. In this way you explicitly remove the extension attributesΓÇÖs values. Then continue to remove the extension attribute itself. Custom attributes can be queries using Microsoft Graph API. +> Before you remove the custom attribute, for each account in the directory, set the extension attribute value to `null`. That way, you explicitly remove the extension attributeΓÇÖs values. Then, continue to remove the extension attribute itself. Custom attributes can be queried using Microsoft Graph API. ::: zone pivot="b2c-user-flow" |
active-directory | On Premises Custom Connector | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/app-provisioning/on-premises-custom-connector.md | + + Title: Azure AD provisioning to applications using custom connectors +description: This document describes how to configure Azure AD to provision users with external systems that offer REST and SOAP APIs. +++++++ Last updated : 05/19/2023++++++# Provisioning with the custom connectors ++Azure AD supports preintegrated connectors for applications that support the following protocols and standards: ++> [!div class="checklist"] +> - [SCIM 2.0](on-premises-scim-provisioning.md) +> - [SQL](tutorial-ecma-sql-connector.md) +> - [LDAP](on-premises-ldap-connector-configure.md) +> - [REST](on-premises-ldap-connector-configure.md) +> - [SOAP](on-premises-ldap-connector-configure.md) ++For connectivity to applications that don't support the aforementioned protocols and standards, customers and [partners](https://social.technet.microsoft.com/wiki/contents/articles/1589.fim-2010-mim-2016-management-agents-from-partners.aspx) have built custom [ECMA 2.0](https://learn.microsoft.com/previous-versions/windows/desktop/forefront-2010/hh859557(v=vs.100)) connectors for Microsoft Identity Manager (MIM) 2016. You can now use those ECMA 2.0 connectors with the lightweight Azure AD provisioning agent, without needing MIM sync deployed. ++## Limitations ++Custom connectors built for MIM rely on the [ECMA framework](https://learn.microsoft.com/previous-versions/windows/desktop/forefront-2010/hh859557(v=vs.100)). The following table includes capabilities of the ECMA framework that are either partially supported or not supported by the Azure AD provisioning agent. For a list of known limitations for the Azure AD provisioning service and on-premises application provisioning, see [here](https://learn.microsoft.com/azure/active-directory/app-provisioning/known-issues?pivots=app-provisioning#on-premises-application-provisioning). +++| **Capability / feature** | **Support** | **Comments** | +| | | | +| Object type | Partially supported | Supports one object type | +| Partitions | Partially supported | Supports one partition | +| Hierarchies | Not supported | | +| Full export | Not supported | | +| DeleteAddAsReplace | Not supported | | +| ExportPasswordInFirstPass | Not supported | | +| Normalizations | Not supported | | +| Concurrent operations | Not supported | | + ++## Next steps ++- [App provisioning](user-provisioning.md) +- [ECMA Connector Host generic SQL connector](tutorial-ecma-sql-connector.md) +- [ECMA Connector Host LDAP connector](on-premises-ldap-connector-configure.md) ++ |
active-directory | How To Delete Role Policy | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/cloud-infrastructure-entitlement-management/how-to-delete-role-policy.md | This article describes how you can use the **Remediation** dashboard in Permissi - For information on how to view existing roles/policies, requests, and permissions, see [View roles/policies, requests, and permission in the Remediation dashboard](ui-remediation.md). - For information on how to create a role/policy, see [Create a role/policy](how-to-create-role-policy.md). - For information on how to clone a role/policy, see [Clone a role/policy](how-to-clone-role-policy.md).-- For information on how to modify a role/policy, see Modify a role/policy](how-to-modify-role-policy.md).+- For information on how to modify a role/policy, see [Modify a role/policy](how-to-modify-role-policy.md). - To view information about roles/policies, see [View information about roles/policies](how-to-view-role-policy.md). - For information on how to attach and detach permissions for AWS identities, see [Attach and detach policies for AWS identities](how-to-attach-detach-permissions.md). - For information on how to revoke high-risk and unused tasks or assign read-only status for Azure and GCP identities, see [Revoke high-risk and unused tasks or assign read-only status for Azure and GCP identities](how-to-revoke-task-readonly-status.md) |
active-directory | Howto Conditional Access Session Lifetime | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/conditional-access/howto-conditional-access-session-lifetime.md | Use the [What If tool](what-if-tool.md) to simulate a sign-in from the user to t ## Prompt tolerance -We factor for five minutes of clock skew, so that we donΓÇÖt prompt users more often than once every five minutes. If the user has done MFA in the last 5 minutes, and they hit another Conditional Access policy that requires reauthentication, we won't prompt the user. Over-promoting users for reauthentication can impact their productivity and increase the risk of users approving MFA requests they didnΓÇÖt initiate. Use ΓÇ£Sign-in frequency ΓÇô every timeΓÇ¥ only for specific business needs. +We factor for five minutes of clock skew, so that we donΓÇÖt prompt users more often than once every five minutes. If the user has done MFA in the last 5 minutes, and they hit another Conditional Access policy that requires reauthentication, we won't prompt the user. Over-prompting users for reauthentication can impact their productivity and increase the risk of users approving MFA requests they didnΓÇÖt initiate. Use ΓÇ£Sign-in frequency ΓÇô every timeΓÇ¥ only for specific business needs. ## Known issues |
active-directory | Terms Of Use | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/conditional-access/terms-of-use.md | Once you've completed your terms of use policy document, use the following proce | Bob | Jan 15 | Feb 14 | Mar 16 | Apr 15 | It's possible to use the **Expire consents** and **Duration before re-acceptance required (days)** settings together, but typically you use one or the other.+ + > [!IMPORTANT] + > Users whose consent has expired (regardless of the setting used, **Expire consents** or **Duration before re-acceptance required (days)**) will only be prompted to re-accept the terms if their session has expired. 1. Under **Conditional Access**, use the **Enforce with Conditional Access policy template** list to select the template to enforce the terms of use policy. You can edit some details of terms of use policies, but you can't modify an exis  1. In the pane on the right, upload the pdf for the new version-1. There's also a toggle option here **Require reaccept** if you want to require your users to accept this new version the next time they sign in. If you require your users to reaccept, next time they try to access the resource defined in your conditional access policy they'll be prompted to accept this new version. If you donΓÇÖt require your users to reaccept, their previous consent stays current and only new users who haven't consented before or whose consent expires see the new version. Until the session expires, **Require reaccept** not require users to accept the new TOU. If you want to ensure reaccept, delete and recreate or create a new TOU for this case. +1. There's also a toggle option here **Require reaccept** if you want to require your users to accept this new version the next time they sign in. If you require your users to reaccept, next time they try to access the resource defined in your conditional access policy they'll be prompted to accept this new version. If you donΓÇÖt require your users to reaccept, their previous consent stays current and only new users who haven't consented before or whose consent expires see the new version. Until the session expires, **Require reaccept** does not require users to accept the new TOU. If you want to ensure reaccept, delete and recreate or create a new TOU for this case.  You can delete old terms of use policies using the following procedure. You should no longer see your terms of use policy. +## Service limits ++You can add no more than 40 terms per tenant. + ## User acceptance record deletion User acceptance records are deleted: |
active-directory | Developer Support Help Options | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/develop/developer-support-help-options.md | If you can't find an answer to your problem by searching Microsoft Q&A, submit a | Component/area | Tags | | -| |+| Azure AD for customers / External Identities | [Azure Active Directory for customers](https://aka.ms/microsoftentraexternalid) | | Azure AD B2B / External Identities | [Azure Active Directory External Identities](/answers/tags/231/azure-active-directory-b2c) | | Azure AD B2C | [Azure Active Directory External Identities](/answers/tags/231/azure-active-directory-b2c) | | All other Azure Active Directory areas | [Azure Active Directory](/answers/tags/49/azure-active-directory) | |
active-directory | Scenario Protected Web Api Verification Scope App Roles | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/develop/scenario-protected-web-api-verification-scope-app-roles.md | You can also verify the scopes for the whole controller The following code snippet shows the usage of the `[RequiredScope]` attribute with hardcoded scopes on the controller. To use the RequiredScopeAttribute, you'll need to either: -- Use `AddMicrosoftIdentitWebApi` in the Startup.cs, as seen in [Code configuration](scenario-protected-web-api-app-configuration.md)+- Use `AddMicrosoftIdentityWebApi` in the Startup.cs, as seen in [Code configuration](scenario-protected-web-api-app-configuration.md) - or otherwise add the `ScopeAuthorizationRequirement` to the authorization policies as explained in [authorization policies](https://github.com/AzureAD/microsoft-identity-web/wiki/authorization-policies). ```csharp |
active-directory | Single Sign On Macos Ios | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/develop/single-sign-on-macos-ios.md | If you use the default web view in your app to sign in users, you'll get automat This type of SSO is currently not available on macOS. MSAL on macOS only supports WKWebView which doesn't have SSO support with Safari. +> [!NOTE] +> iOS clears session cookies right away after login due to the use of temporary browser to perform login. This browser does not share any of the session cookies. To make SSO work on iOS, KMSI must be enabled to utilize persistent cookies. + - **Silent SSO between ADAL and MSAL macOS/iOS apps** MSAL Objective-C support migration and SSO with ADAL Objective-C-based apps. The apps must be distributed by the same Apple Developer. |
active-directory | Device Management Azure Portal | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/devices/device-management-azure-portal.md | If you want to manage device identities by using the Azure portal, the devices n You must be assigned one of the following roles to view or manage device settings in the Azure portal: - Global Administrator-- Cloud Device Administrator - Global Reader-- Directory Reader+- Cloud Device Administrator +- Intune administrator +- Windows 365 administrator +- Directory reviewer  |
active-directory | Howto Vm Sign In Azure Ad Linux | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/devices/howto-vm-sign-in-azure-ad-linux.md | If the Azure Linux VM Sign-In application is missing from Conditional Access, ma 1. Sign in to the Azure portal. 1. Browse to **Azure Active Directory** > **Enterprise applications**.-1. Remove the filters to see all applications, and search for **VM**. If you don't see Azure Linux VM Sign-In as a result, the service principal is missing from the tenant. +1. Remove the filters to see all applications, and search for **Virtual Machine**. If you don't see Microsoft Azure Linux Virtual Machine Sign-In as a result, the service principal is missing from the tenant. Another way to verify it is via Graph PowerShell: Another way to verify it is via Graph PowerShell: 1. Enter the command `Connect-MgGraph -Scopes "ServicePrincipalEndpoint.ReadWrite.All","Application.ReadWrite.All"`. 1. Sign in with a Global Administrator account. 1. Consent to the prompt that asks for your permission.-1. Enter the command `Get-MgServicePrincipal -ConsistencyLevel eventual -Search '"DisplayName:Azure Linux VM Sign-In"'`. +1. Enter the command `Get-MgServicePrincipal -ConsistencyLevel eventual -Search '"DisplayName:Microsoft Azure Linux Virtual Machine Sign-In"'`. If this command results in no output and returns you to the PowerShell prompt, you can create the service principal by using the following Graph PowerShell command: `New-MgServicePrincipal -AppId ce6ff14a-7fdc-4685-bbe0-f6afdfcfa8e0`. |
active-directory | Howto Vm Sign In Azure Ad Windows | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/devices/howto-vm-sign-in-azure-ad-windows.md | Use the following information to correct sign-in problems. You can view the device and single sign-on (SSO) state by running `dsregcmd /status`. The goal is for the device state to show as `AzureAdJoined : YES` and for the SSO state to show `AzureAdPrt : YES`. -RDP sign-in via Azure AD accounts is captured in Event Viewer under the *AAD\Operational* event logs. +RDP sign-in via Azure AD accounts is captured in Event Viewer under the *Applications and Services Logs\Windows\AAD\Operational* event logs. ### Azure role not assigned |
active-directory | Concept Authentication Methods Customers | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/concept-authentication-methods-customers.md | + + Title: Authentication methods and identity providers for CIAM +description: Learn how to use different authentication methods for your customer sign-in and sign-up in CIAM. +++++++ Last updated : 04/28/2023+++++# Authentication methods and identity providers for customers ++Azure Active Directory (Azure AD) for customers offers several options for authenticating users of your applications. You can let customers create an account in your customer directory using their email and either a password or an email one-time passcode. You can also enable sign-in with a social account. ++## Email and password sign-in ++Email sign-up is enabled by default in your local account identity provider settings. With the email option, customers can sign up and sign in with their email address and a password. ++- **Sign-up**: Customers are prompted for an email address, which is verified at sign-up with a one-time passcode. The customer then enters any other information requested on the sign-up page, for example, display name, given name, and surname. Then they select Continue to create an account. ++- **Sign-in**: After the customer signs up and creates an account, they can sign in by entering their email address and password. ++- **Password reset**: If you enable email and password sign-in, a password reset link appears on the password page. If the customer forgets their password, selecting this link sends a one-time passcode to their email address. After verification, the customer can choose a new password. ++ :::image type="content" source="media/concept-authentication-methods-customers/email-password-sign-in.png" alt-text="Screenshots of the email with password sign-in screens." border="false"::: ++When you [create a sign-up and sign-in user flow](how-to-user-flow-sign-up-sign-in-customers.md#create-and-customize-a-user-flow), **Email with password** is the default option. ++## Email with one-time passcode sign-in ++Email with one-time passcode is an option in your local account identity provider settings. With this option, the customer signs in with a temporary passcode instead of a stored password each time they sign in. ++- **Sign-up**: Customers can sign up with their email address and request a temporary code, which is sent to their email address. Then they enter this code to continue signing in. ++- **Sign-in**: After the customer signs up and creates an account, each time they sign they'll enter their email address and receive a temporary passcode. ++ :::image type="content" source="media/concept-authentication-methods-customers/email-passcode-sign-in.png" alt-text="Screenshots of the email with one-time passcode sign-in screens." border="false"::: ++> [!NOTE] +> If you want to enable [multifactor authentication (MFA)](how-to-multifactor-authentication-customers.md), set your local account authentication method to **Email with password**. If you set your local account option to **Email with one-time passcode**, customers who use this method won't be able to sign in because the one-time passcode is already their first-factor sign-in method and can't be used as a second factor. Currently, other verification methods aren't available for customer scenarios. ++When you [create a sign-up and sign-in user flow](how-to-user-flow-sign-up-sign-in-customers.md#create-and-customize-a-user-flow), **Email one-time passcode** is one of the local account options. ++## Social identity providers: Facebook and Google ++For an optimal sign-in experience, federate with social identity providers whenever possible so you can give your customers a seamless sign-up and sign-in experience. In a customer tenant, you can allow a customer to sign up and sign in using their own Facebook or Google account. When a customer signs up for your app using their social account, the social identity provider creates, maintains, and manages identity information while providing authentication services to applications. ++When you enable social identity providers, customers can select from the social identity providers options you've made available on the sign-up page. To set up social identity providers in your customer tenant, you create an application at the identity provider and configure credentials. You obtain a client or app ID and a client or app secret, which you can then add to your customer tenant. ++### Google sign-in ++By setting up federation with Google, you can allow customers to sign in to your applications with their own Gmail accounts. After you've added Google as one of your application's sign-in options, on the sign-in page, users can sign in to Azure AD for customers with a Google account. ++The following screenshots show the sign-in with Google experience. In the sign-in page, users select **Sign-in with Google**. At that point, the user is redirected to the Google identity provider to complete the sign-in. ++ :::image type="content" source="media/concept-authentication-methods-customers/google-sign-in.png" alt-text="Screenshots of google sign-in screens." border="false"::: ++Learn how to [add Google as an identity provider](how-to-google-federation-customers.md). +### Facebook sign-in ++By setting up federation with Facebook, you can allow invited users to sign in to your applications with their own Facebook accounts. After you've added Facebook as one of your application's sign-in options, on the sign-in page, users can sign-in to Azure AD for customers with a Facebook account. ++The following screenshots show the sign-in with Facebook experience. In the sign-in page, users select **Sign-in with Facebook**. Then the user is redirected to the Facebook identity provider to complete the sign-in. ++ :::image type="content" source="media/concept-authentication-methods-customers/facebook-sign-in.png" alt-text="Screenshots of Facebook sign-in screens." border="false"::: ++Learn how to [add Facebook as an identity provider](how-to-facebook-federation-customers.md). ++## Next steps ++To learn how to add identity providers for sign-in to your applications, refer to the following articles: +- [Add Facebook as an identity provider](how-to-facebook-federation-customers.md) +- [Add Google as an identity provider](how-to-google-federation-customers.md) |
active-directory | Concept Branding Customers | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/concept-branding-customers.md | + + Title: Customize the company branding +description: Learn how to customize the sign-in and sign-up experiences for your customers. +++++++ Last updated : 04/21/2023++++#Customer intent: As an it admin, I want to know how can I customize my customers' sign-in experiences, including company branding and languages customizations. +++# Customize the neutral default authentication experience for the customer tenant ++After creating a new customer tenant, you can customize the appearance of your web-based applications for customers who sign in or sign up, to personalize their end-user experience. In Azure AD, the default Microsoft branding will appear in your sign-in pages before you customize any settings. This branding represents the global look and feel that applies across all sign-ins to your tenant. ++Your Azure AD tenant supports Microsoft look and feel as a default state for authentication experience. You can [customize the default Microsoft sign-in experience](/azure/active-directory/fundamentals/how-to-customize-branding) with a custom background image or color, favicon, layout, header, and footer. You can also upload a custom CSS. If the custom company branding fails to load for any reason, the sign-in page will revert to the default Microsoft branding. ++The customer tenant is unique in that it doesn't have any default branding, but instead has a neutral one. It is neutral, because it doesn't contain any existing Microsoft branding. This neutral default branding can be customized to meet the specific needs of your company. If the custom company branding fails to load for any reason, the sign-in page will revert to this neutral branding. It's also possible to add each custom branding property to the custom sign-in page individually. ++The following list and image outline the elements of the default Microsoft sign-in experience in an Azure AD tenant: ++1. Microsoft background image and color. +2. Microsoft favicon. +3. Microsoft banner logo. +4. Footer as a page layout element. +5. Microsoft footer hyperlinks, for example, Privacy & cookies, Terms of use and troubleshooting details also known as ellipsis in the right bottom corner of the screen. +6. Microsoft overlay. ++ :::image type="content" source="media/how-to-customize-branding-customers/azure-ad-microsoft-branding.png" alt-text="Screenshot of the Azure AD default Microsoft branding." lightbox="media/how-to-customize-branding-customers/azure-ad-microsoft-branding.png"::: ++The following image displays the neutral default branding of the customer tenant: + :::image type="content" source="media/how-to-customize-branding-customers/ciam-neutral-branding.png" alt-text="Screenshot of the CIAM neutral branding." lightbox="media/how-to-customize-branding-customers/ciam-neutral-branding.png"::: ++For more information, see [Customize the neutral branding in your customer tenant](how-to-customize-branding-customers.md). ++## Text customization ++You might have different requirements for the information you want to collect during sign-up and sign-in. The customer tenant comes with a built-in set of information stored in attributes, such as Given Name, Surname, City, and Postal Code. In the customer tenant, we have two options to add custom text to the sign-up and sign-in experience. The function is available under each user flow during language customization and also under **Company Branding**. Although we have two ways to customize strings, both ways modify the same JSON file. The most recent change made either via **User flows** or via **Company Branding** will always override the previous one. ++## Language customization ++You can create a personalized sign-in experience for users who sign in using a specific browser language by customizing the branding elements. If you don't make any changes to the elements, the default elements will be displayed. +In the customer tenant you can add a custom language to the sign-in experience under **Company Branding** or to a specific user flow under **User flows**. The language customization is available for a list of languages in the customer tenant. For more information, see [Customize the language of the authentication experience](how-to-customize-languages-customers.md). ++## Next steps +- [Customize the user experience for your customers](how-to-customize-branding-customers.md) +- [Customize the language of the authentication experience](how-to-customize-languages-customers.md) |
active-directory | Concept Custom Extensions | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/concept-custom-extensions.md | + + Title: Custom extensions in a customer tenant +description: Learn about custom authentication extensions that let you enrich or customize application tokens with information from external systems. +++++++ Last updated : 04/30/2023++++#Customer intent: As a dev, devops, or it admin, I want to know +++# Add your own business logic ++Azure Active Directory (Azure AD) for customers is designed for flexibility. In addition to the built-in authentication events within a sign-up and sign-in user flow, you can define actions for events at various points within the authentication flow. ++Custom authentication extensions in Azure AD let you interact with external systems during a user authentication. The custom authentication extension contains information about your REST API endpoint, the credentials to call the REST API, the attributes that it returns, and when the REST API should be called. ++You can create a custom authentication extension using the **OnTokenIssuanceStart** event, which is triggered just before a token is issued to the application: +++This article provides an overview of custom authentication extensions in Azure AD for customers. ++## Token issuance start event ++The token issuance start event is triggered once a user completes all of their authentication challenges, and a security token is about to be issued. ++When users authenticate to your application with Azure AD, a security token is returned to your application. The security token contains claims that are statements about the user, such as name, unique identifier, or application roles. Beyond the default set of claims that are contained in the security token, you can define your own custom claims from external systems using a REST API you develop. ++In some cases, key data might be stored in systems external to Microsoft Entra, such as a secondary email, billing tier, or sensitive information. It's not always feasible for the information in the external system to be stored in the Azure AD directory. For these scenarios, you can use a custom authentication extension and a custom claims provider to add this external data into tokens returned to your application. ++A token issuance event extension involves the following components: ++- **Custom claims provider**. To customize the token return to your applications, enterprise applications in your Azure AD tenant can configure custom claims provider to fetch data from external systems. The custom claims provider points to a custom extension and specifies the attributes to be added to the security token. Multiple claims provider can share the same custom extension. So, each application can choose its own set of attributes to be added to the security token. ++- **REST API endpoint**. When an event fires, Azure AD sends an HTTP request, to your REST API endpoint. The REST API can be an Azure Function, Azure Logic App, or some other publicly available API endpoint. Your REST API endpoint is responsible for interfacing with downstream databases, existing APIs, LDAP directories, or any other stores that contain the attributes you'd like to add to the token configuration. ++ The REST API returns an HTTP response, or action, back to Azure AD containing the attributes. Attributes that return by your REST API aren't automatically added to a token. Instead, an application's claims mapping policy must be configured for any attribute to be included in the token. ++For details, see: ++- [About custom authentication extensions](../../develop/custom-extension-overview.md?context=/azure/active-directory/external-identities/customers/context/customers-context) +- [Configure a custom claims provider token issuance event](../../develop/custom-extension-get-started.md?context=/azure/active-directory/external-identities/customers/context/customers-context) using a custom claims provider. ++## Next steps ++- To learn more about how custom extensions work, see [Custom authentication extensions](../../develop/custom-extension-overview.md?context=/azure/active-directory/external-identities/customers/context/customers-context). +- Configure a [custom claims provider token issuance event](../../develop/custom-extension-get-started.md?context=/azure/active-directory/external-identities/customers/context/customers-context). +- See the [Azure AD for customers Developer Center](https://aka.ms/ciam/dev) for the latest developer content and resources. |
active-directory | Concept Planning Your Solution | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/concept-planning-your-solution.md | + + Title: Plan CIAM deployment +description: Learn how to plan your CIAM deployment. +++++++ Last updated : 05/09/2023++++++# Planning for customer identity and access management ++Azure Active Directory (Azure AD) for customers is a customizable, extensible solution for adding customer identity and access management (CIAM) to your app. Because it's built on the Azure AD platform, you benefit from consistency in app integration, tenant management, and operations across your workforce and customer scenarios. When designing your configuration, it's important to understand the components of a customer tenant and the Azure AD features that are available for your customer scenarios. ++This article provides a general framework for integrating your app and configuring Azure AD for customers. It describes the capabilities available in a customer tenant and outlines the important planning considerations for each step in your integration. ++Adding secure sign-in to your app and setting up a customer identity and access management involves four main steps: +++This article describes each of these steps and outlines important planning considerations. In the following table, select a **Step** for details and planning considerations, or go directly to the **How-to guides**. ++++| Step | How-to guides | +||| +| **[Step 1: Create a customer tenant](#step-1-create-a-customer-tenant)** | • [Create a customer tenant](how-to-create-customer-tenant-portal.md)</br>• [Or start a free trial](https://aka.ms/ciam-free-trial?wt.mc_id=ciamcustomertenantfreetrial_linkclick_content_cnl) | +|**[Step 2: Register your application](#step-2-register-your-application)** | • [Register your application](how-to-register-ciam-app.md) | +|**[Step 3: Integrate a sign-in flow with your app](#step-3-integrate-a-sign-in-flow-with-your-app)** | • [Create a user flow](how-to-user-flow-sign-up-sign-in-customers.md) </br>• [Add your app to the user flow](how-to-user-flow-add-application.md) | +|**[Step 4: Customize and secure your sign-in](#step-4-customize-and-secure-your-sign-in)** | • [Customize branding](concept-branding-customers.md) </br>• [Add identity providers](concept-authentication-methods-customers.md) </br>• [Collect attributes during sign-up](how-to-define-custom-attributes.md)</br>• [Add attributes to the token](how-to-add-attributes-to-token.md) </br>• [Add multifactor authentication (MFA)](concept-security-customers.md) | ++++## Step 1: Create a customer tenant +++A customer tenant is the first resource you need to create to get started with Azure AD for customers. Your customer tenant is where you register your customer-facing application. It also contains a directory where you manage customer identities and access, separate from your workforce tenant. ++When you create a customer tenant, you can set your correct geographic location and your domain name. If you currently use Azure AD B2C, the new workforce and customer tenant model doesn't affect your existing Azure AD B2C tenants. ++### User accounts in a customer tenant ++The directory in a customer tenant contains admin and customer user accounts. You can [create and manage admin accounts](how-to-manage-admin-accounts.md) for your customer tenant. Customer accounts are typically created through self-service sign-up, but you can [create and manage customer local accounts](how-to-manage-customer-accounts.md). ++Customer accounts have a [default set of permissions](reference-user-permissions.md). Customers are restricted from accessing information about other users in the customer tenant. By default, customers canΓÇÖt access information about other users, groups, or devices. ++### How to create a customer tenant ++- [Create a customer tenant](how-to-create-customer-tenant-portal.md) in the Microsoft Entra admin center. ++- If you don't already have an Azure AD tenant and want to try Azure AD for customers, we recommend using the [get started experience](https://aka.ms/ciam-free-trial?wt.mc_id=ciamcustomertenantfreetrial_linkclick_content_cnl) to start a free trial. ++## Step 2: Register your application +++Before your applications can interact with Azure AD for customers, you need to register them in your customer tenant. Azure AD performs identity and access management only for registered applications. [Registering your app](how-to-register-ciam-app.md) establishes a trust relationship and allows you to integrate your app with Azure Active Directory for customers. ++We provide code sample guides and in-depth integration guides for several app types and languages. Depending on the type of app you want to register, you can find guidance on our [Samples by app type and language page](samples-ciam-all.md). ++### How to register your application ++- Find guidance specific to the application you want to register on our [Samples by app type and language page](samples-ciam-all.md). ++- If we don't have a guide specific to your platform or language, refer to the general instructions for [registering an application](how-to-register-ciam-app.md) in a customer tenant. ++## Step 3: Integrate a sign-in flow with your app +++Once you've set up your customer tenant and registered your application, create a sign-up and sign-in user flow. Then integrate your application with the user flow so that anyone who accesses it goes through the sign-up and sign-in experience you've designed. ++To integrate your application with a user flow, you add your application to the user flow properties and update your application code with your tenant information and authorization endpoint. ++### Authentication flow ++When a customer attempts to sign in to your application, the application sends an authorization request to the endpoint you provided when you associated the app with the user flow. The user flow defines and controls the customer's sign-in experience. ++If the user is signing in for the first time, they're presented with the sign-up experience. They enter information based on the built-in or custom user attributes you've chosen to collect. ++When sign-up is complete, Azure AD generates a token and redirects the customer to your application. A customer account is created for the customer in the directory. ++### Sign-up and sign-in user flow ++When planning your sign-up and sign-in experience, determine your requirements: ++- **Number of user flows**. Each application can have just one sign-up and sign-in user flow. If you have several applications, you can use a single user flow for all of them. Or, if you want a different experience for each application, you can create multiple user flows. ++- **Company branding and language customizations**. Although we describe configuring company branding and language customizations later in Step 4, you can configure them anytime, either before or after you integrate an app with a user flow. If you configure company branding before you create the user flow, the sign in pages reflect that branding. Otherwise, the sign in pages reflect the default, neutral branding. ++- **Attributes to collect**. In the user flow settings, you can select from a set of built-in user attributes you want to collect from customers. The customer enters the information on the sign-up page, and it's stored with their profile in your directory. If you want to collect more information, you can [define custom attributes](how-to-define-custom-attributes.md) and add them to your user flow. ++- **Requirements for token claims**. If your application requires specific user attributes, you can include them in the token sent to your application. ++- **Social identity providers**. You can set up social identity providers [Google](how-to-google-federation-customers.md) and [Facebook](how-to-facebook-federation-customers.md) and then add them to your user flow as sign-in options. ++### How to integrate a user flow with your app ++- If you want to collect information from customers beyond the built-in user attributes, [define custom attributes](how-to-define-custom-attributes.md) so they're available as you configure to your user flow. ++- [Create a sign-up and sign-in user flow for customers](how-to-user-flow-sign-up-sign-in-customers.md). ++- [Add your application](how-to-user-flow-add-application.md) to the user flow. ++## Step 4: Customize and secure your sign-in +++When planning for configuring company branding, language customizations, and custom extensions, consider the following points: ++- **Company branding**. After creating a new customer tenant, you can customize the appearance of your web-based applications for customers who sign in or sign up, to personalize their end-user experience. In Azure AD, the default Microsoft branding appear in your sign-in pages before you customize any settings. This branding represents the global look and feel that applies across all sign-ins to your tenant. Learn more about [customizing the sign-in look and feel](concept-branding-customers.md). ++- **Extending the authentication token claims**. Azure AD for customers is designed for flexibility. You can use a custom authentication extension to add claims from external systems to the application token just before the token is issued to the application. Learn more about [adding your own business logic](concept-custom-extensions.md) with custom authentication extensions. ++- **Multifactor authentication (MFA)**. You can also enable application access security by enforcing MFA, which adds a critical second layer of security to user sign-ins by requiring verification via email one-time passcode. Learn more about [MFA for customers](concept-security-customers.md#multifactor-authentication). ++- **Security and governance**. Learn about [security and governance](concept-security-customers.md) features available in your customer tenant, such as Identity Protection and Identity Governance. ++### How to customize and secure your sign-in ++- [Customize branding](concept-branding-customers.md) +- [Add identity providers](concept-authentication-methods-customers.md) +- [Collect attributes during sign-up](how-to-define-custom-attributes.md) +- [Add attributes to the token](how-to-add-attributes-to-token.md) +- [Add multifactor authentication](concept-security-customers.md) ++## Next steps +- [Start a free trial](https://aka.ms/ciam-free-trial?wt.mc_id=ciamcustomertenantfreetrial_linkclick_content_cnl) or [create your customer tenant](how-to-create-customer-tenant-portal.md). +- [Find samples and guidance for integrating your app](samples-ciam-all.md). +- See also the [Azure AD for customers Developer Center](https://aka.ms/ciam/dev) for the latest developer content and resources. |
active-directory | Concept Security Customers | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/concept-security-customers.md | + + Title: CIAM security and governance +description: Learn about CIAM security and governance features. +++++++ Last updated : 04/28/2023++++++# Security and governance in Azure AD for customers ++The integration of customer capabilities into Azure Active Directory (Azure AD) means that your customer scenarios benefit from the advanced security and governance features available in Azure AD. Your customers are able to self-service register for your applications using their preferred authentication methods, including social accounts through identity providers like Google and Facebook. And you can use features like multifactor authentication (MFA), Conditional Access, and Identity Protection to mitigate threats and detect risks. ++> [!NOTE] +> In Conditional Access, MFA, and Identity Protection aren't available in free trial customer tenants. +++## Multifactor authentication ++Azure AD Multi-Factor Authentication (MFA) helps safeguard access to data and applications while maintaining simplicity for your users. Azure AD for customers integrates directly with Azure AD Multi-Factor Authentication so you can add security to your sign-up and sign-in experiences by requiring a second form of authentication. You can fine-tune multifactor authentication depending on the extent of security you want to apply to your apps. Consider the following scenarios: ++- You offer a single app to customers and you want to enable multi-factor authentication for an extra layer of security. You can enable MFA in a Conditional Access policy that's targeted to all users and your app. ++- You offer multiple apps to your customers, but you don't require multifactor authentication for every application. For example, the customer can sign into an auto insurance application with a social or local account, but must verify the phone number before accessing the home insurance application registered in the same directory. In your Conditional Access policy, you can target all users but just those apps for which you want to enforce MFA. ++For details, see [how to enable multi-factor authentication](how-to-multifactor-authentication-customers.md). +## Identity protection ++Azure AD [Identity Protection](../../identity-protection/overview-identity-protection.md) provides ongoing risk detection for your customer tenant. It allows you to discover, investigate, and remediate identity-based risks. Identity Protection allows organizations to accomplish three key tasks: ++- Automate the detection and remediation of identity-based risks. ++- Investigate risks using data in the portal. ++- Export risk detection data to other tools. ++Identity Protection comes with risk reports that can be used to investigate identity risks in customer tenants. For details, see [Investigate risk with Identity Protection in Azure AD for customers](how-to-identity-protection-customers.md). ++## Identity governance ++Identity Governance in a customer tenant enables you to mitigate access risk by protecting, monitoring, and auditing access to your critical assets. It includes identity access lifecycle capabilities that help you manage access over time as needs change. Identity Governance also helps you scale efficiently to be able to develop and enforce access policy and controls on an ongoing basis. ++Start using Identity Governance in the [Microsoft Entra admin center](https://entra.microsoft.com) by selecting the **Identity Governance** tile. On the Identity Governance page, find information for getting started with capabilities such as Entitlement Management, access reviews, and Privileged Identity Management. ++## Next steps ++- [Planning for customer identity and access management](concept-planning-your-solution.md) |
active-directory | Concept Supported Features Customers | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/concept-supported-features-customers.md | + + Title: Supported features in customer tenants +description: Learn about supported features in customer tenants. +++++++ Last updated : 05/10/2023++++#Customer intent: As a dev, devops, or it admin, I want to learn about features supported in a CIAM tenant. ++# Supported features in Azure Active Directory for customers ++Azure Active Directory (Azure AD) for customers is designed for businesses that want to make applications available to their customers, using the Microsoft Entra platform for identity and access. With the introduction of this feature, Microsoft Entra now offers two different types of tenants that you can create and manage: ++- A **workforce tenant** contains your employees and the apps and resources that are internal to your organization. If you've worked with Azure AD, this is the type of tenant you're already familiar with. You might already have an existing workforce tenant for your organization. ++- A **customer tenant** represents your customer-facing app, resources, and directory of customer accounts. A customer tenant is distinct and separate from your workforce tenant. ++## Compare workforce and customer tenant capabilities ++Although workforce tenants and customer tenants are built on the same underlying Microsoft Entra platform, there are some feature differences. The following table compares the features available in each type of tenant. ++|Feature |Workforce tenant | Customer tenant | +|||| +| **External Identities** | Invite partners and other external users to your workforce tenant for collaboration. External users become guests in your workforce directory. | Enable self-service sign-up for customers and authorize access to apps. Users are added to your directory as customer accounts. | +| **Available identity providers** | - Azure AD accounts </br>- Microsoft accounts </br>- Email one-time passcode </br>- Google </br>- Facebook </br>- SAML/WS-Fed federation | - Local accounts </br>- Azure AD accounts </br>- Microsoft accounts </br>- Email one-time passcode </br>- Google </br>- Facebook | +| **Groups** | [Groups](../../fundamentals/active-directory-groups-create-azure-portal.md) can be used to manage administrative and user accounts.| Groups can be used to manage administrative accounts. Support for Azure AD groups and [application roles](how-to-use-app-roles-customers.md) is being phased into customer tenants. For the latest updates, see [Groups and application roles support](reference-group-app-roles-support.md). | +| **Roles and administrators**| [Roles and administrators](../../fundamentals/active-directory-users-assign-role-azure-portal.md) are fully supported for administrative and user accounts. | Roles aren't supported with customer accounts. Customer accounts don't have access to tenant resources.| +| **Custom domain names** | You can use [custom domains](../../fundamentals/add-custom-domain.md) for administrative accounts only. | Not currently supported. However, the URLs visible to customers in sign-up and sign-in pages are neutral, unbranded URLs. [Learn more](concept-branding-customers.md)| +| **Conditional Access** | [Conditional Access](../../conditional-access/overview.md) is fully supported for administrative and user accounts. | A subset of the Azure AD Conditional access is available. Multifactor authentication (MFA) is supported with local accounts in customer tenants. [Learn more](concept-security-customers.md).| +| **Identity protection** | Provides ongoing risk detection for your Azure AD tenant. It allows organizations to discover, investigate, and remediate identity-based risks. | A subset of the Azure AD Identity Protection risk detections is available. [Learn more](how-to-identity-protection-customers.md). | +| **Application registration** | SAML relying parties, OpenID Connect, and OAuth2 | OpenID Connect and OAuth2 | +| **Custom authentication extension** | Add claims from external systems. | Add claims from external systems. | +| **Token customization** | Add user attributes, custom authentication extension (preview), claims transformation and security groups membership to token claims. | Add user attributes, custom authentication extension and security groups membership to token claims. [Learn more](how-to-add-attributes-to-token.md). | +| **Self-service password reset** | Allow users to reset their password using up to two authentication methods (see the next row for available methods). | Allow users to reset their password using email with one time passcode. [Learn more](how-to-enable-password-reset-customers.md). | +| **Authentication methods** | - Username and password</br>- Microsoft Authenticator</br>- FIDO2</br>- SMS</br>- Temporary Access Pass</br>- Third-party software OATH tokens</br>- Voice call</br>- Email one-time passcode</br>- Certificate-based authentication | </br>- Username and password</br>- Email one-time passcode | +| **Company branding** | Azure AD tenant supports Microsoft look and feel as a default state for authentication experience. Administrators can customize the default Microsoft sign-in experience. | Microsoft provides a neutral branding as the default for the customer tenant, which can be customized to meet the specific needs of your company. The default branding for the customer tenant is neutral and doesn't include any existing Microsoft branding. [Learn more](concept-branding-customers.md). | +| **Language customization** | Customize the sign-in experience based on browser language when users authenticate into your corporate intranet or web-based applications. | Use languages to modify the strings displayed to your customers as part of the sign-in and sign-up process. [Learn more](concept-branding-customers.md). | +| **Custom attributes** | Use directory extension attributes to store additional data in the Azure AD directory for user objects, groups, tenant details, and service principals. | Use directory extension attributes to store additional data in the customer directory for user objects. Create custom user attributes and add them to your sign-up user flow. [Learn more](how-to-define-custom-attributes.md). | +++## Next steps ++- [Planning for CIAM](concept-planning-your-solution.md) |
active-directory | How To Add Attributes To Token | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-add-attributes-to-token.md | + + Title: Add attributes to token claims +description: Learn how to add built-in user attributes and custom attributes as claims to the application token. Use directory extension attributes for sending user data to applications in token claims. +++++++ Last updated : 05/08/2023++++++# Add user attributes to token claims ++User attributes are values collected from the user during self-service sign-up. In addition to built-in user attributes, you can create custom attributes when you need to collect additional information. Because your application might rely on certain user attributes to function as designed, you can add any of these attributes to the token that is sent from Azure AD to your application. ++You can specify which built-in or custom attributes you want to include as claims in the token that Azure AD sends to your application. ++## Prerequisites ++- [Register the application](how-to-register-ciam-app.md) with Azure AD. +- [Create a sign-up and sign-in user flow](how-to-user-flow-sign-up-sign-in-customers.md) and selected the attributes you want to collect during sign-up. +- [Create the custom attributes](how-to-define-custom-attributes.md) you want to include. ++## Add built-in or custom attributes to the token ++1. In the [Microsoft Entra admin center](https://entra.microsoft.com/), select **Azure Active Directory**. +1. Select **Applications** > **App registrations**. +1. Select your application in the list to open the application's **Overview** page. ++ :::image type="content" source="media/how-to-add-attributes-to-token/select-app.png" alt-text="Screenshot of the overview page of the app registration."::: ++1. In the **Essentials** section, under **Managed application in local directory**, select the link showing the name of your application. ++ :::image type="content" source="media/how-to-add-attributes-to-token/managed-app-in-local-directory-link.png" alt-text="Screenshot of the managed application in local directory link."::: ++1. Under **Manage**, select **Single Sign-on**. +1. In the **Attributes & Claims** section, select the **Edit** icon. ++ :::image type="content" source="media/how-to-add-attributes-to-token/single-sign-on-edit.png" alt-text="Screenshot of the attributes and claims section and the edit icon."::: ++### To add a built-in attribute to the token as a claim ++1. On the **Manage claim** page, select **Add new claim**. +1. Enter a **Name**. +1. Next to **Source**, select **Attribute**. Then use the drop down list to select the built-in attribute. ++ :::image type="content" source="media/how-to-add-attributes-to-token/add-built-in-claim.png" alt-text="Screenshot of the drop down list of built-in attributes."::: ++1. Select **Save**. Repeat for all built-in attributes you want to add. ++### To add a custom attribute to the token as a claim ++1. On the **Manage claim** page, select **Add new claim**. +1. Enter a **Name**. +1. Next to **Source**, select **Directory schema extension (Preview)**. ++ :::image type="content" source="media/how-to-add-attributes-to-token/manage-claim-directory-schema.png" alt-text="Screenshot of the Directory schema extension option."::: ++1. In the **Select Application** pane, select **b2c-extensions-app** (the app that contains all extension attributes for your customer tenant), and then choose **Select**. ++ :::image type="content" source="media/how-to-add-attributes-to-token/edit-select-application.png" alt-text="Screenshot of the Select Application pane."::: ++1. In the **Add Extension Attributes** pane, find the custom attribute you want to add as a claim to the token, and then select it. +1. Select **Add**. +1. Select **Save**. Repeat for each custom attribute you want to add. ++### Update the application manifest to accept mapped claims ++Ensure that **"allowPublicClient": true** is set in the application manifest. ++1. In the left menu, under **Manage**, select **Manifest** to open application manifest. ++1. Find the **acceptMappedClaims** key and ensure its value is set to **true**. ++## Next steps ++Learn more about [adding claims from custom claims providers](../../develop/custom-extension-get-started.md). |
active-directory | How To Browserless App Dotnet Sample Sign In | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-browserless-app-dotnet-sample-sign-in.md | + + Title: Sign in users in a sample ASP.NET browserless app +description: Use a sample to learn how to configure a sample ASP.NET browserless app. +++++++++ Last updated : 05/10/2023+++#Customer intent: As a dev, devops, I want to learn about how to configure a sample ASP.NET browserless app to sign in users with my Azure Active Directory (Azure AD) for customers tenant +++# Sign in users into a sample ASP.NET browserless app using Device Code flow ++This how-to guide uses a sample ASP.NET browserless app to show how to add authentication to the app. The sample app enables users to sign in. The sample ASP.NET browserless app uses [Microsoft Authentication Library for .NET (MSAL NET)](https://github.com/AzureAD/microsoft-authentication-library-for-dotnet) to handle authentication. ++## Prerequisites ++- [.NET 7 SDK](https://dotnet.microsoft.com/download/dotnet/7.0). ++- [Visual Studio Code](https://code.visualstudio.com/download) or another code editor. ++- Azure AD for customers tenant. If you don't already have one, [sign up for a free trial](https://aka.ms/ciam-free-trial?wt.mc_id=ciamcustomertenantfreetrial_linkclick_content_cnl). ++## Register the headless app +++## Enable public client flow +++## Grant API permissions ++Since this app signs-in users, add delegated permissions: +++## Create a user flow +++## Associate the browserless app with the user flow +++## Clone or download sample browserless app ++To get the browserless app sample code, you can do either of the following tasks: [Download the .zip file](https://github.com/Azure-Samples/ms-identity-ciam-dotnet-tutorial/archive/refs/heads/main.zip) or clone the sample web application from GitHub by running the following command: ++```console +git clone https://github.com/Azure-Samples/ms-identity-ciam-dotnet-tutorial.git +``` +If you choose to download the *.zip* file, extract the sample app file to a folder where the total length of the path is 260 or fewer characters. ++## Configure the sample browserless app ++1. Open the project in your IDE (like Visual Studio or Visual Studio Code) to configure the code. ++1. In your code editor, open the *appsettings.json* file in the *1-Authentication* > *4-sign-in-device-code* folder. ++1. Replace `Enter_the_Application_Id_Here` with the Application (client) ID of the app you registered earlier. + +1. Replace `Enter_the_Tenant_Subdomain_Here` with the Directory (tenant) subdomain. For example, if your primary domain is *contoso.onmicrosoft.com*, replace `Enter_the_Tenant_Subdomain_Here` with *contoso*. If you don't have your primary domain, learn how to [read tenant details](how-to-create-customer-tenant-portal.md#get-the-customer-tenant-details). ++## Run and test sample browserless app ++1. Open a console window, and change to the directory that contains the ASP.NET browserless sample app: ++ ```console + cd 1-Authentication/4-sign-in-device-code + ``` ++1. In your terminal, run the app by running the following command: ++ ```console + dotnet run + ``` +1. When the app launches, copy the suggested URL *https://microsoft.com/devicelogin* from the terminal and visit it in a browser. Then, copy the device code from the terminal and [follow the prompts](./how-to-browserless-app-dotnet-sign-in-sign-in.md#sign-in-to-your-app) on *https://microsoft.com/devicelogin*. ++## How it works ++The browserless app is initialized as a public client application. You acquire token using the device code auth grant flow. This flow allows users to sign in to input-constrained devices such as a smart TV, IoT device, or a printer. You then pass a callback to the `AcquireTokenWithDeviceCodeAsync` method. This callback contains a `DeviceCodeResult` object that contains the URL a user navigates to and sign in. Once the user signs in, an `AuthenticationResult` is returned containing an access token and some basic account information. ++```csharp +var scopes = new string[] { }; // by default, MSAL attaches OIDC scopes to every token request +var result = await app.AcquireTokenWithDeviceCode(scopes, async deviceCode => { + Console.WriteLine($"In a broswer, navigate to the URL '{deviceCode.VerificationUrl}' and enter the code '{deviceCode.UserCode}'"); + await Task.FromResult(0); +}).ExecuteAsync(); ++Console.WriteLine($"You signed in as {result.Account.Username}"); +``` ++## Next steps ++Next, learn how to prepare your Azure AD for customers tenant. ++> [!div class="nextstepaction"] +> [Build your own ASP.NET browserless app and sign in users >](how-to-browserless-app-dotnet-sign-in-overview.md) |
active-directory | How To Browserless App Dotnet Sign In Overview | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-browserless-app-dotnet-sign-in-overview.md | + + Title: Sign in users to an ASP.NET browserless app using Device Code flow +description: Learn about how to Sign in users in your ASP.NET browserless app using Device Code flow. +++++++++ Last updated : 05/10/2023+++#Customer intent: As a dev, devops, I want to learn about how to enable authentication in my ASP.NET browserless app with Azure Active Directory (Azure AD) for customers tenant +++# Sign in users to an ASP.NET browserless app using Device Code flow ++In this series of articles, you learn how to sign in users to your ASP.NET browserless app. The articles guide you through the steps of building an app that authenticates users against Azure Active Directory (Azure AD) for Customers using the device code flow. ++The article series is broken down into the following steps: ++1. Overview (this article) +1. [Prepare your tenant](how-to-browserless-app-dotnet-sign-in-prepare-tenant.md) +1. [Sign in user](how-to-browserless-app-dotnet-sign-in-sign-in.md) ++## Prerequisites ++- [.NET 7 SDK](https://dotnet.microsoft.com/download/dotnet/7.0). ++- [Visual Studio Code](https://code.visualstudio.com/download) or another code editor. ++- Azure AD for customers tenant. If you don't already have one, [sign up for a free trial](https://aka.ms/ciam-free-trial). ++## OAuth 2.0 device authorization grant flow ++The Microsoft identity platform supports the [device authorization grant](https://tools.ietf.org/html/rfc8628), which allows users to sign in to input-constrained devices such as a smart TV, IoT device, or a printer. To enable this flow: ++1. The device provides a verification url to the user. The user navigates to this url in a browser on another device to sign in. +1. The user inputs a code provided by the device which is then verified if it matches the code issues by the device. +1. Once the user is signed in, the device is able to get access tokens and refresh tokens as needed. ++For more information, see [device code flow in the Microsoft identity platform](/azure/active-directory/develop/v2-oauth2-device-code). ++If you want to run a sample ASP.NET browserless app to get a feel of how things work, complete the steps in [Sign in users in a sample ASP.NET browserless app](./how-to-browserless-app-dotnet-sample-sign-in.md) ++## Next steps ++Next, learn how to prepare your Azure AD for customers tenant. ++> [!div class="nextstepaction"] +> [Prepare your Azure AD for customers tenant >](how-to-browserless-app-dotnet-sign-in-prepare-tenant.md) |
active-directory | How To Browserless App Dotnet Sign In Prepare App | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-browserless-app-dotnet-sign-in-prepare-app.md | + + Title: Sign in users in your ASP.NET browserless app using Device Code flow - Prepare app +description: Learn about how to prepare an ASP.NET browserless app that signs in users by using Device Code flow. +++++++++ Last updated : 05/10/2023+++#Customer intent: As a dev, devops, I want to learn about how to enable authentication in my ASP.NET browserless app with Azure Active Directory (Azure AD) for customers tenant +++# Sign in users in your ASP.NET browserless app using Device Code flow - Prepare app ++In this article, you create an ASP.NET browserless app project and organize all the folders and files you require. You also install the packages you need to help you with configuration and authentication. ++## Prerequisites ++Completion of the prerequisites and steps in the [Overview](./how-to-browserless-app-dotnet-sign-in-prepare-tenant.md) before proceeding. ++## Create an ASP.NET browserless app ++This how-to guide useS Visual Studio Code and .NET 7.0. ++1. Open the [integrated terminal](https://code.visualstudio.com/docs/editor/integrated-terminal). +1. Navigate to the folder where you want your project to live. +1. Initialize a .NET console app and navigate to its root folder ++ ```dotnetcli + dotnet new console -o MsIdBrowserlessApp + cd MsIdBrowserlessApp + ``` ++## Add packages + +Install the following packages to help you handle app [configuration](/dotnet/core/extensions/configuration?source=recommendations). These packages are part of the [Microsoft.Extensions.Configuration](https://www.nuget.org/packages/Microsoft.Extensions.Configuration/) package. ++- [*Microsoft.Extensions.Configuration*](/dotnet/api/microsoft.extensions.configuration) +- [*Microsoft.Extensions.Configuration.Json*](/dotnet/api/microsoft.extensions.configuration.json): JSON configuration provider implementation for `Microsoft.Extensions.Configuration`. +- [*Microsoft.Extensions.Configuration.Binder*](/dotnet/api/microsoft.extensions.configuration.configurationbinder): Functionality to bind an object to data in configuration providers for `Microsoft.Extensions.Configuration`. ++Install the following package to help with authentication. ++- [*Microsoft.Identity.Web*](/entra/msal/dotnet/microsoft-identity-web/) simplifies adding authentication and authorization support to apps that integrate with the Microsoft identity platform. +++ ```dotnetcli + dotnet add package Microsoft.Extensions.Configuration + dotnet add package Microsoft.Extensions.Configuration.Json + dotnet add package Microsoft.Extensions.Configuration.Binder + dotnet add package Microsoft.Identity.Web + ``` ++## Configure app registration details ++1. In your code editor, create an *appsettings.json* file in the root folder of the app. ++1. Add the following code to the *appsettings.json* file. + + ```json + { + "AzureAd": { + "Authority": "https://<Enter_the_Tenant_Subdomain_Here>.ciamlogin.com/", + "ClientId": "<Enter_the_Application_Id_Here>" + } + } + ``` ++1. Replace `Enter_the_Application_Id_Here` with the Application (client) ID of the app you registered earlier. + +1. Replace `Enter_the_Tenant_Subdomain_Here` with the Directory (tenant) subdomain. For example, if your primary domain is *contoso.onmicrosoft.com*, replace `Enter_the_Tenant_Subdomain_Here` with *contoso*. If you don't have your primary domain, learn how to [read tenant details](how-to-create-customer-tenant-portal.md#get-the-customer-tenant-details). ++1. Add the following code to the *MsIdBrowserlessApp.csproj* file to instruct your app to copy the *appsettings.json* file to the output directory when the project is compiled. ++ ```xml + <Project Sdk="Microsoft.NET.Sdk"> + ... ++ <ItemGroup> + <None Update="appsettings.json"> + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> + </None> + <ItemGroup> + </Project> + ``` ++## Next steps ++> [!div class="nextstepaction"] +> [Sign in to your ASP.NET browserless app >](./how-to-browserless-app-dotnet-sign-in-sign-in.md) |
active-directory | How To Browserless App Dotnet Sign In Prepare Tenant | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-browserless-app-dotnet-sign-in-prepare-tenant.md | + + Title: Sign in users in your ASP.NET browserless app using Device Code flow - Prepare tenant +description: Learn about how to prepare your Azure Active Directory (Azure AD) for customers tenant to sign in users in your ASP.NET browserless application by using Device Code flow. +++++++++ Last updated : 05/10/2023+++#Customer intent: As a dev, devops, I want to learn about how to enable authentication in my own ASP.NET browserless app with Azure Active Directory (Azure AD) for customers tenant +++# Sign in users in your ASP.NET browserless app using Device Code flow- Prepare tenant ++In this article, you prepare your Azure Active Directory (Azure AD) for customers tenant for authentication. ++## Register the browserless app +++## Enable public client flow +++## Grant API permissions ++Since this app signs-in users, add delegated permissions: +++## Create a user flow +++## Associate the browserless app with the user flow +++## Next steps ++> [!div class="nextstepaction"] +> [Prepare your ASP.NET browserless app >](how-to-browserless-app-dotnet-sign-in-prepare-app.md) |
active-directory | How To Browserless App Dotnet Sign In Sign In | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-browserless-app-dotnet-sign-in-sign-in.md | + + Title: Sign in users in an ASP.NET browserless app using Device Code flow - Add sign-in +description: Learn about how to add sign-in to your ASP.NET browserless app using Device Code flow. +++++++++ Last updated : 05/10/2023+++#Customer intent: As a dev, devops, I want to learn about how to enable authentication in my own Node.js web app with Azure Active Directory (Azure AD) for customers tenant +++# Sign in users in an ASP.NET browserless app using Device Code flow - Add sign-in ++In this article, you add sign-in code and run the app to go through the sign-in flow. ++## Prerequisites ++Completion of the prerequisites and steps in [Prepare your app](./how-to-browserless-app-dotnet-sign-in-prepare-app.md). ++## Add sign-in code ++1. In your code editor, open the *Program.cs* file. ++1. Clear the contents of the *Program.cs* file then add the packages and set up your configuration to read configs from the *appsettings.json* file. ++ ```csharp + // Import packages + using Microsoft.Extensions.Configuration; + using Microsoft.Identity.Client; ++ // Setup your configuration to read configs from appsettings.json + var configuration = new ConfigurationBuilder() + .AddJsonFile($"appsettings.json"); + + var config = configuration.Build(); + var publicClientOptions = config.GetSection("AzureAd"); ++ // Placeholders for the rest of the code ++ var app = PublicClientApplicationBuilder.Create(...) + var scopes = new string[] { }; + var result = await app.AcquireTokenWithDeviceCode(...) ++ Console.WriteLine(...) + ``` ++1. The browserless app is a public client application. Create an instance of the `PublicClientApplication` class and pass in the `ClientId` and `Authority` values from the *appsettings.json* file. ++ ```csharp + var app = PublicClientApplicationBuilder.Create(publicClientOptions.GetValue<string>("ClientId")) + .WithAuthority(publicClientOptions.GetValue<string>("Authority")) + .Build(); + ``` ++1. Add the code that helps the app acquire tokens using the device code flow. Pass in the scopes you want to request for and a callback function that is called when the device code is available. By default, MSAL attaches OIDC scopes to every token request. ++ ```csharp ++ var scopes = new string[] { }; // by default, MSAL attaches OIDC scopes to every token request + var result = await app.AcquireTokenWithDeviceCode(scopes, async deviceCode => { + Console.WriteLine($"In a broswer, navigate to the URL '{deviceCode.VerificationUrl}' and enter the code '{deviceCode.UserCode}'"); + await Task.FromResult(0); + }).ExecuteAsync(); ++ Console.WriteLine($"You signed in as {result.Account.Username}"); + Console.WriteLine($"{result.Account.HomeAccountId}"); + Console.WriteLine("\nRetrieved ID token:"); + result.ClaimsPrincipal.Claims.ToList() + .ForEach(c => Console.WriteLine(c)); + ``` + + The callback function displays the device code and the verification URL to the user. The user then navigates to the verification URL and enters the device code to complete the authentication process. The method then proceeds to poll for the ID token which is granted upon successful login by the user based on the device code information. ++## Sign in to your app ++1. In your terminal, navigate to the root folder of your browserless app and run the app by running the command `dotnet run` in your terminal. ++1. Open your browser, then navigate to the URL printed in your terminal, `https://microsoft.com/devicelogin`. You should see a page similar to the following screenshot: ++ :::image type="content" source="media/how-to-browserless-dotnet-sign-in-sign-in/browserless-app-dotnet-enter-code.png" alt-text="Screenshot of the enter code prompt in a node browserless application using the device code flow."::: ++1. Copy the device code from the message in the terminal and paste it in the **Enter Code** prompt to authenticate. After entering the code, you'll be redirected to the sign in page as follows: ++ :::image type="content" source="media/how-to-browserless-dotnet-sign-in-sign-in/browserless-app-dotnet-sign-in-page.png" alt-text="Screenshot showing the sign in page in a node browserless application."::: ++1. At this point, you most likely don't have an account. If so, select **No account? Create one**, which starts the sign-up flow. Follow through this flow to create a new account. If you already have an account, enter your credentials and sign in. ++1. After completing the sign up flow and signing in, you see a page similar to the following screenshot: ++ :::image type="content" source="media/how-to-browserless-dotnet-sign-in-sign-in/browserless-app-dotnet-signed-in-user.png" alt-text="Screenshot showing a signed-in user in a node browserless application."::: ++1. Move back to the terminal and see your authentication information including the ID token claims. ++You can view the full code for this sample in the [code repo](https://github.com/Azure-Samples/ms-identity-ciam-dotnet-tutorial/tree/main/1-Authentication/4-sign-in-device-code). |
active-directory | How To Browserless App Node Sample Sign In | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-browserless-app-node-sample-sign-in.md | + + Title: Sign in users in a sample Node.js browserless application using the Device Code flow +description: Learn how to configure a sample browserless application to sign in users in an Azure Active Directory (Azure AD) for customers tenant +++++++++ Last updated : 05/09/2023+++#Customer intent: As a dev, devops, I want to learn about how to configure a sample Node.js browserless application to authenticate users with my Azure Active Directory (Azure AD) for customers tenant +++# Authenticate users in a sample Node.js browserless application using the Device Code flow ++This how-to guide uses a sample Node.js application to show how to sign in users in a browserless application. The sample application uses the device code flow to sign in users in an Azure Active Directory (Azure AD) for customers tenant. ++In this article, you complete the following tasks: ++- Register an application in the Microsoft Entra admin center. ++- Create a sign-in and sign-out user flow in Microsoft Entra admin center. ++- Associate your browserless application with the user flow. ++- Update a sample Node.js browserless application using your own Azure AD for customers tenant. ++- Run and test the sample browserless application. ++## Prerequisites ++- [Node.js](https://nodejs.org). ++- [Visual Studio Code](https://code.visualstudio.com/download) or another code editor. ++- Azure AD for customers tenant. If you don't already have one, [sign up for a free trial](https://aka.ms/ciam-free-trial?wt.mc_id=ciamcustomertenantfreetrial_linkclick_content_cnl). ++## Register the browserless app +++## Grant API permissions +++## Create a user flow +++## Associate the browserless application with the user flow +++## Clone or download sample browserless application ++To get the browserless app sample code, you can do either [download the .zip file](https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial/archive/refs/heads/main.zip) or clone the sample browserless application from GitHub by running the following command: ++```powershell + git clone https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial.git +``` ++## Install project dependencies ++1. Open a console window, and navigate to the directory that contains the Node.js sample app. For example: ++ ```powershell + cd 1-Authentication\4-sign-in-device-code\App + ``` +1. Run the following command to install app dependencies: ++ ```powershell + npm install + ``` ++## Update the sample app to use its Azure app registration details ++1. In your code editor, open the `App\authConfig.js` file. ++1. Find the placeholder: + + 1. `Enter_the_Application_Id_Here` and replace it with the Application (client) ID of the app you registered earlier. + + 1. Find the placeholder `Enter_the_Tenant_Subdomain_Here` and replace it with the Directory (tenant) subdomain. For instance, if your tenant primary domain is `contoso.onmicrosoft.com`, use `contoso`. If you don't have your tenant domain name, [learn how to read your tenant details](how-to-create-customer-tenant-portal.md#get-the-customer-tenant-details). ++## Run and test sample browserless app ++You can now test the sample Node.js browserless app. ++1. In your terminal, run the following command: ++ ```powershell + npm start + ``` ++1. Open your browser, then go to the URL suggested from the message in the terminal, https://microsoft.com/devicelogin. You should see a page similar to the following screenshot: ++ :::image type="content" source="media/how-to-browserless-app-node-sample-sign-in/browserless-app-node-sign-in-enter-code.png" alt-text="Screenshot of the enter code prompt in a node browserless application using the device code flow."::: ++1. To authenticate, copy the device code from the message in the terminal then paste it in the **Enter Code** prompt. After entering the code, you'll be redirected to the sign-in page as follows: ++ :::image type="content" source="media/how-to-browserless-app-node-sample-sign-in/browserless-app-node-sign-in-page.png" alt-text="Screenshot showing the sign in page in a node browserless application."::: ++1. On the sign-in page, type your **Email address**. If you don't have an account, select **No account? Create one**, which starts the sign-up flow. ++1. If you choose the sign-up option, after filling in your email, one-time passcode, new password and more account details, you complete the whole sign-up flow. After completing the sign up flow and signing in, you see a page similar to the following screenshot: ++ :::image type="content" source="media/how-to-browserless-app-node-sample-sign-in/browserless-app-node-signed-in-user.png" alt-text="Screenshot showing a signed-in user in a node browserless application."::: ++1. Move back to the terminal and see your authentication information including the ID token claims returned by Microsoft Entra. ++## Next steps ++Learn how to: ++- [Sign in users in your own Node.js browserless application by using Microsoft Entra](how-to-browserless-app-node-sign-in-overview.md) |
active-directory | How To Browserless App Node Sign In Overview | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-browserless-app-node-sign-in-overview.md | + + Title: Sign in users in your own Node.js browserless application using the Device Code flow - Overview +description: Learn how to build a Node.js browserless application that signs in users using the Device Code flow - Overview. +++++++++ Last updated : 05/09/2023+++#Customer intent: As a dev, devops, I want to learn about how to build a Node.js browserless application to authenticate users with my Azure Active Directory (Azure AD) for customers tenant +++# Sign in users in your own Node.js browserless application using the Device Code flow - Overview ++In this article, you learn how to build a Node.js browserless application that signs in users. The client application you build uses the [OAuth 2.0 device code flow](../../develop/v2-oauth2-device-code.md) to sign in users interactively, using another device such as a mobile phone. ++We've organized the content into three separate articles so it's easy for you to follow: ++- [Prepare your Azure AD for customers tenant](how-to-browserless-app-node-sign-in-prepare-tenant.md) tenant guides you how to register your app and configure user flows in the Microsoft Entra admin center. +- [Prepare your Node.js browserless application](how-to-browserless-app-node-sign-in-prepare-app.md) guides you how to set up your Node.js app structure. +- [Add sign-in and sign-out](how-to-browserless-app-node-sign-in-sign-out.md) guides you how to add authentication support to your application using MSAL Node. ++## Overview ++The device code flow is an OAuth2.0 grant flow that allows users to sign in to input-constrained devices like smart TVs, IoT devices, and printers. In a typical interactive authentication experience, Azure AD for customers requires a web browser for user sign-in. In our browserless application scenario, the app uses the [Microsoft Authentication Library (MSAL) for Node](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-node) to obtain tokens through a flow that involves the following steps: ++1. The application receives a code from the authorization server that is used to initiate authentication. +1. The application prompts the user to use another device and navigate to a URL (for instance, https://microsoft.com/devicelogin), where they're prompted to enter the code. +1. That URL leads the user through a normal authentication experience, including consent prompts and multi-factor authentication if necessary. +1. Upon successful authentication, the app receives the required tokens through a back channel to enable it to perform the web API calls it needs. ++## Prerequisites ++- [Node.js](https://nodejs.org). ++- [Visual Studio Code](https://code.visualstudio.com/download) or another code editor. ++- Azure AD for customers tenant. If you don't already have one, [sign up for a free trial](https://aka.ms/ciam-hub-free-trial). +++If you want to run a sample Node.js browserless application rather than building it from scratch, complete the steps in [Sign in users in a sample Node.js browserless application by using the Device Code flow](how-to-browserless-app-node-sample-sign-in.md) ++## Next steps ++Learn how to prepare your Azure AD for customers tenant: ++> [!div class="nextstepaction"] +> [Prepare your Azure AD for customers tenant >](how-to-browserless-app-node-sign-in-prepare-tenant.md) + |
active-directory | How To Browserless App Node Sign In Prepare App | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-browserless-app-node-sign-in-prepare-app.md | + + Title: Sign in users in your own Node.js browserless application by using the Device Code flow- Prepare app +description: Learn how to build a browserless application to sign in and sign out users - Prepare app +++++++++ Last updated : 05/09/2023+++#Customer intent: As a dev, devops, I want to learn about how to build a Node.js browserless application to authenticate users with my Azure Active Directory (Azure AD) for customers tenant +++# Sign in users in your own Node.js browserless application using the Device Code flow- Prepare app ++In this article, you create a new Node.js browserless application and add all the files and folders required. You'll need to create the app to complete the rest of the articles in this series. However, if you prefer using a completed code sample for learning, download the [sample Node.js browserless application](https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial/archive/refs/heads/main.zip) from GitHub. ++## Create a new Node.js application project ++To build the Node.js browserless application from scratch, follow these steps: ++1. Create a folder to host your application and give it a name, such as *ciam-sign-in-node-browserless-app*. ++1. In your terminal, navigate to your project directory, such as `cd ciam-sign-in-node-browserless-app` and initialize your project using `npm init` + This creates a package.json file in your project folder, which contains references to all npm packages. ++1. In your project root directory, create two files named *authConfig.js* and *index.js*. The *authConfig.js* file contains the authentication configuration parameters while *index.js* holds the application authentication logic. ++ After creating the files, you should achieve the following project structure: ++ ``` + ciam-sign-in-node-browserless-app/ + Γö£ΓöÇΓöÇ authConfig.js + ΓööΓöÇΓöÇ index.js + ΓööΓöÇΓöÇ package.json + ``` ++## Install app dependencies ++The application you build uses MSAL Node to sign in users. To install the MSAL Node package as a dependency in your project, open the terminal in your project directory and run the following command. ++```powershell + npm install @azure/msal-node +``` ++## Next steps ++Learn how to add sign-in support to a Node.js browserless application: ++> [!div class="nextstepaction"] +> [Add sign in and sign out >](how-to-browserless-app-node-sign-in-sign-out.md) ++++ |
active-directory | How To Browserless App Node Sign In Prepare Tenant | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-browserless-app-node-sign-in-prepare-tenant.md | + + Title: Sign in users in a Node.js browserless application using the Device Code flow - Prepare tenant +description: Learn how to build a browserless application to sign in and sign out users - Prepare tenant +++++++++ Last updated : 05/09/2023+++#Customer intent: As a dev, devops, I want to learn about how to build a Node.js browserless application to authenticate users with my Azure Active Directory (Azure AD) for customers tenant +++# Sign in users in your own Node.js browserless application - Prepare your tenant ++In this article, you prepare your Azure Active Directory (Azure AD) for customers tenant for authentication. To prepare your tenant, you do the following tasks: ++- Register a browserless application in the Microsoft Entra admin center. ++- Create a sign in and sign out user flow in Microsoft Entra admin center. ++- Associate your browserless application with the user flow. ++After you complete the tasks, you'll collect an *Application (client) ID* and a *Directory (tenant) ID*. ++If you've already registered a browserless application in the Microsoft Entra admin center, and associated it with a user flow, you can skip the steps in this article and move to [Prepare your Node.js browserless app](how-to-browserless-app-node-sign-in-prepare-app.md). ++## Register the application +++## Grant API permissions +++## Create a user flow +++## Associate the browserless application with the user flow +++## Next steps ++Prepare your app to sign in users in an Azure AD for customers tenant: ++> [!div class="nextstepaction"] +> [Prepare your app to sign in users >](how-to-browserless-app-node-sign-in-prepare-app.md) |
active-directory | How To Browserless App Node Sign In Sign Out | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-browserless-app-node-sign-in-sign-out.md | + + Title: Sign in users in a sample Node.js browserless application by using the Device Code flow - Add sign-in support +description: Learn how to configure a browserless application to sign in and sign out users +++++++++ Last updated : 05/09/2023+++#Customer intent: As a dev, devops, I want to learn about how to build a Node.js browserless application to authenticate users with my Azure Active Directory (Azure AD) for customers tenant +++# Add code to sign in users in a Node.js browserless application. ++To sign in users in a Node.js browserless application, you implement the device code flow by following these steps: ++ - Create the MSAL configuration object + - Import the required modules + - Create an instance of a public client application + - Create the device code request + - Initiate the device code flow + - Run and test your app +++## Create the MSAL configuration object ++In your code editor, open *authConfig.js*, which holds the MSAL object configuration parameters, and add the following code: ++```javascript ++const { LogLevel } = require('@azure/msal-node'); ++const msalConfig = { + auth: { + clientId: 'Enter_the_Application_Id_Here', // 'Application (client) ID' of app registration in Azure portal - this value is a GUID + authority: `https://Enter_the_Tenant_Subdomain_Here.ciamlogin.com/`, // replace "Enter_the_Tenant_Subdomain_Here" with your Directory (tenant) subdomain + }, + system: { + loggerOptions: { + loggerCallback(loglevel, message, containsPii) { + // console.log(message); + }, + piiLoggingEnabled: false, + logLevel: LogLevel.Verbose, + }, + }, +}; +``` +The `msalConfig` object contains a set of configuration options that can be used to customize the behavior of your authentication flows. This configuration object is passed into the instance of our public client application upon creation. In your *authConfig.js* file, find the placeholders: ++- `Enter_the_Application_Id_Here` and replace it with the Application (client) ID of the app you registered earlier. ++- `Enter_the_Tenant_Subdomain_Here` wand replace it with the Directory (tenant) subdomain. For instance, if your tenant primary domain is `contoso.onmicrosoft.com`, use `contoso`. If you don't have your tenant domain name, [learn how to read your tenant details](how-to-create-customer-tenant-portal.md#get-the-customer-tenant-details). ++In the configuration object, you also add `LoggerOptions`, which contains two options: ++- `loggerCallback` - A callback function that handles the logging of MSAL statements +- `piiLoggingEnabled` - A config option that when set to true, enables logging of personally identifiable information (PII). For our app, we set this option to false. ++After creating the `msalConfig` object, add a `loginRequest` object that contains the scopes our application requires. Scopes define the level of access that the application has to user resources. Although the scopes array in the example snippet has no values, MSAL by default adds the OIDC scopes (openid, profile, email) to any login request. Users are asked to consent to these scopes during sign in. To create the `loginRequest` object, add the following code in *authConfig.js*. ++```javascript +const loginRequest = { + scopes: [], +}; +``` +In `authcConfig.js`, export the `msalConfig` and `loginRequest` objects to make them accessible when required by adding the following code: ++```javascript +module.exports = { + msalConfig: msalConfig, + loginRequest: loginRequest, +}; +``` +## Import MSAL and the configuration ++The application we're building uses the Microsoft Authentication Library for Node to authenticate users. To import the MSAL Node package and the configurations defined in the previous step, add the following code to *index.js* ++```javascript +const msal = require('@azure/msal-node'); +const { msalConfig, loginRequest } = require("./authConfig"); ++const msalInstance = new msal.PublicClientApplication(msalConfig); +``` ++## Create an instance of a PublicClientApplication object ++To use MSAL Node, you must first create an instance of a [`PublicClientApplication`](/javascript/api/@azure/msal-node/publicclientapplication) object using the `msalConfig` object. The initialized `PublicClientApplication` object is used to authenticate the user and obtain an access token. ++In *index.js*, add the following code to initialize the public client application: ++```javascript +const msalInstance = new msal.PublicClientApplication(msalConfig); +``` ++## Create the device code request ++To create the [`deviceCodeRequest`](/javascript/api/@azure/msal-node/devicecoderequest) that the application uses to obtain access tokens using the Oauth2 device code flow, add the following code to *index.js* ++```javascript +const getTokenDeviceCode = (clientApplication) => { + + const deviceCodeRequest = { + ...loginRequest, + deviceCodeCallback: (response) => { + console.log(response.message); + }, + }; ++ return clientApplication + .acquireTokenByDeviceCode(deviceCodeRequest) + .then((response) => { + return response; + }) + .catch((error) => { + return error; + }); +} +``` +The `getTokenDeviceCode` function takes a single parameter, `clientApplication`, which is an instance of the `PublicClientApplication` object we created previously. The function creates a new object named `deviceCodeRequest`, which includes the `loginRequest` object imported from the *authConfig.js* file. It also contains a `deviceCodeCallback` function that logs the device code message to the console. ++The `clientApplication` object is then used to call the [`acquireTokenByDeviceCode`](/javascript/api/@azure/msal-node/publicclientapplication#@azure-msal-node-publicclientapplication-acquiretokenbydevicecode) API, passing in the `deviceCodeRequest` object. Once the device code request is executed, the application will display a URL that the user should visit. Upon visiting the URL, the user inputs the code displayed in the console. After entering the code, the promise resolves with either an access token or an error. ++## Initiate the device code flow ++Finally, add the following code to *index.js* to initiate the device code flow by calling the `getTokenDeviceCode` function with the `msalInstance` object created earlier. The returned response object is logged to the console. ++```javascript +getTokenDeviceCode(msalInstance).then(response => { + console.log(response) +}); +``` ++## Run and test your app ++Now that we're done building the app, we can test it by following these steps: +++1. In your terminal, ensure you're in project directory that contains the *package.json* file. For example, *ciam-sign-in-node-browserless-app*. ++1. Use the steps in [Run and test the browserless app](how-to-browserless-app-node-sample-sign-in.md?#run-and-test-sample-browserless-app) article to test your browserless app. +++## Next steps ++Learn how to: ++- [Enable password reset](how-to-enable-password-reset-customers.md). |
active-directory | How To Create Customer Tenant Portal | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-create-customer-tenant-portal.md | + + Title: Create a customer tenant +description: Learn how to create a customer tenant in the Microsoft Entra admin center. +++++++ Last updated : 05/09/2023++++#Customer intent: As an it admin, I want to learn how to create a customer tenant in the Microsoft Entra admin center. +++# Create a customer identity and access management (CIAM) tenant ++Azure Active Directory (Azure AD) offers a customer identity access management (CIAM) solution that lets you create secure, customized sign-in experiences for your customer-facing apps and services. With these built-in CIAM features, Azure AD can serve as the identity provider and access management service for your customer scenarios. You'll need to create a customer tenant in the Microsoft Entra admin center to get started. Once the customer tenant is created, you can access it in both the Microsoft Entra admin center and the Azure portal. ++In this article, you learn how to: ++- Create a customer tenant +- Switch to the directory containing your customer tenant +- Find your customer tenant name and ID in the Microsoft Entra admin center ++## Prerequisites ++- An Azure subscription. If you don't have one, create a [free account](https://azure.microsoft.com/free/?WT.mc_id=A261C142F) before you begin. +- An Azure account that's been assigned at least the [Contributor](/azure/role-based-access-control/built-in-roles#contributor) role scoped to the subscription or to a resource group within the subscription. +- If you don't have an Azure account, sign up for a [30-day free trial](quickstart-trial-setup.md). ++## Create a new customer tenant ++1. Sign in to your organization's [Microsoft Entra admin center](https://entra.microsoft.com/). +1. From the left menu, select **Azure Active Directory** > **Overview**. +1. On the overview page, select **Manage tenants** +1. Select **Create**. ++ :::image type="content" source="media/how-to-create-customer-tenant-portal/create-tenant.png" alt-text="Screenshot of the create tenant option."::: ++1. Select **Customer**, and then **Continue**. If you filtered the list of tenants by **Tenant type**: **Customer** in the previous step, this step will be skipped. ++ :::image type="content" source="media/how-to-create-customer-tenant-portal/select-tenant-type.png" alt-text="Screenshot of the select tenant type screen."::: ++1. If you're creating a customer tenant for the first time, you have the option to create a trial tenant that doesn't require an Azure subscription. Otherwise, use the Azure Subscription option to continue to the next step. + + :::image type="content" source="media/how-to-create-customer-tenant-portal/create-first-customer-tenant.png" alt-text="Screenshot of the two customer tenant options available during the initial CIAM tenant creation."::: ++1. If you choose the 30-day free trial, an Azure subscription isn't required. +1. If you choose **Use Azure Subscription** option, then the admin center displays the tenant creation page. On the **Basics** tab, in the **Create a tenant for customers** page, enter the following information: ++ :::image type="content" source="media/how-to-create-customer-tenant-portal/add-basics-to-customer-tenant.png" alt-text="Screenshot of the Basics tab."::: ++ - Type your desired **Tenant Name** (for example *Contoso Customers*). ++ - Type your desired **Domain Name** (for example *Contosocustomers*). ++ - Select your desired **Location**. This selection can't be changed later. ++1. Select **Next: Add a subscription**. ++1. On the **Add a subscription** tab, enter the following information: ++ - Next to **Subscription**, select your subscription from the menu. ++ - Next to **Resource group**, select a resource group from the menu. If there are no available resource groups, select **Create new**, type a **Name**, and then select **OK**. ++ - If **Resource group location** appears, select the geographic location of the resource group from the menu. ++ :::image type="content" source="media/how-to-create-customer-tenant-portal/add-subscription.png" alt-text="Screenshot that shows the subscription settings."::: ++1. Select **Next: Review + Create**. If the information that you entered is correct, select **Create**. The tenant creation process can take up to 30 minutes. You can monitor the progress of the tenant creation process in the **Notifications** pane. Once the customer tenant is created, you can access it in both the Microsoft Entra admin center and the Azure portal. +1. The tenant creation may take a few minutes to complete. You can monitor the progress by checking the notification bell at the top right corner of the screen. Once the tenant is successfully created, you can navigate to it by selecting the link provided below. ++ :::image type="content" source="media/how-to-create-customer-tenant-portal/tenant-successfully-created.png" alt-text="Screenshot that shows the link to the new customer tenant."::: ++## Get the customer tenant details ++If you're not sure which directory contains your customer tenant, you can find the tenant name and ID both in the Microsoft Entra admin center and in the Azure portal. ++1. To make sure you're using the directory that contains your customer tenant, select the **Directories + subscriptions** icon in the toolbar. ++ :::image type="content" source="media/how-to-create-customer-tenant-portal/directories-subscription.png" alt-text="Screenshot of the Directories + subscriptions icon."::: ++1. On the **Portal settings | Directories + subscriptions** page, find your customer tenant in the **Directory name** list, and then select **Switch**. +1. On the tenant's home page, select the **Overview** tab. You can find the tenant **Name**, **Tenant ID** and **Primary domain** under **Basic information**. ++ :::image type="content" source="media/how-to-create-customer-tenant-portal/tenant-overview.png" alt-text="Screenshot of the tenant details."::: ++You can find the same details if you go to **Azure Active Directory** either in the Microsoft Entra admin center or in the Azure portal. On the **Azure Active Directory** page, you can find the tenant **Name**, **Tenant ID** and **Primary domain** under **Overview** > **Basic information**. ++## Next steps +- [Register an app](how-to-register-ciam-app.md) +- [Create user flows](how-to-user-flow-sign-up-sign-in-customers.md) |
active-directory | How To Customize Branding Customers | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-customize-branding-customers.md | + + Title: Customize your branding for your customers +description: Learn how to customize the look and feel of your customers' sign-in experiences. +++++++ Last updated : 04/21/2023++++#Customer intent: As an it admin, I want to learn about the options for customizing the look and feel of the customer sign-in and sing-up experience. +++# Customize the neutral branding in your customer tenant ++After creating a new customer tenant, you can customize the end-user experience. Create a custom look and feel for users signing in to your web-based apps by configuring **Company branding** settings for your tenant. With these settings, you can add your own background images, colors, company logos, and text to customize the sign-in experiences across your apps. +You can also create user flows programmatically using the Company Branding Graph API. ++## Prerequisites ++- If you haven't already created your own Azure AD customer tenant, create one now. +- [Register an application](how-to-register-ciam-app.md). +- [Create a user flow](how-to-user-flow-sign-up-sign-in-customers.md) +- Review the file size requirements for each image you want to add. You may need to use a photo editor to create the right-sized images. The preferred image type for all images is PNG, but JPG is accepted. ++## Comparing the default sign-in experiences between the customer tenant and the Azure AD tenant ++The default sign-in experience is the global look and feel that applies across all sign-ins to your tenant. The default branding experiences between the customer tenant and the default Azure AD tenant are distinct. ++Your Azure AD tenant supports Microsoft look and feel as a default state for authentication experience. You can [customize the default Microsoft sign-in experience](/azure/active-directory/fundamentals/how-to-customize-branding) with a custom background image or color, favicon, layout, header, and footer. You can also upload a custom CSS. If the custom company branding fails to load for any reason, the sign-in page will revert to the default Microsoft branding. ++Microsoft provides a neutral branding as the default for the customer tenant, which can be customized to meet the specific needs of your company. The default branding for the customer tenant is neutral and doesn't include any existing Microsoft branding. If the custom company branding fails to load for any reason, the sign-in page will revert to this neutral branding. It's also possible to add each custom branding property to the custom sign-in page individually. ++The following list and image outline the elements of the default Microsoft sign-in experience in an Azure AD tenant: ++1. Microsoft background image and color. +2. Microsoft favicon. +3. Microsoft banner logo. +4. Footer as a page layout element. +5. Microsoft footer hyperlinks, for example, Privacy & cookies, Terms of use and troubleshooting details also known as ellipsis in the right bottom corner of the screen. +6. Microsoft overlay. ++ :::image type="content" source="media/how-to-customize-branding-customers/azure-ad-microsoft-branding.png" alt-text="Screenshot of the Azure AD default Microsoft branding." lightbox="media/how-to-customize-branding-customers/azure-ad-microsoft-branding.png"::: ++The following image displays the neutral default branding of the customer tenant: + :::image type="content" source="media/how-to-customize-branding-customers/ciam-neutral-branding.png" alt-text="Screenshot of the CIAM neutral branding." lightbox="media/how-to-customize-branding-customers/ciam-neutral-branding.png"::: ++## How to customize the default sign-in experience ++Before you customize any settings, the neutral default branding will appear in your sign-in and sign-up pages. You can customize this default experience with a custom background image or color, favicon, layout, header, and footer. You can also upload a custom CSS. ++1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com/). +1. If you have access to multiple tenants, use the **Directories + subscriptions** filter in the top menu to switch to the customer tenant you created earlier. +1. In the search bar, type and select **Company branding**. +1. Under **Default sign-in** select **Edit**. ++ :::image type="content" source="media/how-to-customize-branding-customers/company-branding-default-edit-button.png" alt-text="Screenshot of the company branding edit button."::: ++### To customize the sign-in page background and layout ++1. On the **Basics** tab, modify any of the background elements. ++ - **Favicon** ΓÇô The icon that displays in the web browser tab. ++ - **Background image** ΓÇô The large image that displays on the sign-in page. If you upload an image, it will scale and crop to fill the browser window. ++ - **Page background color** ΓÇô The color that replaces the background image whenever the image canΓÇÖt be loaded, for example due to connection latency. ++ :::image type="content" source="media/how-to-customize-branding-customers/company-branding-basics-tab.png" alt-text="Screenshot of the company branding basics tab." lightbox="media/how-to-customize-branding-customers/company-branding-basics-tab.png"::: ++1. Select **Next: Layout** if you would like to continue customizing or **Review + save** if you would like to save your changes. ++1. On the Layout tab, select the placement of web page elements on the sign-in page. ++ - **Template** ΓÇô Choose whether the background displays full-screen or partial-screen. ++ - **Header** ΓÇô Show or hide the header. ++ - **Footer** ΓÇô Show or hide the footer. ++ - **Custom CSS** ΓÇô Upload your own CSS file to replace default Microsoft styling with your own styling for: color, font, text size, position of elements, and displays for different devices and screen sizes. ++ :::image type="content" source="media/how-to-customize-branding-customers/company-branding-layout-tab.png" alt-text="Screenshot of the company branding layout tab." lightbox="media/how-to-customize-branding-customers/company-branding-layout-tab.png"::: ++1. Select **Next: Header** if you would like to continue customizing or **Review + save** if you would like to save your changes. ++### To customize the logo, privacy link, and terms of use ++1. On the **Header** tab, select the logo to display in the header of the sign-in page. ++ :::image type="content" source="media/how-to-customize-branding-customers/company-branding-header-tab.png" alt-text="Screenshot of the company branding header tab."::: ++1. Select **Next: Footer** if you would like to continue customizing or **Review + save** if you would like to save your changes. ++1. On the **Footer** tab, you can customize the URLs and link text for the privacy and terms of use hyperlinks that appear in the footer of the sign-in page. ++ - **Privacy & Cookies** ΓÇô Select the checkbox next to Privacy & Cookies to display this hyperlink in the footer. The Microsoft default privacy link will display unless you enter your own hyperlink Display text and URL. ++ - **Terms of Use** ΓÇô Select the checkbox next to Terms of Use to display this hyperlink in the footer. The Microsoft terms of use link will display unless you enter your own hyperlink Display text and URL. ++ :::image type="content" source="media/how-to-customize-branding-customers/company-branding-footer-tab.png" alt-text="Screenshot of the company branding footer tab." lightbox="media/how-to-customize-branding-customers/company-branding-footer-tab.png"::: ++1. Select **Next: Sign-in form** if you would like to continue customizing or **Review + save** if you would like to save your changes. ++### To customize the sign-in form ++1. On the **Sign-in form** tab, configure elements of the sign-in form: ++ - **Banner logo** ΓÇô Displays on the sign-in page and in the userΓÇÖs access panel. ++ - **Square logo (light theme)** ΓÇô Represents user accounts in your organization. ++ - **Square logo (dark theme)** ΓÇô If the light theme square logo displays poorly on dark backgrounds, you can upload a logo to be used in its place when dark backgrounds are used. ++ :::image type="content" source="media/how-to-customize-branding-customers/company-branding-sign-in-form-tab.png" alt-text="Screenshot of the company branding sign-in form tab." lightbox="media/how-to-customize-branding-customers/company-branding-sign-in-form-tab.png"::: ++1. Scroll to the lower half of the page and configure more elements of the sign-in form: ++ - **Username hint text** ΓÇô The hint text that displays in the username input field on the sign-in page (not recommended if guest users sign in to your app). ++ - **Sign-in page text** ΓÇô Appears at the bottom of the sign-in and sign-up pages. Guidelines: ++ - 1024 characters maximum + - Don't include sensitive information + - Use this syntax to format text: + - Hyperlink: `[text](link)` + - Bold: `**text** or __text__` + - Italics: `*text* or _text_` + - Underline: `++text++` ++### To customize self-service password reset ++ 1. Scroll to the **Self-service password reset** section to configure options for showing, hiding, or customizing the self-service password reset link on the sign-in page. ++ - **Show self-service password reset** ΓÇô Select this checkbox to display the self-service password link. + - **Common URL** ΓÇô Enter a password reset URL to use in place of the default Microsoft link. + - **Account collection display text** ΓÇô Enter link text to display in place of the Microsoft default text ΓÇ£CanΓÇÖt access your accountΓÇ¥ text. + - **Password collection display text** ΓÇô Enter link text to display in place of the Microsoft default ΓÇ£Forgot passwordΓÇ¥ text. + + :::image type="content" source="media/how-to-customize-branding-customers/company-branding-self-service-password-reset.png" alt-text="Screenshot of the company branding Self-service password reset ." lightbox="media/how-to-customize-branding-customers/company-branding-self-service-password-reset.png"::: ++1. Select **Next: Review** and review all your modifications. Then select **Save** if you would like to save your changes or **Previous** if you would like to continue customizing. ++### To customize user attributes ++For your customer tenant, you might have different requirements for the information you want to collect during sign-up and sign-in. The customer tenant comes with a built-in set of information stored in attributes, such as Given Name, Surname, City, and Postal Code. You can create custom attributes in your customer tenant using the Microsoft Graph API or in the portal under the **Text** tab in **Company Branding**. ++1. On the **Text** tab select **Add Custom Text**. +1. Select any of the options: ++ - Select **Attributes** to override the default values. + - Select **Attribute collection** to add a new attribute option that you would like to collect during the sign-up process. + - Select **Sign in** to add custom text for the sign-in page. + - Select **Sign up** to add custom text for the sign-in page. + - Select **Sign-in/up one time code (SISU OTC)** to add a custom title. ++ :::image type="content" source="media/how-to-customize-branding-customers/custom-text.png" alt-text="Screenshot of the company branding text tab." lightbox="media/how-to-customize-branding-customers/custom-text.png"::: ++1. Select **Add** once you finished with your changes. You can edit the existing custom text by selecting the **Text name** and select Save. ++> [!IMPORTANT] +> In the customer tenant, we have two options to add custom text to the sign-up and sign-in experience. The function is available under each user flow during language customization and also under Company branding. Although we have two ways to customize strings (via Company Branding and via User Flows), both ways modify the same JSON file. The most recent change made either via User flows or via Company branding will always override the previous one. ++## How to customize the tenant name ++Your customer tenant name replaces the Microsoft banner logo in the neutral default sign-in experience. You can customize your tenant's name in the Properties area. +++1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com/). +1. If you have access to multiple tenants, use the **Directories + subscriptions** filter in the top menu to switch to the customer tenant you created earlier. +1. In the search bar, type and select **Properties**. +1. Edit the **Name** field. ++ :::image type="content" source="media/how-to-customize-branding-customers/tenant-name-edit.png" alt-text="Screenshot of editing the tenant name."::: ++5. Select **Save**. ++## Clean up resources via the portal ++When no longer needed, you can remove the sign-in customization from your customer tenant via the Azure portal. ++1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com/). +1. If you have access to multiple tenants, use the **Directories + subscriptions** filter in the top menu to switch to the customer tenant you created earlier. +1. In the search bar, type and select **Company branding**. +1. Under **Default sign-in experience**, select **Edit**. +1. Remove the elements you no longer need. +1. Once finished select **Review + save**. +1. Wait a few minutes for the changes to take effect. ++## Clean up resources via the Microsoft Graph API ++When no longer needed, you can remove the sign-in customization from your customer tenant via the Microsoft Graph API. ++1. Sign in to the [MS Graph explorer](https://developer.microsoft.com/en-us/graph/graph-explorer) with your customer tenant account: `https://developer.microsoft.com/en-us/graph/graph-explorer?tenant=<your-tenant-name.onmicrosoft.com>`. ++1. Query the default branding object using the Microsoft Graph API beta version: `https://graph.microsoft.com/beta/organization/<your-tenant-ID>/branding/localizations`. To confirm that you're signed in to your customer tenant, verify the tenant name on the right side of the screen. ++ :::image type="content" source="media/how-to-customize-branding-customers/msgraph-ciam-branding.png" alt-text="Screenshot of MS Graph API with CIAM tenant logged in." lightbox="media/how-to-customize-branding-customers/msgraph-ciam-branding.png"::: ++3. [Remove default branding object](/graph/api/organizationalbrandinglocalization-delete) using the Microsoft Graph API beta version and the DELETE request. +4. Wait a few minutes for the changes to take effect. ++## Next steps ++- [Language customization](how-to-customize-languages-customers.md) |
active-directory | How To Customize Languages Customers | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-customize-languages-customers.md | + + Title: Customize the browser language for authentication +description: Learn about how to customize the browser language of your app's authentication experience. ++++++++ Last updated : 05/09/2023+++#Customer intent: As a dev, devops, or it admin, I want to learn about how to add customized browser languages to my app's authentication experience. ++# Customize the language of the authentication experience ++You can create a personalized sign-in experience for users who sign in using a specific browser language by customizing the branding elements. If you don't make any changes to the elements, the default elements will be displayed. ++## Prerequisites ++- If you haven't already created your own Azure AD customer tenant, create one now. +- [Register an application](how-to-register-ciam-app.md). +- [Create a user flow](how-to-user-flow-sign-up-sign-in-customers.md) +- Review the file size requirements for each image you want to add. You may need to use a photo editor to create the right-sized images. The preferred image type for all images is PNG, but JPG is accepted. ++## Add browser language under Company branding ++1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com/). +1. If you have access to multiple tenants, use the **Directories + subscriptions** filter in the top menu to switch to the customer tenant you created earlier. +1. In the search bar, type and select **Company branding**. +1. Under **Browser language customizations**, select **Add browser language**. ++ :::image type="content" source="media/how-to-customize-languages-customers/company-branding-add-browser-language.png" alt-text="Screenshot of the browser language customizations tab." lightbox="media/how-to-customize-languages-customers/company-branding-add-browser-language.png"::: ++4. On the **Basics** tab, under **Language specific UI Customization**, select the browser language you want to customize from the menu. ++ :::image type="content" source="media/how-to-customize-languages-customers/language-selection.png" alt-text="Screenshot of selecting a language." lightbox="media/how-to-customize-languages-customers/language-selection.png"::: ++The following languages are supported in the customer tenant: ++ - Arabic (Saudi Arabia) + - Basque (Basque) + - Bulgarian (Bulgaria) + - Catalan (Catalan) + - Chinese (China) + - Chinese (Hong Kong SAR) + - Croatian (Croatia) + - Czech (Czechia) + - Danish (Denmark) + - Dutch (Netherlands) + - English (United States) + - Estonian (Estonia) + - Finnish (Finland) + - French (France) + - Galician (Galician) + - German (Germany) + - Greek (Greece) + - Hebrew (Israel) + - Hungarian (Hungary) + - Italian (Italy) + - Japanese (Japan) + - Kazakh (Kazakhstan) + - Korean (Korea) + - Latvian (Latvia) + - Lithuanian (Lithuania) + - Norwegian Bokmål (Norway) + - Polish (Poland) + - Portuguese (Brazil) + - Portuguese (Portugal) + - Romanian (Romania) + - Russian (Russia) + - Serbian (Latin, Serbia) + - Slovak (Slovakia) + - Slovenian (Sierra Leone) + - Spanish (Spain) + - Swedish (Sweden) + - Thai (Thailand) + - Turkish (Turkey) + - Ukrainian (Ukraine) + +6. Customize the elements on the **Basics**, **Layout**, **Header**, **Footer**, **Sign-in form**, and **Text** tabs. For detailed instructions, see [Customize the branding and end-user experience](how-to-customize-branding-customers.md). +7. When you’re finished, select the **Review** tab and go over all of your language customizations. Then select **Add** if you would like to save your changes or **Previous** if you would like to continue editing. ++## Add language customization to a user flow ++Language customization in the customer tenant allows your user flow to accommodate different languages to suit your customer's needs. You can use languages to modify the strings displayed to your customers as part of the attribute collection process during sign-up. ++1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com/). +2. If you have access to multiple tenants, use the **Directories + subscriptions** filter in the top menu to switch to the customer tenant you created earlier. +3. In the left menu, select **Azure Active Directory** > **External Identities**. +4. Select **User flows**. +5. Select the user flow that you want to enable for translations. +6. Select **Languages**. +7. On the **Languages** page for the user flow, select the language that you want to customize. +8. Expand **Sign up and sign in (Preview)**. +9. Select **Download defaults** (or **Download overrides** if you have previously edited this language). ++ :::image type="content" source="media/how-to-customize-languages-customers/language-customization-flow.png" alt-text="Screenshot the shows how to add languages under a user flow." lightbox="media/how-to-customize-languages-customers/language-customization-flow.png"::: ++The downloaded file will be in JSON format and will include both built-in and custom attributes, as well as other page-level and error strings: ++```http +{ + "AttributeCollection_Description": "Wir benötigen nur ein paar weitere Informationen, um Ihr Konto einzurichten.", + "AttributeCollection_Title": "Details hinzufügen", + "Attribute_City": "Ort", + "Attribute_Country": "Land/Region", + "Attribute_DisplayName": "Anzeigename", + "Attribute_Email": "E-Mail-Adresse", + "Attribute_Generic_ConfirmationLabel": "{0} erneut eingeben", + "Attribute_GivenName": "Vorname", + "Attribute_JobTitle": "Position", + "Attribute_Password": "Kennwort", + "Attribute_Password_MismatchErrorString": "Kennwörter stimmen nicht überein.", + "Attribute_PostalCode": "Postleitzahl", + "Attribute_State": "Bundesland/Kanton", + "Attribute_StreetAddress": "Straße", + "Attribute_Surname": "Nachname", + "SignIn_Description": "Melden Sie sich an, um auf {0} zuzugreifen.", + "SignIn_Title": "Anmelden", + "SignUp_Description": "Registrieren Sie sich, um auf {0} zuzugreifen.", + "SignUp_Title": "Konto erstellen", + "SisuOtc_Title": "Code eingeben", + "Attribute_extension_a235ca9a0a7c4d33bd69e07bed81c8b1_Shoesize": "Shoe size" +} +``` ++You can modify any or all of these attributes in the downloaded file. For example, you can modify the built-in attribute, **City** and the custom attribute, **Shoesize**: +++```http +{ + "AttributeCollection_Description": "Wir benötigen nur ein paar weitere Informationen, um Ihr Konto einzurichten.", + "AttributeCollection_Title": "Details hinzufügen", + "Attribute_City": "Ort2", + "Attribute_Country": "Land/Region", + "Attribute_DisplayName": "Anzeigename", + "Attribute_Email": "E-Mail-Adresse", + "Attribute_Generic_ConfirmationLabel": "{0} erneut eingeben", + "Attribute_GivenName": "Vorname", + "Attribute_JobTitle": "Position", + "Attribute_Password": "Kennwort", + "Attribute_Password_MismatchErrorString": "Kennwörter stimmen nicht überein.", + "Attribute_PostalCode": "Postleitzahl", + "Attribute_State": "Bundesland/Kanton", + "Attribute_StreetAddress": "Straße", + "Attribute_Surname": "Nachname", + "SignIn_Description": "Melden Sie sich an, um auf {0} zuzugreifen.", + "SignIn_Title": "Anmelden", + "SignUp_Description": "Registrieren Sie sich, um auf {0} zuzugreifen.", + "SignUp_Title": "Konto erstellen", + "SisuOtc_Title": "Code eingeben", + "Attribute_extension_a235ca9a0a7c4d33bd69e07bed81c8b1_Shoesize": "Schuhgröße" +} +``` ++10. After making the necessary changes, you can upload the new overrides file. The changes are saved to your user flow automatically and you'll find the override under the **Configured** tab. +11. To double-check your changes, select the language under the **Configured** tab and expand the **Sign up and sign in (Preview)** option. You can view your customized language file by selecting Download overrides. To remove your customized override file, select **Remove overrides**. ++ :::image type="content" source="media/how-to-customize-languages-customers/remove-download-override-file.png" alt-text="Screenshot the shows how to remove or download the modified JSON file." lightbox="media/how-to-customize-languages-customers/remove-download-override-file.png"::: + +12. Go to the sign-in page of your customer tenant. Make sure you have the right locale and market in your URLs, for example: ui_locales=de-DE and mkt=de-DE. You'll see the updated attributes on the sign-up page: ++ :::image type="content" source="media/how-to-customize-languages-customers/customized-attributes.png" alt-text="Screenshot of the modified sign-up page attributes."::: ++> [!IMPORTANT] +> In the customer tenant, we have two options to add custom text to the sign-up and sign-in experience. The function is available under each user flow during language customization and under [Company Branding](https://github.com/csmulligan/entra-previews/blob/PP3/docs/PP3_Customize%20CIAM%20neutral%20branding.md#customize-the-neutral-default-authentication-experience-for-the-ciam-tenant). Although we have to ways to customize strings (via Company branding and via User flows), both ways modify the same JSON file. The most recent change made either via User flows or via Company branding will always override the previous one. ++## Right-to-left language support ++Languages that are read right-to-left, such as Arabic and Hebrew, are displayed in the opposite direction compared to languages that are read left-to-right. The customer tenant supports right-to-left functionality and features for languages that work in a right-to-left environment for entering, and displaying data. Right-to-left readers can interact in a natural reading manner. +++## Next steps ++- [Customize the branding and end-user experience](how-to-customize-branding-customers.md) |
active-directory | How To Daemon Node Call Api Call Api | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-daemon-node-call-api-call-api.md | + + Title: Call an API in your Node.js daemon application - acquire an access token +description: Learn how to acquire an access token by using client credentials flow, the use the token to call a web API in your own Node.js daemon application. +++++++++ Last updated : 05/22/2023++++# Call an API in your Node.js daemon application - acquire an access token ++In this article, you update the daemon app you prepared in the previous chapter, [prepare your client app and API](how-to-daemon-node-call-api-prepare-app.md), to acquire an access token, then call a web API. The application you build uses [Microsoft Authentication Library (MSAL) for Node](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-node) to simplify adding authorization to your node daemon application. ++## Create MSAL configuration object ++In your code editor, open *authConfig.js* file, then add the following code: ++```javascript +require('dotenv').config(); ++/** + * Configuration object to be passed to MSAL instance on creation. + * For a full list of MSAL Node configuration parameters, visit: + * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-node/docs/configuration.md + */ +const msalConfig = { + auth: { + clientId: process.env.CLIENT_ID || 'Enter_the_Application_Id_Here', // 'Application (client) ID' of app registration in Azure portal - this value is a GUID + authority: process.env.AUTHORITY || 'https://Enter_the_Tenant_Subdomain_Here.ciamlogin.com/', // Replace "Enter_the_Tenant_Subdomain_Here" with your tenant subdomain + clientSecret: process.env.CLIENT_SECRET || 'Enter_the_Client_Secret_Here', // Client secret generated from the app + }, + system: { + loggerOptions: { + loggerCallback(loglevel, message, containsPii) { + console.log(message); + }, + piiLoggingEnabled: false, + logLevel: 'Info', + }, + }, +}; +const protectedResources = { + apiToDoList: { + endpoint: process.env.API_ENDPOINT || 'https://localhost:44351/api/todolist', + scopes: [process.env.SCOPES || 'api://Enter_the_Web_Api_Application_Id_Here'], + }, +}; ++module.exports = { + msalConfig, + protectedResources, +}; +``` +The `msalConfig` object contains a set of configuration options that you use to customize the behavior of your authorization flow. ++In your *authConfig.js* file, replace: ++- `Enter_the_Application_Id_Here` with the Application (client) ID of the client daemon app that you registered earlier. ++- `Enter_the_Tenant_Subdomain_Here` and replace it with the Directory (tenant) subdomain. For example, if your tenant primary domain is `contoso.onmicrosoft.com`, use `contoso`. If you don't have your tenant name, learn how to [read your tenant details](how-to-create-customer-tenant-portal.md#get-the-customer-tenant-details). ++- `Enter_the_Client_Secret_Here` with the client daemon app secret value that you copied earlier. ++- `Enter_the_Web_Api_Application_Id_Here` with the Application (client) ID of the web API app that you copied earlier. ++Notice that the `scopes` property in the `protectedResources` variable is the resource identifier (application ID URI) of the [web API](how-to-daemon-node-call-api-prepare-tenant.md#register-a-web-api-application) that you registered earlier. The complete scope URI looks similar to `api://Enter_the_Web_Api_Application_Id_Here/.default`. ++## Acquire an access token ++In your code editor, open *auth.js* file, then add the following code: ++```javascript +const msal = require('@azure/msal-node'); +const { msalConfig, protectedResources } = require('./authConfig'); +/** + * With client credentials flows permissions need to be granted in the portal by a tenant administrator. + * The scope is always in the format '<resource-appId-uri>/.default'. For more, visit: + * https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow + */ +const tokenRequest = { + scopes: [`${protectedResources.apiToDoList.scopes}/.default`], +}; ++const apiConfig = { + uri: protectedResources.apiToDoList.endpoint, +}; ++/** + * Initialize a confidential client application. For more info, visit: + * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-node/docs/initialize-confidential-client-application.md + */ +const cca = new msal.ConfidentialClientApplication(msalConfig); +/** + * Acquires token with client credentials. + * @param {object} tokenRequest + */ +async function getToken(tokenRequest) { + return await cca.acquireTokenByClientCredential(tokenRequest); +} ++module.exports = { + apiConfig: apiConfig, + tokenRequest: tokenRequest, + getToken: getToken, +}; +``` +In the code: ++- Prepare the `tokenRequest` and `apiConfig` object. The `tokenRequest` contains the scope for which you request an access token. The scope looks something like `api://Enter_the_Web_Api_Application_Id_Here/.default`. The `apiConfig` object contains the endpoint to your web API. Learn more about [OAuth 2.0 client credentials flow](../../develop/v2-oauth2-client-creds-grant-flow.md). ++- You create a confidential client instance by passing the `msalConfig` object to the [ConfidentialClientApplication](/javascript/api/@azure/msal-node/confidentialclientapplication#constructors) class' constructor. ++ ```javascript + const cca = new msal.ConfidentialClientApplication(msalConfig); + ``` ++- You then use the [acquireTokenByClientCredential](/javascript/api/@azure/msal-node/confidentialclientapplication#@azure-msal-node-confidentialclientapplication-acquiretokenbyclientcredential) function to acquire an access token. You implement this logic in the `getToken` function: ++ ```javascript + cca.acquireTokenByClientCredential(tokenRequest); + ``` +Once you acquire an access token, you can proceed to call an API. ++## Call an API ++In your code editor, open *fetch.js* file, then add the following code: ++```javascript +const axios = require('axios'); ++/** + * Calls the endpoint with authorization bearer token. + * @param {string} endpoint + * @param {string} accessToken + */ +async function callApi(endpoint, accessToken) { ++ const options = { + headers: { + Authorization: `Bearer ${accessToken}` + } + }; ++ console.log('request made to web API at: ' + new Date().toString()); ++ try { + const response = await axios.get(endpoint, options); + return response.data; + } catch (error) { + console.log(error) + return error; + } +}; ++module.exports = { + callApi: callApi +}; +``` +In this code, you make a call to the web API, by passing the access token as a bearer token in the request `Authorization` header: ++```javascript + Authorization: `Bearer ${accessToken}` +``` ++You use the access token that you acquired earlier in [Acquire an access token](#acquire-an-access-token). ++Once the web API receives the request, it evaluates it then determines that it's an application request. If the access token is valid, the web API returns requested data. Otherwise, the API returns a `401 Unauthorized` HTTP error. ++## Finalize your daemon app ++In your code editor, open *index.js* file, then add the following code: ++```javascript +#!/usr/bin/env node ++// read in env settings ++require('dotenv').config(); ++const yargs = require('yargs'); +const fetch = require('./fetch'); +const auth = require('./auth'); ++const options = yargs + .usage('Usage: --op <operation_name>') + .option('op', { alias: 'operation', describe: 'operation name', type: 'string', demandOption: true }) + .argv; ++async function main() { + console.log(`You have selected: ${options.op}`); ++ switch (yargs.argv['op']) { + case 'getToDos': + try { + const authResponse = await auth.getToken(auth.tokenRequest); + const todos = await fetch.callApi(auth.apiConfig.uri, authResponse.accessToken); + } catch (error) { + console.log(error); + } ++ break; + default: + console.log('Select an operation first'); + break; + } +}; ++main(); +``` ++This code is the entry point to your app. You use the [yargs js](https://www.npmjs.com/package/yargs) command-line argument parsing library for Node.js apps to interactively fetch an access token, then call API. You use the `getToken` and `callApi` functions you defined earlier: ++```javascript +const authResponse = await auth.getToken(auth.tokenRequest); +const todos = await fetch.callApi(auth.apiConfig.uri, authResponse.accessToken); +``` +## Run and test daemon app and API ++At this point, you're ready to test your client daemon app and web API: ++1. Use the steps you learned in [Secure an ASP.NET web API](how-to-protect-web-api-dotnet-core-overview.md) article to start your web API. Your web API is now ready to serve client requests. If you don't run your web API on port `44351` as specified in the *authConfig.js* file, make sure you update the file to use your web API's port number. ++1. In your terminal, make sure you're in the project folder that contains your daemon Node app such as `ciam-call-api-node-daemon`, then run the following command: ++ ```console + node . --op getToDos + ``` ++If your daemon app and web API successfully run, you should find the data returned by the web API endpoint `todos` variable. ++## Next steps ++Learn how to [Use client certificate instead of a secret for authentication in your Node.js confidential app](how-to-web-app-node-use-certificate.md). |
active-directory | How To Daemon Node Call Api Overview | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-daemon-node-call-api-overview.md | + + Title: Call an API in your Node.js daemon application +description: Learn how to configure your Node.js daemon application that calls an API. The API is protected by Azure Active Directory (Azure AD) for customers +++++++++ Last updated : 05/22/2023+++#Customer intent: As a dev, devops, I want to create a Node.js daemon application that acquires an access token, then calls an API protected by Azure Active Directory (Azure AD) for customers tenant +++# Call an API in your Node.js daemon application ++In this article, you learn how to acquire an access token, then call a web API in your own Node.js daemon application. You add authorization to your daemon application against your Azure Active Directory (Azure AD) for customers tenant. ++We've organized the content into three separate articles so it's easy for you to follow: ++- [Prepare your Azure AD for customers tenant](how-to-daemon-node-call-api-prepare-app.md) tenant guides you how to register your app and configure user flows in the Microsoft Entra admin center. ++- [Prepare your daemon application](how-to-daemon-node-call-api-prepare-app.md) guides you how to set up your Node.js app structure. ++- [Acquire an access token and call API](how-to-daemon-node-call-api-call-api.md) guides you how to acquire an access token using client credentials flow, then use the token to call a web API. ++## Overview ++The [OAuth 2.0 client credentials grant flow](../../develop/v2-oauth2-client-creds-grant-flow.md) permits a web service (confidential client) to use its own credentials, instead of impersonating a user, to authenticate when calling another web service. ++The client credentials grant flow is commonly used for server-to-server interactions that must run in the background, without immediate interaction with a user. ++The application you build uses [Microsoft Authentication Library (MSAL) for Node](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-node) to simplify adding authorization to your node daemon application. +++## Prerequisites ++- [Node.js](https://nodejs.org). ++- [Visual Studio Code](https://code.visualstudio.com/download) or another code editor. ++- Azure AD for customers tenant. If you don't already have one, [sign up for a free trial](https://aka.ms/ciam-free-trial?wt.mc_id=ciamcustomertenantfreetrial_linkclick_content_cnl). +++If you want to run a sample Node.js daemon application to get a feel of how things work, complete the steps in [Call an API in a sample Node.js daemon application](how-to-daemon-node-sample-call-api.md). ++## Next steps ++Next, learn how to prepare your Azure AD for customers tenant. ++> [!div class="nextstepaction"] +> [Prepare your Azure AD for customers tenant for authorization >](how-to-daemon-node-call-api-prepare-tenant.md) |
active-directory | How To Daemon Node Call Api Prepare App | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-daemon-node-call-api-prepare-app.md | + + Title: Call an API in your Node.js daemon application - prepare client app and web API +description: Learn about how to prepare your Node.js client daemon app and ASP.NET web API. The app you here prepare is what you configure later to sign in users, then call the web API. +++++++++ Last updated : 05/22/2023++++# Call an API in your Node.js daemon application - prepare client app and web API ++In this article, you create app projects for both the client daemon app and web API. Later, you enable the client daemon app to acquire an access token using its own identity, then call the web API. ++## Prerequisite ++- Install [.NET SDK](https://dotnet.microsoft.com/learn/dotnet/hello-world-tutorial/install) v7 or later in your computer. ++## Build ASP.NET web API ++You must first create a protected web API, which the client daemon calls by presenting a valid token. To do so, complete the steps in [Secure an ASP.NET web API](how-to-protect-web-api-dotnet-core-overview.md) article. In this article, you learn how to create and protect ASP.NET API endpoints, and run and test the API. The web API checks both app and user permissions. However, in this article, the client app acquires an access token with only app permissions. ++Before you proceed, make sure you've [registered a web API app in Microsoft Entra admin center](how-to-daemon-node-call-api-prepare-tenant.md). ++## Prepare Node.js client web app ++In this step, you prepare the Node.js client web app that calls the ASP.NET web API. ++### Create the Node.js daemon project ++Create a folder to host your Node.js daemon application, such as `ciam-call-api-node-daemon`: ++1. In your terminal, change directory into your Node daemon app folder, such as `cd ciam-call-api-node-daemon`, then run `npm init -y`. This command creates a default package.json file for your Node.js project. This command creates a default `package.json` file for your Node.js project. ++1. Create more folders and files to achieve the following project structure: ++ ``` + ciam-call-api-node-daemon/ + Γö£ΓöÇΓöÇ auth.js + ΓööΓöÇΓöÇ authConfig.js + ΓööΓöÇΓöÇ fetch.js + ΓööΓöÇΓöÇ index.js + ΓööΓöÇΓöÇ package.json + ``` ++## Install app dependencies ++In your terminal, install `axios`, `yargs` and `@azure/msal-node` packages by running the following command: ++```console +npm install axios yargs @azure/msal-node +``` ++## Next steps ++Next, learn how to acquire an access token and call API: ++> [!div class="nextstepaction"] +> [Acquire an access token and call API >](how-to-daemon-node-call-api-call-api.md) |
active-directory | How To Daemon Node Call Api Prepare Tenant | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-daemon-node-call-api-prepare-tenant.md | + + Title: Call an API in your Node.js daemon application - prepare your tenant +description: Learn about how to prepare your Azure Active Directory (Azure AD) tenant for customers to acquire an access token using client credentials flow in your Node.js daemon application +++++++++ Last updated : 05/22/2023++++# Call an API in your Node.js daemon application - prepare your tenant ++In this article, you prepare your Azure Active Directory (Azure AD) for customers tenant for authorization. To prepare your tenant, you do the following tasks: ++- Register a web API and configure app permissions the Microsoft Entra admin center. ++- Register a client daemon application and grant it app permissions in the Microsoft Entra admin center. ++- Create a client secret for your daemon application in the Microsoft Entra admin center. ++After you complete the tasks, you collect: ++- *Application (client) ID* for your client daemon app and one for your web API. ++- A *Client secret* for your client daemon app. ++- A *Directory (tenant) ID* for your Azure AD for customers tenant. ++- App permissions/roles. ++If you've already registered a client daemon application and a web API in the Microsoft Entra admin center, you can skip the steps in this article, then proceed to [Prepare your daemon application and web API](how-to-daemon-node-call-api-prepare-app.md). ++## Register a web API application +++## Configure app roles +++## Configure optional claims +++## Register the daemon app +++## Create a client secret +++## Grant API permissions to the daemon app ++++## Next steps ++Next, learn how to prepare your daemon application and web API. ++> [!div class="nextstepaction"] +> [Prepare your daemon application and web API >](how-to-daemon-node-call-api-prepare-app.md) |
active-directory | How To Daemon Node Sample Call Api | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-daemon-node-sample-call-api.md | + + Title: Call an API in a sample Node.js daemon application +description: Learn how to configure a sample Node.js daemon application that calls an API protected Azure Active Directory (Azure AD) for customers +++++++++ Last updated : 05/22/2023+++#Customer intent: As a dev, devops, I want to configure a sample Node.js daemon application that calls an API protected by Azure Active Directory (Azure AD) for customers tenant +++# Call an API in a sample Node.js daemon application ++This article uses a sample Node.js daemon application to show you how a daemon app acquires a token to call a web API. Azure Active Directory (Azure AD) for customers protects the Web API. ++A daemon application acquires a token on behalf of itself (not on behalf of a user). Users can't interact with a daemon application because it requires its own identity. This type of application requests an access token by using its application identity and presenting its application ID, credential (password or certificate), and application ID URI to Azure AD. ++A daemon app uses the standard [OAuth 2.0 client credentials grant](../../develop/v2-oauth2-client-creds-grant-flow.md). To simplify the process of acquiring the token, the sample we use in this article uses [Microsoft Authentication Library for Node (MSAL Node)](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-node). +++## Prerequisites ++- [Node.js](https://nodejs.org). ++- [.NET 7.0](https://dotnet.microsoft.com/learn/dotnet/hello-world-tutorial/install) or later. ++- [Visual Studio Code](https://code.visualstudio.com/download) or another code editor. ++- Azure AD for customers tenant. If you don't already have one, [sign up for free trial](https://aka.ms/ciam-free-trial?wt.mc_id=ciamcustomertenantfreetrial_linkclick_content_cnl). ++## Register a daemon application and a web API ++In this step, you create the daemon and the web API application registrations, and you specify the scopes of your web API. ++### Register a web API application +++### Configure app roles +++### Configure optional claims +++### Register the daemon app +++### Create a client secret +++### Grant API permissions to the daemon app +++## Clone or download sample daemon application and web API ++To get the web app sample code, you can do either of the following tasks: ++- [Download the .zip file](https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial/archive/refs/heads/main.zip) or clone the sample web application from GitHub by running the following command: ++ ```console + git clone https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial.git + ``` +If you choose to download the *.zip* file, extract the sample app file to a folder where the total length of the path is 260 or fewer characters. ++## Install project dependencies ++1. Open a console window, and change to the directory that contains the Node.js sample app: ++ ```console + cd 2-Authorization\3-call-api-node-daemon\App + ``` +1. Run the following commands to install app dependencies: ++ ```console + npm install && npm update + ``` ++## Configure the sample daemon app and API ++To use your app registration in the client web app sample: ++1. In your code editor, open `App\authConfig.js` file. ++1. Find the placeholder: ++ - `Enter_the_Application_Id_Here` and replace it with the Application (client) ID of the daemon app you registered earlier. + + - `Enter_the_Tenant_Subdomain_Here` and replace it with the Directory (tenant) subdomain. For example, if your tenant primary domain is `contoso.onmicrosoft.com`, use `contoso`. If you don't have your tenant name, learn how to [read your tenant details](how-to-create-customer-tenant-portal.md#get-the-customer-tenant-details). + + - `Enter_the_Client_Secret_Here` and replace it with the daemon app secret value you copied earlier. + + - `Enter_the_Web_Api_Application_Id_Here` and replace it with the Application (client) ID of the web API you copied earlier. ++To use your app registration in the web API sample: ++1. In your code editor, open `API\ToDoListAPI\appsettings.json` file. ++1. Find the placeholder: + + - `Enter_the_Application_Id_Here` and replace it with the Application (client) ID of the web API you copied. + + - `Enter_the_Tenant_Id_Here` and replace it with the Directory (tenant) ID you copied earlier. + + - `Enter_the_Tenant_Subdomain_Here` and replace it with the Directory (tenant) subdomain. For example, if your tenant primary domain is `contoso.onmicrosoft.com`, use `contoso`. If you don't have your tenant name, learn how to [read your tenant details](how-to-create-customer-tenant-portal.md#get-the-customer-tenant-details). ++## Run and test sample daemon app and API ++1. Open a console window, then run the web API by using the following commands: ++ ```console + cd 2-Authorization\3-call-api-node-daemon\API\ToDoListAPI + dotnet run + ``` +1. Run the web app client by using the following commands: ++ ```console + 2-Authorization\3-call-api-node-daemon\App + node . --op getToDos + ``` ++If your daemon app and web API successfully run, you should see something similar to the following JSON array in your console window ++```json +{ + id: 1, + owner: '3e8....-db63-43a2-a767-5d7db...', + description: 'Pick up grocery' +}, +{ + id: 2, + owner: 'c3cc....-c4ec-4531-a197-cb919ed.....', + description: 'Finish invoice report' +}, +{ + id: 3, + owner: 'a35e....-3b8a-4632-8c4f-ffb840d.....', + description: 'Water plants' +} +``` ++### How it works ++The Node.js app uses [OAuth 2.0 client credentials grant](../../develop/v2-oauth2-client-creds-grant-flow.md) to acquire an access token for itself and not for the user. The access token that the app requests contains the permissions represented as roles. The client credential flow uses this set of permissions in place of user scopes for application tokens.You [exposed these application permissions](#configure-app-roles) in the web API earlier, then [granted them to the daemon app](#grant-api-permissions-to-the-daemon-app). ++On the API side, the web API must verify that the access token has the required permissions (application permissions). The web API can't accept an access token that doesn't have the required permissions. ++### Access to data ++A Web API endpoint should be prepared to accept calls from both users and applications. Therefore, it should have a way to respond to each request accordingly. For example, a call from a user via delegated permissions/scopes receives the user's data to-do list. On the other hand, a call from an application via application permissions/roles may receive the entire to-do list. However, in this article, we're only making an application call, so we didn't need to configure delegated permissions/scopes. ++## Next steps ++- Learn how to [Acquire an access token, then call a web API in your own Node.js daemon app](how-to-daemon-node-call-api-overview.md). ++- Learn how to [Use client certificate instead of a secret for authentication in your Node.js confidential app](how-to-web-app-node-use-certificate.md). ++- Learn about [permissions and consent](../../develop/permissions-consent-overview.md). |
active-directory | How To Define Custom Attributes | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-define-custom-attributes.md | + + Title: Define custom attributes +description: Learn how to create and define new custom attributes to be collected from users during sign-up and sign-in. +++++++ Last updated : 05/08/2023++++++# Collect user attributes during sign-up ++User attributes are values collected from the user during self-service sign-up. In the user flow settings, you can select from a set of *built-in user attributes* you want to collect from customers. The customer enters the information on the sign-up page, and it's stored with their profile in your directory. Azure AD provides the following built-in user attributes: ++ - City + - Country/Region + - Display Name + - Email Address + - Given Name + - Job Title + - Postal Code + - State/Province + - Street Address + - Surname ++If you want to collect information beyond the built-in attributes, you can create *custom user attributes* and add them to your sign-up user flow. Custom attributes are also known as directory extension attributes because they extend the user profile information stored in your customer directory. All extension attributes for your customer tenant are stored in an app named *b2c-extensions-app*. After a user enters a value for the custom attribute during sign-up, it's added to the user object and can be called via the Microsoft Graph API. ++If your application relies on certain built-in or custom user attributes, you can [include these attributes in the token](how-to-add-attributes-to-token.md) that is sent to your application. ++## Create custom attributes ++1. In the [Microsoft Entra admin center](https://entra.microsoft.com/), select **Azure Active Directory**. +1. Select **External Identities** > **Overview**. +1. Select **Custom user attributes**. The available user attributes are listed. +1. To add an attribute, select **Add**. +1. In the **Add an attribute** pane, enter the following values: ++ - **Name** - Provide a name for the custom attribute. For example, "Loyalty number". + - **Data Type** - Choose a data type, **String**, **Boolean**, or **Int**. + - **Description** - Optionally, enter a description of the custom attribute for internal use. This description isn't visible to the user. ++1. Select **Create**. The custom attribute is now available in the list of user attributes and can be added to your user flows. ++## Select attributes (built-in and custom) for sign-up ++1. Under **User attributes**, choose the attributes you want to collect from the user during sign-up. Select **Show more** to choose from the full list of attributes, including **Job Title**, **Display Name**, and **Postal Code**. This list also includes any custom attributes you defined. ++ :::image type="content" source="media/how-to-define-custom-attributes/user-attributes.png" alt-text="Screenshot of the user attribute options on the Create a user flow page."::: ++1. Select **OK**. ++1. Select **Create** to create the user flow. ++## Select the layout of the attribute collection page ++You can choose the order in which the attributes are displayed on the sign-up page. ++1. In the [Microsoft Entra admin center](https://entra.microsoft.com/), select **Azure Active Directory**. ++1. In the left pane, select **Azure Active Directory** > **External Identities** > **User flows**. ++1. From the list, select your user flow. ++1. Under **Customize**, select **Page layouts**. The attributes you chose to collect appear. ++ - To change the properties of an attribute, select a value under the **Label**, **Required**, or **Attribute type** columns, and then type or select a new value. ++ - To change the order of display, select an attribute, and then select **Move up**, **Move down**, **Move to the top**, or **Move to the bottom**. ++ :::image type="content" source="media/how-to-define-custom-attributes/page-layouts.png" alt-text="Screenshot of page layout options for a user flow."::: ++1. Select **Save**. ++1. Select **Create**. The new user flow appears in the user flows list. (You might need to refresh the page.) ++## Next steps ++[Add attributes to the ID token returned to your application](how-to-add-attributes-to-token.md) ++[Create a sign-up and sign-in user flow for customers](how-to-user-flow-sign-up-sign-in-customers.md) |
active-directory | How To Desktop App Electron Sample Sign In | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-desktop-app-electron-sample-sign-in.md | + + Title: Sign in users in a sample Electron desktop application. +description: Learn how to configure a sample Electron desktop to sign in and sign out users. +++++++++ Last updated : 05/22/2023+++#Customer intent: As a dev, devops, I want to learn about how to configure a sample Electron desktop app to sign in and sign out users with my Azure Active Directory (Azure AD) for customers tenant +++# Sign in users in a sample Electron desktop application by using ++This how-to guide uses a sample Electron desktop application to show how to add authentication to a desktop application. The sample application enables users to sign in and sign out. The sample web application uses [Microsoft Authentication Library (MSAL)](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-node) for Node to handle authentication. ++In this article, you do the following tasks: ++- Register a desktop application in the Microsoft Entra admin center. ++- Create a sign-in and sign-out user flow in Microsoft Entra admin center. ++- Associate your web application with the user flow. ++- Update a sample Electron desktop application using your own Azure Active Directory (Azure AD) for customers tenant details. ++- Run and test the sample desktop application. ++## Prerequisites ++- [Node.js](https://nodejs.org). ++- [Visual Studio Code](https://code.visualstudio.com/download) or another code editor. ++- Azure AD for customers tenant. If you don't already have one, [sign up for a free trial](https://aka.ms/ciam-free-trial?wt.mc_id=ciamcustomertenantfreetrial_linkclick_content_cnl). ++<!--Awaiting this link http://developer.microsoft.com/identity/customers to go live on Developer hub--> ++## Register desktop app +++## Grant API permissions +++## Configure optional claims ++ +## Create a user flow +++## Associate the web application with the user flow +++## Clone or download sample web application ++To get the desktop app sample code, [download the .zip file](https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial/archive/refs/heads/main.zip) or clone the sample web application from GitHub by running the following command: ++```powershell +git clone https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial.git +``` ++If you choose to download the `.zip` file, extract the sample app file to a folder where the total length of the path is 260 or fewer characters. ++## Install project dependencies ++1. Open a console window, and change to the directory that contains the Electron sample app: ++ ```powershell + cd 1-Authentication\3-sign-in-electron\App + ``` +1. Run the following commands to install app dependencies: ++ ```powershell + npm install && npm update + ``` ++## Configure the sample web app ++1. In your code editor, open `App\authConfig.js` file. ++1. Find the placeholder: + + 1. `Enter_the_Application_Id_Here` and replace it with the Application (client) ID of the app you registered earlier. ++ 1. `Enter_the_Tenant_Subdomain_Here` and replace it with the Directory (tenant) subdomain. For example, if your tenant primary domain is `contoso.onmicrosoft.com`, use `contoso`. If you don't have your tenant name, learn how to [read your tenant details](how-to-create-customer-tenant-portal.md#get-the-customer-tenant-details). ++## Run and test sample web app ++You can now test the sample Electron desktop app. After you run the app, the desktop app window appears automatically: ++1. In your terminal, run the following command: ++ ```powershell + npm start + ``` ++ :::image type="content" source="media/how-to-desktop-app-electron-sample-sign-in/desktop-app-electron-sign-in.png" alt-text="Screenshot of sign in into an electron desktop app."::: ++1. On the desktop window that appears, select the **Sign In** or **Sign up** button. A browser window opens, and you're prompted to sign in. ++1. On the browser sign-in page, type your **Email address**, select **Next**, type your **Password**, then select **Sign in**. If you don't have an account, select **No account? Create one** link, which starts the sign-up flow. ++1. If you choose the sign-up option, after filling in your email, one-time passcode, new password and more account details, you complete the whole sign-up flow. You see a page similar to the following screenshot. You see a similar page if you choose the sign-in option. The page displays token ID claims. ++ :::image type="content" source="media/how-to-desktop-app-electron-sample-sign-in/desktop-app-electron-view-claims.png" alt-text="Screenshot of view token claims in an electron desktop app."::: ++## Next steps ++- [Enable password reset](how-to-enable-password-reset-customers.md). ++- [Customize the default branding](how-to-customize-branding-customers.md). ++- [Configure sign-in with Google](how-to-google-federation-customers.md). ++- [Explore the Electron desktop app sample code](https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial/tree/main/1-Authentication/3-sign-in-electron#about-the-code). |
active-directory | How To Desktop App Maui Sample Sign In | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-desktop-app-maui-sample-sign-in.md | + + Title: Sign in users in a sample .NET MAUI desktop application +description: Learn how to configure a sample .NET MAUI desktop application to sign in and sign out users by using Azure AD for customers tenant. +++++++++ Last updated : 05/22/2023++#Customer intent: As a dev, devops, I want to learn about how to configure a sample .NET MAUI desktop app to sign in and sign out users with the Azure AD for customers tenant +++# Sign in users in a sample .NET MAUI desktop application ++This how-to guide uses a sample .NET Multi-platform App UI (.NET MAUI) to show how to add authentication to a desktop application by using Azure Active Directory (Azure AD) for customers tenant. The sample application enables users to sign in and sign out. The sample .NET MAUI desktop application uses [Microsoft Authentication Library (MSAL)](https://github.com/AzureAD/microsoft-authentication-library-for-dotnet) for .NET to handle authentication. ++In this article, you do the following tasks: ++- Register a .NET MAUI desktop application in the Azure AD for customers tenant. +- Create a sign-in and sign-out user flow in the Azure AD for customers tenant. +- Associate your .NET MAUI desktop application with the user flow. +- Update a sample .NET MAUI desktop application to use your own Azure AD for customers tenant details. +- Run and test the sample .NET MAUI desktop application. ++## Prerequisites ++- [Visual Studio Code](https://code.visualstudio.com/download) with the MAUI workload installed: + - [Instructions for Windows](/dotnet/maui/get-started/installation?tabs=vswin) + - [Instructions for macOS](/dotnet/maui/get-started/installation?tabs=vsmac) +- Azure AD for customers tenant. If you don't already have one, [sign up for a free trial](https://aka.ms/ciam-free-trial?wt.mc_id=ciamcustomertenantfreetrial_linkclick_content_cnl). ++## Register .NET MAUI desktop application +++## Grant API permissions +++## Create a user flow +++## Associate the .NET MAUI desktop application with the user flow +++## Clone or download sample .NET MAUI desktop application ++To get the .NET MAUI desktop application sample code, [download the .zip file](https://github.com/Azure-Samples/ms-identity-ciam-dotnet-tutorial/archive/refs/heads/main.zip) or clone the sample .NET MAUI desktop application from GitHub by running the following command: ++```bash +git clone https://github.com/Azure-Samples/ms-identity-ciam-dotnet-tutorial.git +``` ++## Configure the sample .NET MAUI desktop application ++1. In Visual Studio, open *ms-identity-ciam-dotnet-tutorial-main/1-Authentication/2-sign-in-maui/appsettings.json* file. +1. Find the placeholder: + 1. `Enter_the_Tenant_Subdomain_Here` and replace it with the Directory (tenant) subdomain. For example, if your tenant primary domain is `contoso.onmicrosoft.com`, use `contoso`. If you don't have your tenant name, learn how to [read your tenant details](how-to-create-customer-tenant-portal.md#get-the-customer-tenant-details). + 1. `Enter_the_Application_Id_Here` and replace it with the Application (client) ID of the app you registered earlier. ++## Run and test sample .NET MAUI desktop application ++Select the Windows platform to work on by setting the startup project in the **Solution Explorer**. Make sure that your platform of choice is marked for build and deploy in the configuration manager. ++Clean the solution, rebuild the solution, and run it. ++1. You can now test the sample .NET MAUI desktop application. After you run the application, the desktop application window appears automatically: ++ :::image type="content" source="media/how-to-desktop-app-maui-sample-sign-in/maui-desktop-sign-in-page.jpg" alt-text="Screenshot of the sign-in button in the desktop application"::: ++1. On the desktop window that appears, select the **Sign In** button. A browser window opens, and you're prompted to sign in. ++ :::image type="content" source="media/how-to-desktop-app-maui-sample-sign-in/maui-desktop-sign-in-prompt.jpg" alt-text="Screenshot of user prompt to enter credential in desktop application."::: ++ During the sign in process, you're prompted to grant various permissions (to allow the application to access your data). Upon successful sign in and consent, the application screen displays the main page. ++ :::image type="content" source="media/how-to-desktop-app-maui-sample-sign-in/maui-desktop-after-sign-in.png" alt-text="Screenshot of the main page in the desktop application after signing in."::: ++## Next Steps ++- [Customize the default branding](how-to-customize-branding-customers.md). +- [Configure sign-in with Google](how-to-google-federation-customers.md). |
active-directory | How To Enable Password Reset Customers | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-enable-password-reset-customers.md | + + Title: Enable self-service password reset +description: Learn how to enable self-service password reset so your customers can reset their own passwords without admin assistance. +++++++ Last updated : 05/09/2023++++#Customer intent: As an it admin, I want to enable self-service password reset so my customers can reset their own passwords without admin assistance. +++# Enable self-service password reset ++Self-service password reset (SSPR) in Azure Active Directory (Azure AD) for customers gives customers the ability to change or reset their password, with no administrator or help desk involvement. If a customer's account is locked or they forget their password, they can follow prompts to unblock themselves and get back to work. ++## How does the password reset process work? ++The self-service password uses the email one-time passcode (Email OTP) authentication. When enabled, customer users who forgot their passwords use Email OTP authentication. With one-time passcode authentication, users verify their identity by entering the one-time passcode sent to their email address, and are then prompted to change their password. ++The following screenshots show the self-service password rest flow. From the app, the customer chooses to sign-in. On the sign-in page, the user types their email and selects **Next**. If users forgot their password, they choose the **Forgot password?** option. Azure AD sends the passcode to email address provided on the first page. The customer needs to type the passcode to continue. +++## Prerequisites ++- If you haven't already created your own Azure AD customer tenant, create one now. +- If you haven't already created a User flow, [create one](how-to-user-flow-sign-up-sign-in-customers.md) now. ++## Enable self-service password reset for customers ++1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com/). +1. If you have access to multiple tenants, use the **Directories + subscriptions** filter in the top menu to switch to the customer tenant you created earlier. +1. In the navigation pane, select **Azure Active Directory**. +1. Select **External Identities** > **User flows**. +1. From the list of **User flows**, select the user flow you want to enable SSPR. +1. Make sure that the sign-up user flow registers **Email with password** as an authentication method under **Identity providers**. ++ :::image type="content" source="media/how-to-enable-password-reset-customers/email-authentication-method.png" alt-text="Screenshot that shows how to enable email authentication."::: ++### Enable email one-time passcode ++To enable self-service password reset, you need to enable the email one-time passcode (Email OTP) authentication method for all users in your tenant. To ensure that the Email OTP feature is enabled follow the steps below: ++ 1. Select **Protect & secure** from the sidebar under **Azure Active Directory** and then **Authentication methods** > **Policies**. ++ 1. Under **Method** select **Email OTP (preview)**. + + :::image type="content" source="media/how-to-enable-password-reset-customers/authentication-methods.png" alt-text="Screenshot that shows authentication methods."::: + + 1. Under **Enable and Target** enable Email OTP and select **All users** under **Include**. + + :::image type="content" source="media/how-to-enable-password-reset-customers/enable-otp.png" alt-text="Screenshot of enabling OTP."::: ++1. Select **Save**. ++## Customize the password reset flow ++You can configure options for showing, hiding, or customizing the self-service password reset link on the sign-in page. For details, see [To customize self-service password reset](how-to-customize-branding-customers.md#to-customize-self-service-password-reset) in the article [Customize the neutral branding in your customer tenant](how-to-customize-branding-customers.md). ++## Test self-service password reset ++To go through the self-service password reset flow: ++1. Open your application, and select **Sign-in**. ++1. In the sign-in page, enter your **Email address** and select **Next**. + + :::image type="content" source="media/how-to-enable-password-reset-customers/sign-in.png" alt-text="Screenshot that shows the sign-in page."::: + +1. Select the **Forgot password?** link. ++ :::image type="content" source="media/how-to-enable-password-reset-customers/forgot-password.png" alt-text="Screenshot that shows the forgot password link."::: ++1. Enter the one-time passcode sent to your email address. ++ :::image type="content" source="media/how-to-enable-password-reset-customers/enter-code.png" alt-text="Screenshot that shows the enter code option."::: ++1. Once you're authenticated, you're prompted to enter a new password. Provide a **New password**, and **Confirm password**, then select **Reset password** to sign in to your application. ++ :::image type="content" source="media/how-to-enable-password-reset-customers/update-password.png" alt-text="Screenshot that shows the update password screen."::: ++## Next steps ++- Add [Google](how-to-google-federation-customers.md) or [Facebook](how-to-facebook-federation-customers.md) federation. |
active-directory | How To Facebook Federation Customers | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-facebook-federation-customers.md | + + Title: Add Facebook for customer sign-in +description: Learn how to add Facebook as an identity provider for your customer tenant. +++++++ Last updated : 04/28/2023++++#Customer intent: As a dev, devops, or it admin, I want to +++# Add Facebook as an identity provider ++By setting up federation with Facebook, you can allow customers to sign in to your applications with their own Facebook accounts. After you've added Facebook as one of your application's sign-in options, on the sign-in page, customers can sign-in to Azure AD for customers with a Facebook account. (Learn more about [authentication methods and identity providers for customers](concept-authentication-methods-customers.md).) ++## Create a Facebook application ++To enable sign-in for customers with a Facebook account, you need to create an application in [Facebook App Dashboard](https://developers.facebook.com/). For more information, see [App Development](https://developers.facebook.com/docs/development). ++If you don't already have a Facebook account, sign up at [https://www.facebook.com](https://www.facebook.com). After you sign-up or sign-in with your Facebook account, start the [Facebook developer account registration process](https://developers.facebook.com/async/registration). For more information, see [Register as a Facebook Developer](https://developers.facebook.com/docs/development/register). ++1. Sign in to [Facebook for developers](https://developers.facebook.com/apps) with your Facebook developer account credentials. +1. If you haven't already done so, register as a Facebook developer: Select **Get Started** in the upper-right corner of the page, accept Facebook's policies, and complete the registration steps. +1. Select **Create App**. +1. For **Select an app type**, select **customers**, then select **Next**. +1. Enter an **App Display Name** and a valid **App Contact Email**. +1. Select **Create App**. This step may require you to accept Facebook platform policies and complete an online security check. +1. Select **Settings** > **Basic**. + 1. Copy the value of **App ID**. + 1. Select **Show** and copy the value of **App Secret**. You use both of them to configure Facebook as an identity provider in your tenant. **App Secret** is an important security credential. + 1. Enter a URL for the **Privacy Policy URL**, for example `https://www.contoso.com/privacy`. The policy URL is a page you maintain to provide privacy information for your application. + 1. Enter a URL for the **Terms of Service URL**, for example `https://www.contoso.com/tos`. The policy URL is a page you maintain to provide terms and conditions for your application. + 1. Enter a URL for the **User Data Deletion**, for example `https://www.contoso.com/delete_my_data`. The User Data Deletion URL is a page you maintain to provide away for users to request that their data be deleted. + 1. Choose a **Category**, for example `Business and Pages`. Facebook requires this value, but it's not used for Azure AD. +2. At the bottom of the page, select **Add Platform**, and then select **Website**. +3. In **Site URL**, enter the address of your website, for example `https://contoso.com`. +4. Select **Save Changes**. +5. From the menu, select the **plus** sign or **Add Product** link next to **PRODUCTS**. Under the **Add Products to Your App**, select **Set up** under **Facebook Login**. +6. From the menu, select **Facebook Login**, select **Settings**. +7. In **Valid OAuth redirect URIs**, enter: + - `https://login.microsoftonline.com` + - `https://login.microsoftonline.com/te/<tenant ID>/oauth2/authresp`. Replace the tenant ID with your Azure AD for customers tenant ID. To find your tenant ID, go to the [Microsoft Entra admin center](https://entra.microsoft.com). Under **Azure Active Directory**, select **Overview**. Then select the **Overview** tab and copy the **Tenant ID**. + - `https://login.microsoftonline.com/te/<tenant name>.onmicrosoft.com/oauth2/authresp`. Replace the tenant name with your Azure AD for customers tenant name. +8. Select **Save Changes** at the bottom of the page. +9. To make your Facebook application available to Azure AD, select the Status selector at the top right of the page and turn it **On** to make the Application public, and then select **Switch Mode**. At this point, the Status should change from **Development** to **Live**. For more information, see [Facebook App Development](https://developers.facebook.com/docs/development/release). ++## Configure Facebook federation in Azure AD for customers ++After you create the Facebook application, in this step you set the Facebook client ID and client secret in Azure AD. You can use the Azure portal or PowerShell to do so. To configure Facebook federation in the Microsoft Entra admin center, follow these steps: ++1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com/) as the global administrator of your customer tenant. +1. Go to **Azure Active Directory** > **External Identities** > **All identity providers**. +2. Select **+ Facebook**. ++ <!-- --> ++1. Enter a **Name**. For example, *Facebook*. +1. For the **Client ID**, enter the Client ID of the Facebook application that you created earlier. +1. For the **Client secret**, enter the Client Secret that you recorded. +1. Select **Save**. ++To configure Facebook federation by using PowerShell, follow these steps: ++1. Install the latest version of the Azure AD PowerShell for Graph module ([AzureADPreview](https://www.powershellgallery.com/packages/AzureADPreview)). +1. Run the following command: `Connect-AzureAD` +1. At the sign-in prompt, sign in with the managed Global Administrator account. +1. Run the following command: + + `New-AzureADMSIdentityProvider -Type Facebook -Name Facebook -ClientId <client ID> -ClientSecret <client secret>` ++ Use the client ID and client secret from the app you created in [Create a Facebook application](#create-a-facebook-application) step. ++## Add Facebook identity provider to a user flow ++At this point, the Facebook identity provider has been set up in your customer tenant, but it's not yet available in any of the sign-in pages. To add the Facebook identity provider to a user flow: ++1. In your customer tenant, go to **Azure Active Directory** > **External Identities** > **User flows**. +1. Select the user flow where you want to add the Facebook identity provider. +1. Under Settings, select **Identity providers** +1. Under **Other Identity Providers**, select **Facebook**. ++ <!-- --> ++1. At the top of the pane, select **Save**. ++## Next steps ++- [Add Google as an identity provider](how-to-google-federation-customers.md) +- [Customize the branding for customer sign-in experiences](how-to-customize-branding-customers.md) |
active-directory | How To Google Federation Customers | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-google-federation-customers.md | + + Title: Add Google as an identity provider +description: Learn how to add Google as an identity provider for your customer tenant. +++++++ Last updated : 04/28/2023++++#Customer intent: As a dev, devops, or it admin, I want to +++# Add Google as an identity provider ++By setting up federation with Google, you can allow customers to sign in to your applications with their own Gmail accounts. After you've added Google as one of your application's sign-in options, on the sign-in page, customers can sign in to Azure AD for customers with a Google account. (Learn more about [authentication methods and identity providers for customers](concept-authentication-methods-customers.md).) ++## Create a Google application ++To enable sign-in for customers with a Google account, you need to create an application in [Google Developers Console](https://console.developers.google.com/). For more information, see [Setting up OAuth 2.0](https://support.google.com/googleapi/answer/6158849). If you don't already have a Google account, you can sign up at [`https://accounts.google.com/signup`](https://accounts.google.com/signup). ++1. Sign in to the [Google Developers Console](https://console.developers.google.com/) with your Google account credentials. +1. Accept the terms of service if you're prompted to do so. +1. In the upper-left corner of the page, select the project list, and then select **New Project**. +1. Enter a **Project Name**, select **Create**. +1. Make sure you're using the new project by selecting the project drop-down in the top-left of the screen. Select your project by name, then select **Open**. +1. Under the **Quick access**, or in the left menu, select **APIs & services** and then **OAuth consent screen**. +1. For the **User Type**, select **External** and then select **Create**. +1. On the **OAuth consent screen**, under **App information** + 1. Enter a **Name** for your application. + 2. Select a **User support email** address. +1. Under the **Authorized domains** section, select **Add domain**, and then type *microsoftonline.com*. +1. In the **Developer contact information** section, enter comma separated emails for Google to notify you about any changes to your project. +1. Select **Save and Continue**. +1. From the left menu, select **Credentials** +1. Select **Create credentials**, and then **OAuth client ID**. +1. Under **Application type**, select **Web application**. + 1. Enter a suitable **Name** for your application, such as "Azure AD for customers." + 1. For the **Authorized redirect URIs**, enter: + - `https://login.microsoftonline.com` + - `https://login.microsoftonline.com/te/<tenant ID>/oauth2/authresp`. Replace the tenant ID with your Azure AD for customers tenant ID. To find your tenant ID, go to the [Microsoft Entra admin center](https://entra.microsoft.com). Under **Azure Active Directory**, select **Overview**. Then select the **Overview** tab and copy the **Tenant ID**. + - `https://login.microsoftonline.com/te/<tenant name>.onmicrosoft.com/oauth2/authresp`. Replace the tenant name with your Azure AD for customers tenant name. +1. Select **Create**. +1. Copy the values of **Client ID** and **Client secret**. You need both values to configure Google as an identity provider in your tenant. **Client secret** is an important security credential. ++> [!NOTE] +> In some cases, your app might require verification by Google (for example, if you update the application logo). For more information, check out the [Google's verification status guid](https://support.google.com/cloud/answer/10311615#verification-status). ++## Configure Google federation in Azure AD for customers ++After you create the Google application, in this step you set the Google client ID and client secret in Azure AD. You can use the Microsoft Entra admin center or PowerShell to do so. To configure Google federation in the Microsoft Entra admin center, follow these steps: ++1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com/) as the global administrator of your customer tenant. +1. Go to **Azure Active Directory** > **External Identities** > **All identity providers**. +2. Select **+ Google**. ++ <!-- --> ++1. Enter a **Name**. For example, *Google*. +1. For the **Client ID**, enter the Client ID of the Google application that you created earlier. +1. For the **Client secret**, enter the Client Secret that you recorded. +1. Select **Save**. ++To configure Google federation by using PowerShell, follow these steps: ++1. Install the latest version of the Azure AD PowerShell for Graph module ([AzureADPreview](https://www.powershellgallery.com/packages/AzureADPreview)). +1. Run the following command: `Connect-AzureAD` +1. At the sign-in prompt, sign in with the managed Global Administrator account. +1. Run the following command: + + `New-AzureADMSIdentityProvider -Type Google -Name Google -ClientId <client ID> -ClientSecret <client secret>` ++ Use the client ID and client secret from the app you created in [Create a Google application](#create-a-google-application) step. +++## Add Google identity provider to a user flow ++At this point, the Google identity provider has been set up in your Azure AD, but it's not yet available in any of the sign-in pages. To add the Google identity provider to a user flow: ++1. In your customer tenant, go to **Azure Active Directory** > **External Identities** > **User flows**. +1. Select the user flow where you want to add the Facebook identity provider. +1. Under Settings, select **Identity providers** +1. Under **Other Identity Providers**, select **Google**. ++ <!-- --> ++1. Select **Save**. ++## Next steps ++- [Add Facebook as an identity provider](how-to-facebook-federation-customers.md) +- [Customize the branding for customer sign-in experiences](how-to-customize-branding-customers.md) |
active-directory | How To Identity Protection Customers | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-identity-protection-customers.md | + + Title: Identity Protection for a customer app +description: Learn how to add Identity Protection to your customer-facing (CIAM) application to provide ongoing risk detection. +++++++ Last updated : 04/27/2023+++++# Investigate risk with Identity Protection in Azure AD for customers ++Azure AD [Identity Protection](../../identity-protection/overview-identity-protection.md) provides ongoing risk detection for your customer tenant. It allows organizations to discover, investigate, and remediate identity-based risks. Identity Protection comes with risk reports that can be used to investigate identity risks in customer tenants. In this article, you learn how to investigate and mitigate risks. ++## Identity Protection reporting ++Identity Protection provides two reports. The *Risky users* report is where administrators can find which users are at risk and details about detections. The *risk detections* report gives information about each risk detection. This report includes the risk type, other risks triggered at the same time, the location of the sign-in attempt, and more. ++Each report launches with a list of all detections for the period shown at the top of the report. Reports can be filtered using the filters across the top of the report. Administrators can choose to download the data, or use [MS Graph API and Microsoft Graph PowerShell SDK](../../identity-protection/howto-identity-protection-graph-api.md) to continuously export the data. ++## Service limitations and considerations ++Consider the following points when using Identity Protection: ++- Identity Protection is not available in trial tenants. +- Identity Protection is on by default. +- Identity Protection is available for both local and social identities, such as Google or Facebook. Detection is limited because the external identity provider manages the social account credentials. +- Currently in Azure AD customer tenants, a subset of the [Azure AD Identity Protection risk detections](../../identity-protection/overview-identity-protection.md) is available. Azure AD for customers supports the following risk detections: ++|Risk detection type |Description | +||| +| Atypical travel | Sign-in from an atypical location based on the user's recent sign-ins. | +|Anonymous IP address | Sign-in from an anonymous IP address (for example: Tor browser, anonymizer VPNs). | +|Malware linked IP address | Sign-in from a malware linked IP address. | +|Unfamiliar sign-in properties | Sign-in with properties we haven't seen recently for the given user. | +|Admin confirmed user compromised | An admin has indicated that a user was compromised. | +|Password spray | Sign-in through a password spray attack. | +|Azure AD threat intelligence | Microsoft's internal and external threat intelligence sources have identified a known attack pattern. | ++## Investigate risky users ++With the information provided by the **Risky users** report, administrators can find: ++- The **Risk state**, showing which users are **At risk**, have had risk **Remediated**, or have had risk **Dismissed** +- Details about detections +- History of all risky sign-ins +- Risk history + +Administrators can then choose to take action on these events. Administrators can choose to: ++- Reset the user password +- Confirm user compromise +- Dismiss user risk +- Block user from signing in +- Investigate further using Azure ATP ++An administrator can choose to dismiss a user's risk in the Microsoft Entra admin center or programmatically through the Microsoft Graph API [Dismiss User Risk](/graph/api/riskyusers-dismiss?preserve-view=true&view=graph-rest-beta). Administrator privileges are required to dismiss a user's risk. The risky user or an administrator working on the user's behalf can remediate the risk, for example through a password reset. ++### Navigating the risky users report ++1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com). ++1. Make sure you're using the directory that contains your Azure AD customer tenant: Select the Directories + subscriptions icon  in the toolbar and find your customer tenant in the list. If it's not the current directory, select **Switch**. ++1. Browse to **Azure Active Directory** > **Protect & secure** > **Security Center**. ++1. Select **Identity Protection**. ++1. Under **Report**, select **Risky users**. ++ Selecting individual entries expands a details window below the detections. The details view allows administrators to investigate and perform actions on each detection. ++## Risk detections report ++The **Risk detections** report contains filterable data for up to the past 90 days (three months). ++With the information provided by the risk detections report, administrators can find: ++- Information about each risk detection including type. +- Other risks triggered at the same time. +- Sign-in attempt location. ++Administrators can then choose to return to the user's risk or sign-ins report to take actions based on information gathered. ++### Navigating the risk detections report ++1. In the [Microsoft Entra admin center](https://entra.microsoft.com), browse to **Azure Active Directory** > **Protect & secure** > **Security Center**. ++1. Select **Identity Protection**. ++1. Under **Report**, select **Risk detections**. |
active-directory | How To Manage Admin Accounts | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-manage-admin-accounts.md | + + Title: Add and manage admin accounts +description: Learn how to add and manage admin accounts in your customer tenant with Microsoft Entra for customers. +++++++ Last updated : 03/09/2023+++++# Add and manage admin accounts ++In Azure Active Directory (Azure AD) for customers, a customer tenant represents your directory of consumer and guest accounts. With an administrator role, work and guest accounts can manage the tenant. ++## Prerequisites ++- If you haven't already created your own Azure AD customer tenant, create one now. <!--(how-to-create-customer-tenant-portal.md)--> +- Understand user accounts in Azure AD for customers. +- Understand user roles to control resource access. ++## Add an admin account ++To create a new admin account, follow these steps: ++1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com/) with Global Administrator or Privileged Role Administrator permissions. +1. Make sure you're using your customer tenant. Select the **Directories + subscriptions** icon in the toolbar. +1. On the **Portal settings | Directories + subscriptions** page, find your customer tenant in the **Directory name** list, and then select **Switch**. +1. Under **Azure Active Directory**, select **Users** > **All users**. +1. Select **New user** > **Create new user**. +1. Enter information for this admin: + + - **User name**. *Required*. The user name of the new user. For example, `mary@contoso.com`. + - **Name**. *Required*. The first and last name of the new user. For example, *Mary Parker*. + - **First name**. The first name of the new user. For example, *Mary*. + - **Last name**. The last name of the new user. For example, *Parker*. + - **Groups**. *Optional*. You can add the user to one or more existing groups. You can also add the user to groups at a later time. + - **Roles**: To add administrative permissions for the user, add them to an Azure AD role. You can assign the user to be a Global administrator or one or more of the limited administrator roles in Azure AD. + - **Settings**: Use the yes or no toggle to set **Block sign in**, and the select the admin's primary location in the **Usage location** list. + - **Job info**: You can add more information about the user here, or do it later. ++1. Copy the autogenerated password provided in the **Password** box. You'll need to give this password to the admin to sign in for the first time. +1. Select **Create**. ++The admin is created and added to your customer tenant. It's preferable to have at least one admin account native to your customer tenant assigned the Global Administrator role. This account can be considered a *break-glass account* or *emergency access account*. ++## Invite an admin (guest account) ++You can also invite a new guest user to manage your tenant. To invite an admin, follow these steps: ++1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com/) with Global Administrator or Privileged Role Administrator permissions. +1. Make sure you're using your customer tenant. Select the **Directories + subscriptions** icon in the toolbar. +1. On the **Portal settings | Directories + subscriptions** page, find your customer tenant in the **Directory name** list, and then select **Switch**. +1. Under **Azure Active Directory**, select **Users** > **All users**. +1. Select **New user** > **Invite external user**. +1. On the **New user** page, enter information for the admin: ++ - **Name**. *Required*. The first and last name of the new user. For example, *Mary Parker*. + - **Email address**. *Required*. The email address of the user you would like to invite. + - **Personal message**: You add a personal message that will be included in the invite email. + - **Groups**. *Optional*. You can add the user to one or more existing groups. You can also add the user to groups at a later time. + - **Roles**: To add administrative permissions for the user, add them to an Azure AD role. You can assign the user to be a Global administrator or one or more of the limited administrator roles in Azure AD. + - **Settings**: Use the yes or no toggle to set **Block sign in**, and the select the admin's primary location in the **Usage location** list. + - **Job info**: You can add more information about the user here, or do it later. ++1. Select **Invite**. ++An invitation email is sent to the user. The user needs to accept the invitation to be able to sign in. ++## Add a role assignment ++You can assign a role when you create a user or invite a guest user. You can add a role, change the role, or remove a role for a user: ++1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com/) with Global Administrator or Privileged Role Administrator permissions. +1. Make sure you're using your customer tenant. Select the **Directories + subscriptions** icon in the toolbar. +1. On the **Portal settings | Directories + subscriptions** page, find your customer tenant in the **Directory name** list, and then select **Switch**. +1. Under **Azure Active Directory**, select **Users** > **All users**. +1. Select the user you want to change the roles for. Then select **Assigned roles**. +1. Select **Add assignments**, select the role to assign (for example, *Application administrator*), and then choose **Add**. ++## Remove a role assignment ++If you need to remove a role assignment from a user, follow these steps: ++1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com/) with Global Administrator or Privileged Role Administrator permissions. +1. Make sure you're using your customer tenant. Select the **Directories + subscriptions** icon in the toolbar. +1. On the **Portal settings | Directories + subscriptions** page, find your customer tenant in the **Directory name** list, and then select **Switch**. +1. Under **Azure Active Directory**, select **Users** > **All users**. +1. Select the user you want to change the roles for. Then select **Assigned roles**. +1. Select the role you want to remove, for example *Application administrator*, and then select **Remove assignment**. ++## Review administrator account role assignments ++As part of an auditing process, you typically review which users are assigned to specific roles in your customer directory. Use the following steps to audit which users are currently assigned privileged roles. ++1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com/) with Global Administrator or Privileged Role Administrator permissions. +1. Make sure you're using your customer tenant. Select the **Directories + subscriptions** icon in the toolbar. +1. On the **Portal settings | Directories + subscriptions** page, find your customer tenant in the **Directory name** list, and then select **Switch**. +1. Under **Azure Active Directory**, select **Roles & admins** > **Roles & admins**. +2. Select a role, such as **Global administrator**. The **Assignments** page lists the users with that role. ++## Delete an administrator account ++To delete an existing user, you must have a *Global administrator* role assignment. Global admins can delete any user, including other admins. *User administrators* can delete any non-admin user. ++1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com/) with Global Administrator or Privileged Role Administrator permissions. +1. Make sure you're using your customer tenant. Select the **Directories + subscriptions** icon in the toolbar. +1. On the **Portal settings | Directories + subscriptions** page, find your customer tenant in the **Directory name** list, and then select **Switch**. +1. Under **Azure Active Directory**, select **Users** > **All users**. +1. Select the user you want to delete. +1. Select **Delete**, and then **Yes** to confirm the deletion. ++The user is deleted and no longer appears on the **All users** page. The user can be seen on the **Deleted users** page for the next 30 days and can be restored during that time. For more information about restoring a user, see [Restore or remove a recently deleted user using Azure AD](../../fundamentals/active-directory-users-restore.md). ++## Protect administrative accounts ++It's recommended that you protect all administrator accounts with multifactor authentication (MFA) for more security. MFA is an identity verification process during sign in that prompts the user for a one-time passcode. |
active-directory | How To Manage Customer Accounts | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-manage-customer-accounts.md | + + Title: Add and manage customer accounts +description: Learn how to add and manage customer accounts in Microsoft Entra for customers. +++++++ Last updated : 03/09/2023+++++# Add and manage customer accounts ++There might be scenarios in which you want to manually create customer accounts in your Azure Active Directory customer tenant. Although customer accounts are most commonly created when users sign up to use one of your applications, you can create them programmatically and by using the Microsoft Entra admin center. This article focuses on the Microsoft Entra admin center method of user creation and deletion. ++To add or delete users, your account must be assigned the *User administrator* or *Global administrator* role. ++## Prerequisites ++- If you haven't already created your own Azure AD customer tenant, create one now. +- Understand user accounts in Azure AD for customers. +- Understand user roles to control resource access. ++## Create a customer account ++1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com/) with Global Administrator or Privileged Role Administrator permissions. +1. Make sure you're using your customer tenant. Select the **Directories + subscriptions** icon in the toolbar. +1. On the **Portal settings | Directories + subscriptions** page, find your customer tenant in the **Directory name** list, and then select **Switch**. +1. Under **Azure Active Directory**, select **Users** > **All users**. +1. Select **New user** > **Create new user**. +1. Select **Create a customer**. +1. Under **Identity**, select a **Sign in method** and enter the **Value**: + - **Email**: Enter the customer's email address, which will become their sign-in name. + - **User Name**: Enter a user name for the customer. +1. Next to **Name** (required), enter the first and last name of the customer (for example, *Mary Parker*). +1. Under **Settings**, use the yes or no toggle to set **Block sign in**, and the select the user's primary location in the **Usage location** list. Then enter the customer's **First name** and **Last name**. +1. Copy the autogenerated password provided in the **Password** box. Give this password to the user to sign in for the first time. +1. Select **Create**. ++Unless you've selected **Block sign in**, the user can now sign in using the sign in method (email or username) that you specified. ++## Reset a customer's password ++As an administrator, you can reset a user's password, if the user forgets their password. When you reset the user's password, a temporary password is autogenerated for the user. The temporary password never expires. The next time the user signs in, the password will still work, regardless how much time has passed since the temporary password was generated. Then user must reset password to a permanent one. ++To reset a customer's password: ++1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com/) with Global Administrator or Privileged Role Administrator permissions. +1. Make sure you're using your customer tenant. Select the **Directories + subscriptions** icon in the toolbar. +1. On the **Portal settings | Directories + subscriptions** page, find your customer tenant in the **Directory name** list, and then select **Switch**. +1. Under **Azure Active Directory**, select **Users** > **All users**. +1. Search for and select the user that needs the reset, and then select **Reset Password**. +1. In the **Reset password** page, select **Reset password**. +1. Copy the password and give it to the user. The user will be required to change the password during the next sign-in process. ++## Delete a customer account ++1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com/) with Global Administrator or Privileged Role Administrator permissions. +1. Make sure you're using your customer tenant. Select the **Directories + subscriptions** icon in the toolbar. +1. On the **Portal settings | Directories + subscriptions** page, find your customer tenant in the **Directory name** list, and then select **Switch**. +1. Under **Azure Active Directory**, select **Users** > **All users**. +1. Search for and select the user to delete. +1. Select **Delete**, and then **Yes** to confirm the deletion. ++For details about restoring a user within the first 30 days after deletion, or for permanently deleting a user, see [Restore or remove a recently deleted user using Azure Active Directory](../../fundamentals/active-directory-users-restore.md). |
active-directory | How To Mobile App Maui Sample Sign In | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-mobile-app-maui-sample-sign-in.md | + + Title: Sign in users in a sample .NET MAUI mobile application by using Azure AD for customers tenant +description: Learn how to configure a sample .NET MAUI mobile to sign in and sign out users by using Azure AD for customers tenant. +++++++++ Last updated : 05/22/2023++#Customer intent: As a dev, devops, I want to learn about how to configure a sample .NET MAUI mobile app to sign in and sign out users with Azure AD for customers tenant +++# Sign in users in a sample .NET MAUI Android application ++This how-to guide uses a sample .NET Multi-platform App UI (.NET MAUI) to show how to add authentication to an Android application by using Azure Active Directory (Azure AD) for customers tenant. The sample application enables users to sign in and sign out. The sample .NET MAUI Android application uses [Microsoft Authentication Library (MSAL)](https://github.com/AzureAD/microsoft-authentication-library-for-dotnet) for .NET to handle authentication. ++In this article, you do the following tasks: ++- Register a .NET MAUI Android application in the Azure AD for customers tenant. +- Create a sign-in and sign-out user flow in the Azure AD for customers tenant. +- Associate your .NET MAUI Android application with the user flow. +- Update a sample .NET MAUI Android application to use your own Azure AD for customers tenant details. +- Run and test the sample .NET MAUI Android application. ++## Prerequisites ++- [Visual Studio Code](https://code.visualstudio.com/download) with the MAUI workload installed: + - [Instructions for Windows](/dotnet/maui/get-started/installation?tabs=vswin) + - [Instructions for macOS](/dotnet/maui/get-started/installation?tabs=vsmac) +- Azure AD for customers tenant. If you don't already have one, [sign up for a free trial](https://aka.ms/ciam-free-trial?wt.mc_id=ciamcustomertenantfreetrial_linkclick_content_cnl). ++## Register .NET MAUI Android application +++## Grant API permissions +++## Create a user flow +++## Associate the .NET MAUI Android application with the user flow +++## Clone or download sample .NET MAUI Android application ++To get the .NET MAUI Android application sample code, [download the .zip file](https://github.com/Azure-Samples/ms-identity-ciam-dotnet-tutorial/archive/refs/heads/main.zip) or clone the sample .NET MAUI Android application from GitHub by running the following command: ++```bash +git clone https://github.com/Azure-Samples/ms-identity-ciam-dotnet-tutorial.git +``` ++## Configure the sample .NET MAUI Android application ++1. In Visual Studio, open *ms-identity-ciam-dotnet-tutorial-main/1-Authentication/2-sign-in-maui/appsettings.json* file. +1. Find the placeholder: + 1. `Enter_the_Tenant_Subdomain_Here` and replace it with the Directory (tenant) subdomain. For example, if your tenant primary domain is `contoso.onmicrosoft.com`, use `contoso`. If you don't have your tenant name, learn how to [read your tenant details](how-to-create-customer-tenant-portal.md#get-the-customer-tenant-details). + 1. `Enter_the_Application_Id_Here` and replace it with the **Application (client) ID** of the app you registered earlier. +1. In Visual Studio, open *ms-identity-ciam-dotnet-tutorial-main/1-Authentication/2-sign-in-maui/Platforms/Android/AndroidManifest.xml* file. +1. Find the placeholder: + 1. `Enter_the_Application_Id_Here` and replace it with the **Application (client) ID** of the app you registered earlier. ++## Run and test sample .NET MAUI Android application ++Select the Android platform to work on by setting the startup project in the **Solution Explorer**. Make sure that your platform of choice is marked for build and deploy in the configuration manager. ++Clean the solution, rebuild the solution, and run it. ++1. You can now test the sample .NET MAUI Android app. After you run the app, the Android app window appears in an emulator: ++ :::image type="content" source="media/how-to-mobile-app-maui-sample-sign-in/maui-android-sign-in.jpg" alt-text="Screenshot of the sign-in button in the Android application."::: ++1. On the Android window that appears, select the **Sign In** button. A browser window opens, and you're prompted to sign in. ++ :::image type="content" source="media/how-to-mobile-app-maui-sample-sign-in/maui-android-sign-in-prompt.jpg" alt-text="Screenshot of user prompt to enter credential in Android application."::: ++ During the sign in process, you're prompted to grant various permissions (to allow the application to access your data). Upon successful sign in and consent, the application screen displays the main page. ++ :::image type="content" source="media/how-to-mobile-app-maui-sample-sign-in/maui-android-after-sign-in.png" alt-text="Screenshot of the main page in the Android application after signing in."::: ++## Next Steps ++- [Customize the default branding](how-to-customize-branding-customers.md). +- [Configure sign-in with Google](how-to-google-federation-customers.md). |
active-directory | How To Multifactor Authentication Customers | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-multifactor-authentication-customers.md | + + Title: Add multifactor authentication (MFA) to a customer app +description: Learn how to add multifactor authentication (MFA) to your customer-facing (CIAM) application. For example, add email one-time passcode as a second authentication factor to your CIAM sign-up and sign-in user flows. +++++++ Last updated : 05/09/2023++++#Customer intent: As a dev, devops, or it admin, I want to add multifactor authentication to my customer-facing app. +++# Add multifactor authentication (MFA) to a customer-facing app ++[Multifactor authentication](../../authentication/concept-mfa-howitworks.md) (MFA) adds a layer of security to your customer-facing applications. With MFA, customers who sign in with a username and password are prompted for a one-time passcode as a second verification method. This article describes how to enforce MFA for your customers by creating an Azure AD Conditional Access policy and adding MFA to your sign-up and sign-in user flow. ++> [!NOTE] +> If you want to enable MFA, set your local account authentication method to **Email with password**. If you set your local account option to **Email with one-time passcode**, customers who use this method won't be able to sign in because the one-time passcode is already their first-factor sign-in method and can't be used as a second factor. Currently, one-time passcode is the only method available for MFA in customer tenants. ++## Prerequisites ++- An Azure AD customer tenant (if you don't have a tenant, you can start a [free trial](https://aka.ms/ciam-free-trial?wt.mc_id=ciamcustomertenantfreetrial_linkclick_content_cnl)). +- A [sign-up and sign-in user flow](how-to-user-flow-sign-up-sign-in-customers.md). +- An app that's registered in your customer tenant, added to the sign-up and sign-in user flow, and updated to point to the user flow for authentication. +- An account with Conditional Access Administrator, Security Administrator, or Global Administrator privileges to configure Conditional Access policies and MFA. ++## Create a Conditional Access policy ++Create a Conditional Access policy in your customer tenant that prompts users for MFA when they sign up or sign in to your app. (For more information, see [Common Conditional Access policy: Require MFA for all users](../../conditional-access/howto-conditional-access-policy-all-users-mfa.md)). ++1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com) as a Conditional Access Administrator, Security Administrator, or Global Administrator. ++1. Make sure you're using the directory that contains your Azure AD customer tenant: Select the Directories + subscriptions icon  in the toolbar and find your customer tenant in the list. If it's not the current directory, select **Switch**. ++1. Browse to **Azure Active Directory** > **Protect & secure** > **Security Center**. ++1. Select **Conditional Access** > **Policies**, and then select **New policy**. ++ :::image type="content" source="media/how-to-multifactor-authentication-customers/new-policy.png" alt-text="Screenshot of the new policy button." lightbox="media/how-to-multifactor-authentication-customers/new-policy.png"::: ++1. Give your policy a name. We recommend that organizations create a meaningful standard for the names of their policies. ++1. Under **Assignments**, select the link under **Users**. ++ a. On the **Include** tab, select **All users**. ++ b. On the **Exclude** tab, select **Users and groups** and choose your organization's emergency access or break-glass accounts. ++ :::image type="content" source="media/how-to-multifactor-authentication-customers/new-policy-users.png" alt-text="Screenshot of assigning users to the new policy." lightbox="media/how-to-multifactor-authentication-customers/new-policy-users.png"::: ++1. Select the link under **Cloud apps or actions**. ++ a. On the Include tab, choose one of the following options: ++ - Choose **All cloud apps**. ++ - Choose **Select apps** and select the link under **Select**. Find your app, select it, and then choose **Select**. ++ b. Under **Exclude**, select any applications that don't require multifactor authentication. ++ :::image type="content" source="media/how-to-multifactor-authentication-customers/new-policy-apps.png" alt-text="Screenshot of assigning apps to the new policy." lightbox="media/how-to-multifactor-authentication-customers/new-policy-apps.png"::: ++1. Under **Access controls** select the link under **Grant**. Select **Grant access**, select **Require multifactor authentication**, and then choose **Select**. ++ :::image type="content" source="media/how-to-multifactor-authentication-customers/new-policy-grant-require-mfa.png" alt-text="Screenshot of requiring MFA." lightbox="media/how-to-multifactor-authentication-customers/new-policy-grant-require-mfa.png"::: ++1. Confirm your settings and set **Enable policy** to **On**. ++1. Select **Create** to create to enable your policy. ++## Enable email one-time passcode as an MFA method ++Enable the email one-time passcode authentication method in your customer tenant for all users. ++1. Sign in to your customer tenant in the [Microsoft Entra admin center](https://entra.microsoft.com). ++1. Browse to **Azure Active Directory** > **Protect & secure** > **Authentication Methods**. ++1. In the **Method** list, select **Email OTP**. ++ :::image type="content" source="media/how-to-multifactor-authentication-customers/auth-methods-eotp.png" alt-text="Screenshot of the email one-time passcode option." lightbox="media/how-to-multifactor-authentication-customers/auth-methods-eotp.png"::: ++1. Under **Enable and Target**, turn the **Enable** toggle on. ++1. Under **Include**, next to **Target**, select **All users**. ++ :::image type="content" source="media/how-to-multifactor-authentication-customers/enable-eotp.png" alt-text="Screenshot of enabling email one-time passcode." lightbox="media/how-to-multifactor-authentication-customers/enable-eotp.png"::: ++1. Select **Save**. ++## Test the sign-in ++In a private browser, open your application and select **Sign-in**. You should be prompted for another authentication method. + |
active-directory | How To Protect Web Api Dotnet Core Overview | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-protect-web-api-dotnet-core-overview.md | + + Title: Secure an ASP.NET web API using Microsoft Entra +description: Learn how to secure a web API registered in customer's tenant using Microoft Entra +++++++++ Last updated : 05/10/2023+++#Customer intent: As a dev, I want to secure my web API registered in the customer's tenant using Microsoft Entra. +++# Secure an ASP.NET web API by using Microsoft Entra ++Web APIs may contain sensitive information that requires user authentication and authorization. Microsoft identity platform provides capabilities for you to protect your web API against unauthorized access. Applications can use delegated access, acting on behalf of a signed-in user, or app-only access, acting only as the application's own identity when calling protected web APIs. ++## Prerequisites ++- [An API registration](how-to-register-ciam-app.md?tabs=webapi&preserve-view=true) that exposes scopes (permissions) such as *ToDoList.Read*. If you haven't already, register an API in the Microsoft Entra admin center by following the registration steps. ++## Protecting a web API ++The following are the steps you complete to protect your web API: ++1. [Register your web API](how-to-register-ciam-app.md?tabs=webapi) in the Microsoft Entra admin center. +1. [Configure your web API](how-to-protect-web-api-dotnet-core-prepare-api.md). +1. [Protect your web API endpoints](how-to-protect-web-api-dotnet-core-protect-endpoints.md). +1. [Test your protected web API](how-to-protect-web-api-dotnet-core-test-api.md). ++## Next steps ++> [!div class="nextstepaction"] +> [Configure your web API >](how-to-protect-web-api-dotnet-core-prepare-api.md) |
active-directory | How To Protect Web Api Dotnet Core Prepare Api | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-protect-web-api-dotnet-core-prepare-api.md | + + Title: Configure web API for protection using Microsoft Entra +description: Learn how to configure web API settings so as to protect it using Microsoft Entra. +++++++++ Last updated : 05/10/2023+++#Customer intent: As a dev, I want to configure my web API settings so as to protect it using Microsoft Entra. +++# Secure an ASP.NET web API by using Microsoft Entra - configure your web API ++In this how-to article, we go through the steps you take to configure your web API before securing its endpoints. When using the Microsoft identity platform to secure your web API, you first need to have it registered before configuring your API. ++## Prerequisites ++Go through the [overview of creating a protected web API](how-to-protect-web-api-dotnet-core-overview.md) before proceeding further with this tutorial. ++## Create an ASP.NET Core web API ++In this how to guide, we use Visual Studio Code and .NET 7.0. If you're using Visual Studio to create the API, see the [create a Create a web API with ASP.NET Core](/aspnet/core/tutorials/first-web-api). ++1. Open the [integrated terminal](https://code.visualstudio.com/docs/editor/integrated-terminal). +1. Navigate to the folder where you want your project to live. +1. Run the following commands: ++ ```dotnetcli + dotnet new webapi -o ToDoListAPI + cd ToDoListAPI + ``` ++1. When a dialog box asks if you want to add required assets to the project, select **Yes**. ++## Add packages ++Install the following packages: ++- `Microsoft.EntityFrameworkCore.InMemory` that allows Entity Framework Core to be used with an in-memory database. It's not designed for production use. +- `Microsoft.Identity.Web` simplifies adding authentication and authorization support to web apps and web APIs integrating with the Microsoft identity platform. ++ ```dotnetcli + dotnet add package Microsoft.EntityFrameworkCore.InMemory + dotnet add package Microsoft.Identity.Web + ``` ++## Configure app registration details ++To protect your web API, you need to have the Application (Client) ID, Directory / Tenant ID and Directory / Tenant name that you have obtained during registration on the Microsoft Entra admin center. If you haven't registered your web API yet, kindly follow the [web API registration instructions](how-to-register-ciam-app.md?tabs=webapi&preserve-view=true) before proceeding. ++Open the *appsettings.json* file in your app folder and add in the app registration details. ++```json +{ + "AzureAd": { + "Instance": "https://Enter_the_Tenant_Subdomain_Here.ciamlogin.com/", + "TenantId": "Enter_the_Tenant_Id_Here", + "ClientId": "Enter_the_Application_Id_Here", + }, + "Logging": {...}, + "AllowedHosts": "*" +} +``` ++Replace the following placeholders as shown: ++- Replace `Enter_the_Application_Id_Here` with your application (client) ID. +- Replace `Enter_the_Tenant_Id_Here` with your Directory (tenant) ID. +- Replace `Enter_the_Tenant_Subdomain_Here` with your Directory (tenant) subdomain. For example, if your primary domain is *contoso.onmicrosoft.com*, replace `Enter_the_Tenant_Subdomain_Here` with *contoso*. ++If you don't have these values, learn how to [read tenant details](how-to-create-customer-tenant-portal.md#get-the-customer-tenant-details) ++## Add app role and scope ++All APIs must publish a minimum of one scope, also called [Delegated Permission](/azure/active-directory/develop/permissions-consent-overview#types-of-permissions), for the client apps to obtain an access token for a user successfully. In a similar sense, APIs should also publish a minimum of one app role for applications, also called [Application Permission](/azure/active-directory/develop/permissions-consent-overview#types-of-permissions), for the client apps to obtain an access token as themselves, that is, when they aren't signing-in a user. ++We specify these permissions in the *appsettings.json* file as configuration parameters. These permissions are registered via the Microsoft Entra admin center. For the purposes of this tutorial, we have registered four permissions. *ToDoList.ReadWrite* and *ToDoList.Read* as the delegated permissions, and *ToDoList.ReadWrite.All* and *ToDoList.Read.All* as the application permissions. ++```json +{ + "AzureAd": {...}, + "Scopes": { + "Read": ["ToDoList.Read", "ToDoList.ReadWrite"], + "Write": ["ToDoList.ReadWrite"] + }, + "AppPermissions": { + "Read": ["ToDoList.Read.All", "ToDoList.ReadWrite.All"], + "Write": ["ToDoList.ReadWrite.All"] + } + }, + "Logging": {...}, + "AllowedHosts": "*" +} +``` +++## Add authentication scheme ++An [authentication scheme](/aspnet/core/security/authorization/limitingidentitybyscheme) is named when the authentication service is configured during authentication. In this article, we use the JWT bearer authentication scheme. ++Add the following code in the *Programs.cs* file to add authentication scheme. ++```csharp +// Add the following to your imports +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.Identity.Web; ++// Add authentication scheme +builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + .AddMicrosoftIdentityWebApi(builder.Configuration); +``` ++## Create your models ++Create a folder called *Models* in the root folder of your project. Navigate to the folder and create a file called *ToDo.cs* and add the following code. This code creates a model called *ToDo*. ++```csharp +using System; ++namespace ToDoListAPI.Models; ++public class ToDo +{ + public int Id { get; set; } + public Guid Owner { get; set; } + public string Description { get; set; } = string.Empty; +} +``` ++## Add a database context ++The database context is the main class that coordinates Entity Framework functionality for a data model. This class is created by deriving from the [*Microsoft.EntityFrameworkCore.DbContext*](/dotnet/api/microsoft.entityframeworkcore.dbcontext) class. In this article, we use an in-memory database for testing purposes. ++Create a folder called *DbContext* in the root folder of the project. Navigate into that folder and create a file called *ToDoContext.cs*. Add the following contents to that file: ++```csharp +using Microsoft.EntityFrameworkCore; +using ToDoListAPI.Models; ++namespace ToDoListAPI.Context; ++public class ToDoContext : DbContext +{ + public ToDoContext(DbContextOptions<ToDoContext> options) : base(options) + { + } ++ public DbSet<ToDo> ToDos { get; set; } +} +``` ++Add the following code in the *Program.cs* file. ++```csharp +// Add the following to your imports +using ToDoListAPI.Context; +using Microsoft.EntityFrameworkCore; ++builder.Services.AddDbContext<TodoContext>(opt => + opt.UseInMemoryDatabase("ToDos")); +``` ++## Next steps ++> [!div class="nextstepaction"] +> [Protect your web API endpoints >](how-to-protect-web-api-dotnet-core-protect-endpoints.md) |
active-directory | How To Protect Web Api Dotnet Core Protect Endpoints | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-protect-web-api-dotnet-core-protect-endpoints.md | + + Title: Secure web API endpoints using Microsoft Entra +description: Learn how to secure endpoints of a web API registered in customer's tenant using Microoft Entra +++++++++ Last updated : 05/10/2023+++#Customer intent: As a dev, I want to secure endpoints of my web API registered in the customer's tenant using Microsoft Entra. +++# Secure an ASP.NET web API by using Microsoft Entra - secure web API endpoints ++Controllers handle requests that come in through the API endpoints. Controllers are made of Action methods. To protect our resources, we protect the API endpoints by adding security features to our controllers. Create a folder called *Controllers* in the project root folder. Navigate into this folder and create a file called *ToDoListController.cs*. ++## Prerequisites ++[Configure your web API](how-to-protect-web-api-dotnet-core-prepare-api.md) before going through this article. ++## Add the code ++We begin adding controller actions to our controller. In most cases, the controller would have more than one action. Typically Create, Read, Update, and Delete (CRUD) actions. For more information, see the article on [how to create a .NET web API doc](/aspnet/core/tutorials/first-web-api?view=aspnetcore-7.0&tabs=visual-studio-code&preserve-view=true#scaffold-a-controller). For the purposes of this article, we demonstrate using two action items, a read all action item and a create action item, how to protect your endpoints. For a full example, see the [samples file](https://github.com/Azure-Samples/ms-identity-ciam-dotnet-tutorial/blob/main/2-Authorization/3-call-own-api-dotnet-core-daemon/ToDoListAPI/Controllers/ToDoListController.cs). ++Our boiler plate code for the controller looks as follows: ++```csharp +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Microsoft.Identity.Web; +using Microsoft.Identity.Web.Resource; +using ToDoListAPI.Models; ++namespace ToDoListAPI.Controllers; ++[Authorize] +[Route("api/[controller]")] +[ApiController] +public class ToDoListController : ControllerBase +{ + private readonly ToDoContext _toDoContext; ++ public ToDoListController(ToDoContext toDoContext) + { + _toDoContext = toDoContext; + } ++ [HttpGet()] + [RequiredScopeOrAppPermission()] + public async Task<IActionResult> GetAsync(){...} + + [HttpPost] + [RequiredScopeOrAppPermission()] + public async Task<IActionResult> PostAsync([FromBody] ToDo toDo){...} ++ private bool RequestCanAccessToDo(Guid userId){...} ++ private Guid GetUserId(){...} ++ private bool IsAppMakingRequest(){...} +} +``` ++## Explanation for the code snippets ++In this section, we go through the code to see we protect our API by adding code into the placeholders we created. The focus here isn't on building the API, but rather protecting it. ++1. Import the necessary packages. The [*Microsoft.Identity.Web*](/azure/active-directory/develop/microsoft-identity-web) package is an MSAL wrapper that helps us easily handle authentication logic, for example, by handling token validation. We also use the permissions definitions that we defined in the *appsettings.json* configuration file. To ensure that our endpoints require authorization, we use the inbuilt [*Microsoft.AspNetCore.Authorization*](/dotnet/api/microsoft.aspnetcore.authorization) package. ++1. Since we granted permissions for this API to be called either using delegated permissions on behalf of the user or application permissions where the client calls as itself and not on the user's behalf, it's important to know whether the call is being made by the app on its own behalf. To do this, we check the claims to find whether the access token contains the `idtyp` optional claim. This claim is the most accurate way for the API to determine whether a token is an app token or an app + user token. Configure your API to use this [optional claim](/azure/active-directory/develop/active-directory-optional-claims) via your API app registration if you haven't. ++ ```csharp + private bool IsAppMakingRequest() + { + // Add in the optional 'idtyp' claim to check if the access token is coming from an application or user. + // See: https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-optional-claims + if (HttpContext.User.Claims.Any(c => c.Type == "idtyp")) + { + return HttpContext.User.Claims.Any(c => c.Type == "idtyp" && c.Value == "app"); + } + else + { + // alternatively, if an AT contains the roles claim but no scp claim, that indicates it's an app token + return HttpContext.User.Claims.Any(c => c.Type == "roles") && !HttpContext.User.Claims.Any(c => c.Type == "scp"); + } + } + ``` ++1. Add a helper function that determines whether the request being made contains enough permissions to carry out the intended action. To do this, we check whether it's the app making the request on its own behalf or whether the app is making the call on behalf of a user who owns the given resource by validating the user ID. ++ ```csharp + private bool RequestCanAccessToDo(Guid userId) + { + return IsAppMakingRequest() || (userId == GetUserId()); + } ++ private Guid GetUserId() + { + Guid userId; ++ if (!Guid.TryParse(HttpContext.User.GetObjectId(), out userId)) + { + throw new Exception("User ID is not valid."); + } ++ return userId; + } + ``` ++1. Plug in our permission definitions to protect our routes. We protect our API by adding the `[Authorize]` attribute to the controller class. This ensures the controller actions can be called only if the API is called with an authorized identity. The permission definitions define what kinds of permissions are needed to perform these actions. ++ ```csharp + [Authorize] + [Route("api/[controller]")] + [ApiController] + public class ToDoListController: ControllerBase{...} + ``` ++ Here, we add permissions to the GET all endpoint and the POST endpoint. We do this by using the [*RequiredScopeOrAppPermission*](/dotnet/api/microsoft.identity.web.resource.requiredscopeorapppermissionattribute) method that is part of the *Microsoft.Identity.Web.Resource* namespace. We then pass our scopes and permissions to this method via the *RequiredScopesConfigurationKey* and *RequiredAppPermissionsConfigurationKey* attributes. ++ ```csharp + [HttpGet] + [RequiredScopeOrAppPermission( + RequiredScopesConfigurationKey = "AzureAD:Scopes:Read", + RequiredAppPermissionsConfigurationKey = "AzureAD:AppPermissions:Read" + )] + public async Task<IActionResult> GetAsync() + { + var toDos = await _toDoContext.ToDos! + .Where(td => RequestCanAccessToDo(td.Owner)) + .ToListAsync(); ++ return Ok(toDos); + } ++ [HttpPost] + [RequiredScopeOrAppPermission( + RequiredScopesConfigurationKey = "AzureAD:Scopes:Write", + RequiredAppPermissionsConfigurationKey = "AzureAD:AppPermissions:Write" + )] + public async Task<IActionResult> PostAsync([FromBody] ToDo toDo) + { + // Only let applications with global to-do access set the user ID or to-do's + var ownerIdOfTodo = IsAppMakingRequest() ? toDo.Owner : GetUserId(); ++ var newToDo = new ToDo() + { + Owner = ownerIdOfTodo, + Description = toDo.Description + }; ++ await _toDoContext.ToDos!.AddAsync(newToDo); + await _toDoContext.SaveChangesAsync(); ++ return Created($"/todo/{newToDo!.Id}", newToDo); + } + ``` ++## Run your API ++Run your API to ensure that it's running well without any errors using the command `dotnet run`. If you intend to use https protocol even during testing, you need to [trust .NET's development certificate](/aspnet/core/tutorials/first-web-api#test-the-project). ++## Next steps ++> [!div class="nextstepaction"] +> [Test your protected web API >](how-to-protect-web-api-dotnet-core-test-api.md) |
active-directory | How To Protect Web Api Dotnet Core Test Api | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-protect-web-api-dotnet-core-test-api.md | + + Title: Test a protected web API +description: Learn how to test a protected web API registered in the CIAM tenant +++++++++ Last updated : 05/10/2023+++#Customer intent: As a dev, I want to learn how to test my protected web API. +++# Test your protected API ++In this article, we create a .NET daemon app that helps us test a protected web API. ++## Prerequisites ++Before going through this article, ensure you have a [protected web API](how-to-protect-web-api-dotnet-core-protect-endpoints.md) to use for testing purposes. ++## Register the daemon app ++++## Assign app role to your daemon app ++Apps authenticating by themselves require app permissions. +++## Write code ++1. Initialize a .NET console app and navigate to its root folder ++ ```dotnetcli + dotnet new console -o MyTestApp + cd MyTestApp + ``` +1. Install MSAL to help you with handling authentication by running the following command: + + ```dotnetcli + dotnet add package Microsoft.Identity.Client + ``` +1. Run your API project and note the port on which it's running. +1. Open the *Program.cs* file and replace the "Hello world" code with the following code. ++ ```csharp + using System; + using System.Net.Http; + using System.Net.Http.Headers; ++ HttpClient client = new HttpClient(); ++ var response = await client.GetAsync("https://localhost:<your-api-port>/api/todolist"); + Console.WriteLine("Your response is: " + response.StatusCode); + ``` ++ Navigate to the daemon app root directory and run app using the command `dotnet run`. This code sends a request without an access token. You should see the string: *Your response is: Unauthorized* printed in your console. +1. Remove the code in step 4 and replace with the following to test your API by sending a request with a valid access token. ++ ```csharp + using Microsoft.Identity.Client; + using System; + using System.Net.Http; + using System.Net.Http.Headers; ++ HttpClient client = new HttpClient(); ++ var clientId = "<your-daemon-app-client-id>"; + var clientSecret = "<your-daemon-app-secret>"; + var scopes = new[] {"api://<your-web-api-application-id>/.default"}; + var tenantName= "<your-tenant-name>"; + var authority = $"https://{tenantName}.ciamlogin.com/"; ++ var app = ConfidentialClientApplicationBuilder + .Create(clientId) + .WithAuthority(authority) + .WithClientSecret(clientSecret) + .Build(); ++ var result = await app.AcquireTokenForClient(scopes).ExecuteAsync(); ++ client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); + var response = await client.GetAsync("https://localhost:44351/api/todolist"); + Console.WriteLine("Your response is: " + response.StatusCode); + ``` ++ Navigate to the daemon app root directory and run app using the command `dotnet run`. This code sends a request with a valid access token. You should see the string: *Your response is: OK* printed in your console. |
active-directory | How To Register Ciam App | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-register-ciam-app.md | + + Title: How-to - Register an app in Azure AD for customers +description: Learn about how to register an app in the customer tenant. ++++++++ Last updated : 05/09/2023++++#Customer intent: As a dev, devops, or it admin, I want to learn about how to register an app on the Microsoft Entra admin center. ++# Register your app in the customer tenant ++Azure Active Directory (Azure AD) for customers enables your organization to manage customers’ identities, and securely control access to your public facing applications and APIs. Applications where your customers can buy your products, subscribe to your services, or access their account and data. Your customers only need to sign in on a device or a web browser once and have access to all your applications you granted them permissions. ++To enable your application to sign in with Azure AD for customers, you need to register your app in the Azure AD for customers. The app registration establishes a trust relationship between the app and Azure AD for customers. +During app registration, you specify the redirect URI. The redirect URI is the endpoint to which users are redirected by Azure AD for customers after they authenticate. The app registration process generates an application ID, also known as the client ID, that uniquely identifies your app. ++Azure AD for customers supports authentication for various modern application architectures, for example web app or single-page app. The interaction of each application type with the customer tenant is different, therefore, you must specify the type of application you want to register. ++In this article, you’ll learn how to register an application in your customer tenant. ++## Prerequisites ++- An Azure account that has an active subscription. [Create an account for free](https://azure.microsoft.com/free/?WT.mc_id=A261C142F). +- Your Azure AD for customers tenant. If you don't already have one, sign up for a [free trial](https://aka.ms/ciam-free-trial?wt.mc_id=ciamcustomertenantfreetrial_linkclick_content_cnl). ++## Choose your app type ++# [Single-page app (SPA)](#tab/spa) +## How to register your Single-page app? ++The following steps show you how to register your app in the admin center: ++1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com/). ++1. If you have access to multiple tenants, make sure you use the directory that contains your Azure AD for customers tenant: + + 1. Select the **Directories + subscriptions** icon in the portal toolbar. + + 1. On the **Portal settings | Directories + subscriptions** page, find your Azure AD for customers directory in the **Directory name** list, and then select **Switch**. ++1. On the sidebar menu, select **Azure Active Directory**. ++1. Select **Applications**, then select **App Registrations**. ++1. Select **+ New registration**. ++1. In the **Register an application page** that appears, enter your application's registration information: + + 1. In the **Name** section, enter a meaningful application name that will be displayed to users of the app, for example *ciam-client-app*. + + 1. Under **Supported account types**, select **Accounts in this organizational directory only**. + + 1. Under **Redirect URI (optional)**, select **Single-page application (SPA)** and then, in the URL box, enter `http://localhost:3000/`. ++1. Select **Register**. ++1. The application's **Overview pane** is displayed when registration is complete. Record the **Directory (tenant) ID** and the **Application (client) ID** to be used in your application source code. +++### Add delegated permissions +This app signs in users. You can add delegated permissions to it, by following the steps below: +++### If you want to call an API follow the steps below (optional): ++If you'd like to learn how to expose the permissions by adding a link, go to the [Web API](how-to-register-ciam-app.md?tabs=webapi) section. ++## Next steps + +- [Create a sign-up and sign-in user flow](how-to-user-flow-sign-up-sign-in-customers.md) +- [Sign in users in a sample vanilla JavaScript single-page app](how-to-single-page-app-vanillajs-sample-sign-in.md) ++# [Web app](#tab/webapp) +## How to register your Web app? ++The following steps show you how to register your app in the admin center: ++1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com/). ++1. If you have access to multiple tenants, make sure you use the directory that contains your Azure AD for customers tenant: + + 1. Select the **Directories + subscriptions** icon in the portal toolbar. + + 1. On the **Portal settings | Directories + subscriptions** page, find your Azure AD for customers directory in the **Directory name** list, and then select **Switch**. ++1. On the sidebar menu, select **Azure Active Directory**. ++1. Select **Applications**, then select **App Registrations**. ++1. Select **+ New registration**. ++1. In the **Register an application page** that appears, enter your application's registration information: + + 1. In the **Name** section, enter a meaningful application name that will be displayed to users of the app, for example *ciam-client-app*. + + 1. Under **Supported account types**, select **Accounts in this organizational directory only**. + + 1. Under **Redirect URI (optional)**, select **Web** and then, in the URL box, enter `http://localhost:3000/`. ++1. Select **Register**. ++1. The application's **Overview pane** is displayed when registration is complete. Record the **Directory (tenant) ID** and the **Application (client) ID** to be used in your application source code. +++### Add delegated permissions +This app signs in users. You can add delegated permissions to it, by following the steps below: +++### Create a client secret  ++### If you want to call an API follow the steps below (optional): ++## Next steps + +- [Create a sign-up and sign-in user flow](how-to-user-flow-sign-up-sign-in-customers.md) +- [Sign in users in a sample Node.js web app](how-to-web-app-node-sample-sign-in.md) ++# [Web API](#tab/webapi) +## How to register your Web API? +++### Expose permissions +++### If you want to add app roles follow the steps below (optional): +++## Next steps + +- [Create a sign-up and sign-in user flow](how-to-user-flow-sign-up-sign-in-customers.md) ++# [Desktop or Mobile app](#tab/desktopmobileapp) +## How to register your Desktop or Mobile app? ++The following steps show you how to register your app in the admin center: ++1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com/). ++1. If you have access to multiple tenants, make sure you use the directory that contains your Azure AD for customers tenant: + + 1. Select the **Directories + subscriptions** icon in the portal toolbar. + + 1. On the **Portal settings | Directories + subscriptions** page, find your Azure AD for customers directory in the **Directory name** list, and then select **Switch**. ++1. On the sidebar menu, select **Azure Active Directory**. ++1. Select **Applications**, then select **App Registrations**. ++1. Select **+ New registration**. ++1. In the **Register an application page** that appears, enter your application's registration information: + + 1. In the **Name** section, enter a meaningful application name that will be displayed to users of the app, for example *ciam-client-app*. + + 1. Under **Supported account types**, select **Accounts in this organizational directory only**. + + 1. Under **Redirect URI (optional)**, select the **Mobile and desktop applications** option and then, in the URL box, enter a URI with a unique scheme. For example, Electron desktop app's redirect URI looks something similar to `http://localhost` while that of a .NET Multi-platform App UI (MAUI) looks similar to `msal{ClientId}://auth`. ++1. Select **Register**. ++1. The application's **Overview pane** is displayed when registration is complete. Record the **Directory (tenant) ID** and the **Application (client) ID** to be used in your application source code. ++### Add delegated permissions ++### If you want to call an API follow the steps below (optional): ++## Next steps + +- [Create a sign-up and sign-in user flow](how-to-user-flow-sign-up-sign-in-customers.md) +- [Sign in users in a sample Electron desktop app](how-to-desktop-app-electron-sample-sign-in.md) ++# [Daemon app](#tab/daemonapp) +## How to register your Daemon app? +++### If you want to call an API follow the steps below (optional) +A daemon app signs-in as itself using the [OAuth 2.0 client credentials flow](/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow), you add application permissions, which is required by apps that authenticate as themselves: +++## Next steps + +- Learn more about a [daemon app that calls a web API in the daemon's name](/azure/active-directory/develop/authentication-flows-app-scenarios#daemon-app-that-calls-a-web-api-in-the-daemons-name) +- [Create a sign-up and sign-in user flow](how-to-user-flow-sign-up-sign-in-customers.md) |
active-directory | How To Single Page App Vanillajs Configure Authentication | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-single-page-app-vanillajs-configure-authentication.md | + + Title: Configure a vanilla JavaScript single-page app for authentication +description: Learn how to configure authentication for a vanilla JavaScript single-page app (SPA) with your Azure Active Directory (AD) for customers tenant. +++++++++ Last updated : 05/23/2023+++#Customer intent: As a developer, I want to learn how to configure vanilla JavaScript single-page app (SPA) to sign in and sign out users with my Azure Active Directory (AD) for customers tenant. +++# Create components for authentication and authorization ++In the previous article, you created a vanilla JavaScript (JS) single-page application (SPA) and a server to host it. In this article, you'll configure the application to authenticate and authorize users to access protected resources. Authentication and authorization are handled by the [Microsoft Authentication Library for JavaScript (MSAL.js)](/javascript/api/overview/). The library is used to authenticate users and acquire access tokens from Azure Active Directory (AD) for customers. ++## Prerequisites ++* Completion of the prerequisites and steps in [Prepare a single-page application for authentication](how-to-single-page-app-vanillajs-prepare-app.md). ++## Creating the authentication configuration file ++The application uses the [Implicit Grant Flow](../../develop/v2-oauth2-implicit-grant-flow.md) to authenticate users. The Implicit Grant Flow is a browser-based flow that doesn't require a back-end server. The flow redirects the user to the sign-in page, where the user signs in and consents to the permissions that are being requested by the application. The purpose of *authConfig.js* is to configure the authentication flow. ++1. In your IDE, create a new folder and name it **public** +1. In the *public* folder, create a new file and name it *authConfig.js*. +1. Open *authConfig.js* and add the following code snippet: ++ ```javascript + /** + * Configuration object to be passed to MSAL instance on creation. + * For a full list of MSAL.js configuration parameters, visit: + * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/configuration.md + */ + const msalConfig = { + auth: { + clientId: 'Enter_the_Application_Id_Here', // This is the ONLY mandatory field that you need to supply. + authority: 'https://Enter_the_Tenant_Subdomain_Here.ciamlogin.com/', // Replace "Enter_the_Tenant_Subdomain_Here" with your tenant subdomain + redirectUri: '/', // You must register this URI on Azure Portal/App Registration. Defaults to window.location.href e.g. http://localhost:3000/ + navigateToLoginRequestUrl: true, // If "true", will navigate back to the original request location before processing the auth code response. + }, + cache: { + cacheLocation: 'sessionStorage', // Configures cache location. "sessionStorage" is more secure, but "localStorage" gives you SSO. + storeAuthStateInCookie: false, // set this to true if you have to support IE + }, + system: { + loggerOptions: { + loggerCallback: (level, message, containsPii) => { + if (containsPii) { + return; + } + switch (level) { + case msal.LogLevel.Error: + console.error(message); + return; + case msal.LogLevel.Info: + console.info(message); + return; + case msal.LogLevel.Verbose: + console.debug(message); + return; + case msal.LogLevel.Warning: + console.warn(message); + return; + } + }, + }, + }, + }; + + /** + * An optional silentRequest object can be used to achieve silent SSO + * between applications by providing a "login_hint" property. + */ + + // const silentRequest = { + // scopes: ["openid", "profile"], + // loginHint: "example@domain.net" + // }; + + // exporting config object for jest + if (typeof exports !== 'undefined') { + module.exports = { + msalConfig: msalConfig, + loginRequest: loginRequest, + }; + } + ``` ++1. Find the `Enter_the_Application_Id_Here` value and replace it with the application ID (clientId) of the app you registered in the Microsoft Entra admin center. +1. In **Authority**, find `Enter_the_Tenant_Subdomain_Here` and replace it with the subdomain of your tenant. For example, if your tenant primary domain is *caseyjensen@onmicrosoft.com*, the value you should enter is *casyjensen*. +1. Save the file. ++## Creating the redirection file ++A redirection file is required to handle the response from the sign-in page. The redirection file is used to extract the access token from the URL fragment and use it to call the protected API. ++1. In the *public* folder, create a new file and name it *authRedirect.js*. +1. Open *authRedirect.js* and add the following code snippet: ++ ```javascript + // Create the main myMSALObj instance + // configuration parameters are located at authConfig.js + const myMSALObj = new msal.PublicClientApplication(msalConfig); + + let username = ""; + + /** + * A promise handler needs to be registered for handling the + * response returned from redirect flow. For more information, visit: + * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/initialization.md#redirect-apis + */ + myMSALObj.handleRedirectPromise() + .then(handleResponse) + .catch((error) => { + console.error(error); + }); + + function selectAccount() { + + /** + * See here for more info on account retrieval: + * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-common/docs/Accounts.md + */ + + const currentAccounts = myMSALObj.getAllAccounts(); + + if (!currentAccounts) { + return; + } else if (currentAccounts.length > 1) { + // Add your account choosing logic here + console.warn("Multiple accounts detected."); + } else if (currentAccounts.length === 1) { + welcomeUser(currentAccounts[0].username); + updateTable(currentAccounts[0]); + } + } + + function handleResponse(response) { + + /** + * To see the full list of response object properties, visit: + * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/request-response-object.md#response + */ + + if (response !== null) { + welcomeUser(response.account.username); + updateTable(response.account); + } else { + selectAccount(); + } + } + + function signIn() { + + /** + * You can pass a custom request object below. This will override the initial configuration. For more information, visit: + * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/request-response-object.md#request + */ + + myMSALObj.loginRedirect(loginRequest); + } + + function signOut() { + + /** + * You can pass a custom request object below. This will override the initial configuration. For more information, visit: + * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/request-response-object.md#request + */ + + // Choose which account to logout from by passing a username. + const logoutRequest = { + account: myMSALObj.getAccountByUsername(username), + postLogoutRedirectUri: '/signout', // remove this line if you would like navigate to index page after logout. + + }; + + myMSALObj.logoutRedirect(logoutRequest); + } + ``` ++1. Save the file. ++## Creating the authPopup.js file ++The application uses *authPopup.js* to handle the authentication flow when the user signs in using the pop-up window. The pop-up window is used when the user is already signed in and the application needs to get an access token for a different resource. ++1. In the *public* folder, create a new file and name it *authPopup.js*. +1. Open *authPopup.js* and add the following code snippet: ++ ```javascript + // Create the main myMSALObj instance + // configuration parameters are located at authConfig.js + const myMSALObj = new msal.PublicClientApplication(msalConfig); + + let username = ""; + + function selectAccount () { + + /** + * See here for more info on account retrieval: + * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-common/docs/Accounts.md + */ + + const currentAccounts = myMSALObj.getAllAccounts(); + + if (!currentAccounts || currentAccounts.length < 1) { + return; + } else if (currentAccounts.length > 1) { + // Add your account choosing logic here + console.warn("Multiple accounts detected."); + } else if (currentAccounts.length === 1) { + username = currentAccounts[0].username + welcomeUser(currentAccounts[0].username); + updateTable(currentAccounts[0]); + } + } + + function handleResponse(response) { + + /** + * To see the full list of response object properties, visit: + * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/request-response-object.md#response + */ + + if (response !== null) { + username = response.account.username + welcomeUser(username); + updateTable(response.account); + } else { + selectAccount(); + } + } + + function signIn() { + + /** + * You can pass a custom request object below. This will override the initial configuration. For more information, visit: + * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/request-response-object.md#request + */ + + myMSALObj.loginPopup(loginRequest) + .then(handleResponse) + .catch(error => { + console.error(error); + }); + } + + function signOut() { + + /** + * You can pass a custom request object below. This will override the initial configuration. For more information, visit: + * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/request-response-object.md#request + */ + + // Choose which account to logout from by passing a username. + const logoutRequest = { + account: myMSALObj.getAccountByUsername(username), + mainWindowRedirectUri: '/signout' + }; + + myMSALObj.logoutPopup(logoutRequest); + } + + selectAccount(); + ``` ++1. Save the file. ++## Next steps ++> [!div class="nextstepaction"] +> [Configure a single-page application User Interface and Sign-In](how-to-single-page-app-vanillajs-sign-in-sign-out.md) |
active-directory | How To Single Page App Vanillajs Prepare App | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-single-page-app-vanillajs-prepare-app.md | + + Title: Prepare a vanilla JavaScript single-page app for authentication +description: Learn how to prepare a vanilla JavaScript single-page app (SPA) for authentication and authorization with your Azure Active Directory (AD) for customers tenant. ++++++++ Last updated : 05/23/2023+++#Customer intent: As a developer, I want to learn how to configure vanilla JavaScript single-page app (SPA) to sign in and sign out users with my Azure AD for customers tenant. +++# Prepare a Single-page application for authentication ++After registering an application and creating a user flow in a Azure Active Directory (AD) for customers tenant, a vanilla JavaScript (JS) single-page application (SPA) can be created using an integrated development environment (IDE) or a code editor. In this article, you'll create a vanilla JS SPA and a server to host the application. ++## Prerequisites ++- Completion of the prerequisites and steps in [Sign in users to a vanilla JS Single-page application](how-to-single-page-app-vanillajs-prepare-tenant.md). +- Although any IDE that supports vanilla JS applications can be used, **Visual Studio Code** is used for this guide. It can be downloaded from the [Downloads](https://visualstudio.microsoft.com/downloads) page. +- [Node.js](https://nodejs.org/en/download/). ++## Create a new vanilla JS project and install dependencies ++1. Open a terminal in your IDE and navigate to the location in which to create your project. +1. Run the following command to create a new vanilla JS project ++ ```powershell + npm init -y + ``` ++1. In the **Terminal**, run the following command to install the required dependencies for the project: ++ ```powershell + npm install express morgan @azure/msal-browser + ``` ++## Create the server file ++**Express** is a web application framework for **Node.js**. It's used to create a server that hosts the application. **Morgan** is the middleware that logs HTTP requests to the console. The server file is used to host these dependencies and contains the routes for the application. ++1. In your IDE, create a new file and call it *server.js*. +1. Add the following code snippet to the *server.js* file: ++ ```javascript + const express = require('express'); + const morgan = require('morgan'); + const path = require('path'); + + const DEFAULT_PORT = process.env.PORT || 3000; + + // initialize express. + const app = express(); + + // Configure morgan module to log all requests. + app.use(morgan('dev')); + + // serve public assets. + app.use(express.static('public')); + + // serve msal-browser module + app.use(express.static(path.join(__dirname, "node_modules/@azure/msal-browser/lib"))); + + // set up a route for signout.html + app.get('/signout', (req, res) => { + res.sendFile(path.join(__dirname + '/public/signout.html')); + }); + + // set up a route for redirect.html + app.get('/redirect', (req, res) => { + res.sendFile(path.join(__dirname + '/public/redirect.html')); + }); + + // set up a route for https://docsupdatetracker.net/index.html + app.get('/', (req, res) => { + res.sendFile(path.join(__dirname + '/https://docsupdatetracker.net/index.html')); + }); + + app.listen(DEFAULT_PORT, () => { + console.log(`Sample app listening on port ${DEFAULT_PORT}!`); + }); ++ ``` ++## Next steps ++> [!div class="nextstepaction"] +> [Configure application for authentication](how-to-single-page-app-vanillajs-configure-authentication.md) |
active-directory | How To Single Page App Vanillajs Prepare Tenant | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-single-page-app-vanillajs-prepare-tenant.md | + + Title: Prepare your tenant to use a vanilla JavaScript single-page app for authentication. +description: Learn how to configure your Azure Active Directory (AD) for customers tenant for authentication with a vanilla JavaScript single-page app (SPA). ++++++++ Last updated : 05/23/2023+++#Customer intent: As a developer, I want to learn how to configure vanilla JavaScript single-page app (SPA) to sign in and sign out users with my Azure Active Directory (AD) for customers tenant. +++# Sign in users to a vanilla JS single-page application - Prepare your tenant ++This how-to guide demonstrates how to prepare your Azure Active Directory (Azure AD) for customers tenant for authentication. You'll register a single-page application (SPA) in the Microsoft Entra admin center, and record its identifiers. You'll then create a sign in and sign out user flow in the Microsoft Entra admin center and associate your SPA with the user flow. ++## Prerequisites ++- Azure AD for customers tenant. If you don't already have one, [sign up for a free trial](https://aka.ms/ciam-free-trial?wt.mc_id=ciamcustomertenantfreetrial_linkclick_content_cnl). ++- If you have already registered a SPA in the Microsoft Entra admin center, and associated it with a user flow, you can skip the steps in this article and move to [Prepare a vanilla JavaScript single-page app for authentication](how-to-single-page-app-vanillajs-prepare-app.md). ++## Register the SPA +++## Grant API permissions +++## Create a user flow +++## Associate the SPA with the user flow +++## Next steps ++> [!div class="nextstepaction"] +> [Prepare your Vanilla JS SPA](how-to-single-page-app-vanillajs-prepare-app.md) |
active-directory | How To Single Page App Vanillajs Sample Sign In | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-single-page-app-vanillajs-sample-sign-in.md | + + Title: Sign in users in a sample vanilla JavaScript single-page application +description: Learn how to configure a sample JavaSCript single-page application (SPA) to sign in and sign out users. +++++++++ Last updated : 05/23/2023+++#Customer intent: As a dev, devops, I want to learn about how to configure a sample vanilla JS SPA to sign in and sign out users with my Azure Active Directory (Azure AD) for customers tenant +++# Sign in users in a sample vanilla JavaScript single-page application ++This how-to guide uses a sample vanilla JavaScript single-page Application (SPA) to demonstrate how to add authentication to a SPA. This SPA enables users to sign in and sign out by using their own Azure Azure Active Directory (AD) for customers tenant. The sample uses the [Microsoft Authentication Library for JavaScript (MSAL.js)](https://github.com/AzureAD/microsoft-authentication-library-for-js) to handle authentication. ++## Prerequisites ++* Although any IDE that supports vanilla JS applications can be used, **Visual Studio Code** is used for this guide. It can be downloaded from the [Downloads](https://visualstudio.microsoft.com/downloads) page. +* [Node.js](https://nodejs.org/en/download/). +* Azure AD for customers tenant. If you don't already have one, [sign up for a free trial](https://aka.ms/ciam-free-trial?wt.mc_id=ciamcustomertenantfreetrial_linkclick_content_cnl). ++## Register the SPA in the Microsoft Entra admin center +++## Grant API permissions +++## Create a user flow +++## Associate the SPA with the user flow +++## Clone or download sample SPA ++To get the sample SPA, you can choose one of the following options: ++* Clone the repository using Git: ++ ```powershell + git clone https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial.git + ``` ++* [Download the sample](https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial/archive/refs/heads/main.zip) ++If you choose to download the `.zip` file, extract the sample app file to a folder where the total length of the path is 260 or fewer characters. ++## Install project dependencies ++1. Open a terminal window in the root directory of the sample project, and enter the following snippet to navigate to the project folder: ++ ```powershell + cd 1-Authentication\0-sign-in-vanillajs\App + ``` ++1. Install the project dependencies: ++ ```powershell + npm install + ``` ++## Configure the sample SPA ++1. Open `authConfig.js`. +1. Find `Enter_the_Tenant_Name_Here` and replace it with the name of your tenant. +1. In **Authority**, find `Enter_the_Tenant_Subdomain_Here` and replace it with the subdomain of your tenant. For example, if your tenant primary domain is *caseyjensen@onmicrosoft.com*, the value you should enter is *casyjensen*. +1. Save the file. ++## Run your project and sign in ++1. Open a new terminal and run the following command to start your express web server. ++ ```powershell + npm start + ``` ++1. Open a web browser and navigate to `http://localhost:3000/`. +1. Select **No account? Create one**, which starts the sign-up flow. +1. In the **Create account** window, enter the email address registered to your customer tenant, which starts the sign-up flow as a user for your application. +1. After entering a one-time passcode from the customer tenant, enter a new password and more account details, this sign-up flow is completed. +1. If a window appears prompting you to **Stay signed in**, choose either **Yes** or **No**. +1. The SPA will now display a button saying **Request Profile Information**. Select it to display profile data. ++ :::image type="content" source="media/how-to-spa-vanillajs-sign-in-sign-in-out/display-vanillajs-welcome.png" alt-text="Screenshot of sign in into a vanilla JS SPA." lightbox="media/how-to-spa-vanillajs-sign-in-sign-in-out/display-vanillajs-welcome.png"::: ++## Sign out of the application ++1. To sign out of the application, select **Sign out** in the navigation bar. +1. A window appears asking which account to sign out of. +1. Upon successful sign out, a final window appears advising you to close all browser windows. ++## Next steps ++Learn how to use the Microsoft Authentication Library (MSAL) for JavaScript to sign in users and acquire tokens to call Microsoft Graph. |
active-directory | How To Single Page App Vanillajs Sign In Sign Out | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-single-page-app-vanillajs-sign-in-sign-out.md | + + Title: Sign in users with a vanilla JavaScript single-page-application +description: Learn how to configure a vanilla JavaScript single-page app (SPA) to sign in and sign out users with your Azure Active Directory (AD) for customers tenant. +++++++++ Last updated : 05/23/2023+++#Customer intent: As a developer, I want to learn how to configure vanilla JavaScript single-page app (SPA) to sign in and sign out users with my Azure Active Directory (AD) for customers tenant. +++# Configure a Single-page application User Interface and Sign-In ++When authorization has been configured, the user interface can be created to allow users to sign in and sign out when the project is run. To build the user interface (UI) for the application, [Bootstrap](https://getbootstrap.com/) is used to create a responsive UI that contains a **Sign-In** and **Sign-Out** button. Next, you'll run the project and test the sign-in and sign-out functionality. ++## Prerequisites ++* Completion of the prerequisites and steps in [Create components for authentication and authorization](how-to-single-page-app-vanillajs-configure-authentication.md). ++## Create the *https://docsupdatetracker.net/index.html* file ++The main page of the application, *https://docsupdatetracker.net/index.html*, is the first page that is loaded when the application is started. It's also the page that is loaded when the user selects the **Sign Out** button. ++1. In the *public* folder, create a new file named *https://docsupdatetracker.net/index.html*. This file contains the HTML for the main page of the application. +1. Open *https://docsupdatetracker.net/index.html* and add the following code snippet: ++ ```html + <!DOCTYPE html> + <html lang="en"> + + <head> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no"> + <title>Microsoft identity platform</title> + <link rel="SHORTCUT ICON" href="./favicon.svg" type="image/x-icon"> + <link rel="stylesheet" href="./styles.css"> + + <!-- adding Bootstrap 5 for UI components --> + <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" + integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous"> + + <!-- msal.min.js can be used in the place of msal-browser.js --> + <script src="/msal-browser.min.js"></script> + </head> + + <body> + <nav class="navbar navbar-expand-sm navbar-dark bg-primary navbarStyle"> + <a class="navbar-brand" href="/">Microsoft identity platform</a> + <div class="navbar-collapse justify-content-end"> + <button type="button" id="signIn" class="btn btn-secondary" onclick="signIn()">Sign-in</button> + <button type="button" id="signOut" class="btn btn-success d-none" onclick="signOut()">Sign-out</button> + </div> + </nav> + <br> + <h5 id="title-div" class="card-header text-center">Vanilla JavaScript single-page application secured with MSAL.js + </h5> + <h5 id="welcome-div" class="card-header text-center d-none"></h5> + <br> + <div class="table-responsive-ms" id="table"> + <table id="table-div" class="table table-striped d-none"> + <thead id="table-head-div"> + <tr> + <th>Claim Type</th> + <th>Value</th> + <th>Description</th> + </tr> + </thead> + <tbody id="table-body-div"> + </tbody> + </table> + </div> + <!-- importing bootstrap.js and supporting js libraries --> + <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" + integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"> + </script> + <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js" + integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3" + crossorigin="anonymous"></script> + <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" + integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" + crossorigin="anonymous"></script> + + <!-- importing app scripts (load order is important) --> + <script type="text/javascript" src="./authConfig.js"></script> + <script type="text/javascript" src="./ui.js"></script> + <script type="text/javascript" src="./claimUtils.js"></script> + <!-- <script type="text/javascript" src="./authRedirect.js"></script> --> + <!-- uncomment the above line and comment the line below if you would like to use the redirect flow --> + <script type="text/javascript" src="./authPopup.js"></script> + </body> + + </html> + ``` ++1. Save the file. ++## Create the *signout.html* file ++1. In the *public* folder, create a new file named *signout.html*. This file contains the HTML for the sign-out page of the application. +1. Open *signout.html* and add the following code snippet: ++ ```html + <!DOCTYPE html> + <html lang="en"> + <head> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <title>Azure AD | Vanilla JavaScript SPA</title> + <link rel="SHORTCUT ICON" href="./favicon.svg" type="image/x-icon"> + + <!-- adding Bootstrap 4 for UI components --> + <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> + </head> + <body> + <div class="jumbotron" style="margin: 10%"> + <h1>Goodbye!</h1> + <p>You have signed out and your cache has been cleared.</p> + <a class="btn btn-primary" href="/" role="button">Take me back</a> + </div> + </body> + </html> + ``` ++1. Save the file. ++## Create the *ui.js* file ++1. In the *public* folder, create a new file named *ui.js*. This file contains the JavaScript code for the UI of the application. +1. Open *ui.js* and add the following code snippet: ++ ```javascript + // Select DOM elements to work with + const signInButton = document.getElementById('signIn'); + const signOutButton = document.getElementById('signOut'); + const titleDiv = document.getElementById('title-div'); + const welcomeDiv = document.getElementById('welcome-div'); + const tableDiv = document.getElementById('table-div'); + const tableBody = document.getElementById('table-body-div'); + + function welcomeUser(username) { + signInButton.classList.add('d-none'); + signOutButton.classList.remove('d-none'); + titleDiv.classList.add('d-none'); + welcomeDiv.classList.remove('d-none'); + welcomeDiv.innerHTML = `Welcome ${username}!`; + }; + + function updateTable(account) { + tableDiv.classList.remove('d-none'); + + const tokenClaims = createClaimsTable(account.idTokenClaims); + + Object.keys(tokenClaims).forEach((key) => { + let row = tableBody.insertRow(0); + let cell1 = row.insertCell(0); + let cell2 = row.insertCell(1); + let cell3 = row.insertCell(2); + cell1.innerHTML = tokenClaims[key][0]; + cell2.innerHTML = tokenClaims[key][1]; + cell3.innerHTML = tokenClaims[key][2]; + }); + }; + ``` ++1. Save the file. ++## Create the styles.css file ++1. In the *public* folder, create a new file named *styles.css*. This file contains the CSS code for the UI of the application. +1. Open *styles.css* and add the following code snippet: ++ ```css + .navbarStyle { + padding: .5rem 1rem !important; + } + + .table-responsive-ms { + max-height: 39rem !important; + padding-left: 10%; + padding-right: 10%; + } + ``` ++1. Save the file. ++## Run your project and sign in ++Now that all the required code snippets have been added, the application can be called and tested in a web browser. ++1. Open a new terminal and run the following command to start your express web server. ++ ```powershell + npm start + ``` ++1. Open a new private browser, and enter the application URI into the browser, `https://localhost:3000/`. +1. Select **No account? Create one**, which starts the sign-up flow. +1. In the **Create account** window, enter the email address registered to your Azure Active Directory (AD) for customers tenant, which starts the sign-up flow as a user for your application. +1. After entering a one-time passcode from the customer tenant, enter a new password and more account details, this sign-up flow is completed. + 1. If a window appears prompting you to **Stay signed in**, choose either **Yes** or **No**. +1. The SPA will now display a button saying **Request Profile Information**. Select it to display profile data. ++ :::image type="content" source="media/how-to-spa-vanillajs-sign-in-sign-in-out/display-vanillajs-welcome.png" alt-text="Screenshot of sign in into a vanilla JS SPA." lightbox="media/how-to-spa-vanillajs-sign-in-sign-in-out/display-vanillajs-welcome.png"::: ++## Sign out of the application ++1. To sign out of the application, select **Sign out** in the navigation bar. +1. A window appears asking which account to sign out of. +1. Upon successful sign out, a final window appears advising you to close all browser windows. ++## Next steps ++> [!div class="nextstepaction"] +> [Enable self-service password reset](./how-to-enable-password-reset-customers.md) |
active-directory | How To Single Page Application Angular Sample | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-single-page-application-angular-sample.md | + + Title: Sign in users in a sample Angular single-page application. +description: Learn how to configure a sample Angular Single Page Application (SPA) using Azure Active Directory for Customers ++++++++ Last updated : 05/23/2023+++#Customer intent: As a dev, devops, I want to learn about how to configure a sample Angular Single Page Application to sign in and sign out users with my Azure Active Directory (Azure AD) for customers tenant +++# Sign in users in a sample Angular single-page application ++This how-to guide uses a sample Angular single-page application (SPA) to demonstrate how to add authentication users into a SPA. The SPA enables users to sign in and sign out by using your Azure Active Directory (Azure AD) for customers tenant. The sample uses the [Microsoft Authentication Library for JavaScript (MSAL.js)](https://github.com/AzureAD/microsoft-authentication-library-for-js) to handle authentication. ++## Prerequisites ++* Although any IDE that supports vanilla JS applications can be used, **Visual Studio Code** is used for this guide. It can be downloaded from the [Downloads](https://visualstudio.microsoft.com/downloads) page. +* [Node.js](https://nodejs.org/en/download/). +* Azure AD for customers tenant. If you don't already have one, [sign up for a free trial](https://aka.ms/ciam-free-trial?wt.mc_id=ciamcustomertenantfreetrial_linkclick_content_cnl). +++## Register the SPA in the Microsoft Entra admin center +++## Grant API permissions +++## Create a user flow +++## Associate the SPA with the user flow +++## Clone or download sample SPA ++To get the sample SPA, you can choose one of the following options: ++* Clone the repository using Git: ++ ```powershell + git clone https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial.git + ``` ++* [Download the sample](https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial/archive/refs/heads/main.zip) ++If you choose to download the `.zip` file, extract the sample app file to a folder where the total length of the path is 260 or fewer characters. ++## Install project dependencies ++1. Open a terminal window in the root directory of the sample project, and enter the following snippet to navigate to the project folder: ++ ```powershell + cd 1-Authentication\2-sign-in-angular\SPA + ``` ++1. Install the project dependencies: ++ ```powershell + npm install + ``` ++## Configure the sample SPA ++1. Open `SPA\src\authConfig.js` and replace the following with the values obtained from the Microsoft Entra admin center + * `clientId` - The identifier of the application, also referred to as the client. Replace `Enter_the_Application_Id_Here` with the **Application (client) ID** value that was recorded earlier from the overview page of the registered application. + * `authority` - The identity provider instance and sign-in audience for the app. Replace `Enter_the_Tenant_Name_Here` with the name of your CIAM tenant. + * The *Tenant ID* is the identifier of the tenant where the application is registered. Replace the `_Enter_the_Tenant_Info_Here` with the **Directory (tenant) ID** value that was recorded earlier from the overview page of the registered application. +1. Save the file. ++## Run your project and sign in ++All the required code snippets have been added, so the application can now be called and tested in a web browser. ++1. Open a new terminal by selecting **Terminal** > **New Terminal**. +1. Run the following command to start your web server. ++ ```powershell + cd 1-Authentication\2-sign-in-angular\SPA + npm start + ``` ++1. Open a web browser and navigate to `http://localhost:4200/`. ++1. Sign-in with an account registered to the Azure AD for customers tenant. ++1. Once you successfully sign-in, the display name is shown next to the **Sign out** button. ++## Next steps ++Learn how to use the Microsoft Authentication Library (MSAL) for JavaScript to sign in users and acquire tokens to call Microsoft Graph. |
active-directory | How To Single Page Application React Prepare App | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-single-page-application-react-prepare-app.md | + + Title: Prepare a React Single Page App (SPA) for authentication +description: Learn how to prepare a React single-page app (SPA) for authentication and authorization with your Azure Active Directory (AD) for customers tenant. +++++++ Last updated : 05/23/2023++++#Customer intent: As a dev, devops, or IT admin, enable authentication in my own React ++# Prepare a React Single-page application for authentication ++After registration is complete, a React project can be created using an integrated development environment (IDE). This tutorial demonstrates how to create a React Single-page application using npm and create files needed for authentication and authorization. ++In this article, you learn how to: ++> [!div class="checklist"] +> * Create a new React project +> * Configure the settings for the application +> * Install identity and bootstrap packages +> * Add authentication code to the application ++## Prerequisites +* Completion of the prerequisites and steps in [Prepare your customer tenant for building a React Single Page App (SPA)](./how-to-single-page-application-react-prepare-tenant.md)) +* Although any IDE that supports React applications can be used, Visual Studio Code is used for this guide. This can be downloaded from the [Downloads](https://visualstudio.microsoft.com/downloads/) page. +* [Node.js](https://nodejs.org/en/download/) ++## Create a new React project ++Use the following tabs to create a React project within the IDE. ++1. Open Visual Studio Code, select **File** > **Open Folder...**. Navigate to and select the location in which to create your project. +1. Open a new terminal by selecting **Terminal** > **New Terminal**. +1. Run the following commands to create a new React project with the name *reactspalocal*, change to the new directory and start the React project. A web browser will open with the address `http://localhost:3000/` by default. The browser remains open and re-renders for every saved change. ++ ```powershell + npx create-react-app reactspalocal + cd reactspalocal + npm start + ``` ++## Install identity and bootstrap packages ++Identity related **npm** packages must be installed in the project to enable user authentication. For project styling, **Bootstrap** will be used. ++1. In the **Terminal** bar, select the **+** icon to create a new terminal. A separate terminal window will open with the previous node terminal continuing to run in the background. +1. Ensure that the correct directory is selected (*reactspalocal*) then enter the following into the terminal to install the relevant `msal` and `bootstrap` packages. ++ ```powershell + npm install @azure/msal-browser @azure/msal-react + npm install react-bootstrap bootstrap + ``` ++## Creating the authentication configuration file ++1. In the *src* folder, create a new file called *authConfig.js*. +1. Open *authConfig.js* and add the following code snippet: ++ ```javascript + /* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ ++ import { LogLevel } from '@azure/msal-browser'; ++ /** + * Configuration object to be passed to MSAL instance on creation. + * For a full list of MSAL.js configuration parameters, visit: + * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/configuration.md + */ ++ export const msalConfig = { + auth: { + clientId: 'Enter_the_Application_Id_Here', // This is the ONLY mandatory field that you need to supply. + authority: 'https://Enter_the_Tenant_Name_Here.ciamlogin.com/', // Replace "Enter_the_Tenant_Name_Here" with your tenant name + redirectUri: '/', // Points to window.location.origin. You must register this URI on Azure Portal/App Registration. + postLogoutRedirectUri: '/', // Indicates the page to navigate after logout. + navigateToLoginRequestUrl: false, // If "true", will navigate back to the original request location before processing the auth code response. + }, + cache: { + cacheLocation: 'sessionStorage', // Configures cache location. "sessionStorage" is more secure, but "localStorage" gives you SSO between tabs. + storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge + }, + system: { + loggerOptions: { + loggerCallback: (level, message, containsPii) => { + if (containsPii) { + return; + } + switch (level) { + case LogLevel.Error: + console.error(message); + return; + case LogLevel.Info: + console.info(message); + return; + case LogLevel.Verbose: + console.debug(message); + return; + case LogLevel.Warning: + console.warn(message); + return; + default: + return; + } + }, + }, + }, + }; ++ /** + * Scopes you add here will be prompted for user consent during sign-in. + * By default, MSAL.js will add OIDC scopes (openid, profile, email) to any login request. + * For more information about OIDC scopes, visit: + * https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#openid-connect-scopes + */ + export const loginRequest = { + scopes: [], + extraQueryParameters: { + dc: "ESTS-PUB-EUS-AZ1-FD000-TEST1" + } + }; + ``` ++1. Replace the following values with the values from the Azure portal. + - Replace `Enter_the_Application_Id_Here` with the **Application (client) ID** value that was recorded earlier from the overview page of the registered application. + - The *Tenant ID* is the identifier of the tenant where the application is registered. Replace the `_Enter_the_Tenant_Info_Here` with the **Directory (tenant) ID** value that was recorded earlier from the overview page of the registered application. +++## Modify index.js to include the authentication provider ++All parts of the app that require authentication must be wrapped in the [`MsalProvider`](/javascript/api/@azure/msal-react/#@azure-msal-react-msalprovider) component. You instantiate a [PublicClientApplication](/javascript/api/@azure/msal-browser/publicclientapplication) then pass it to `MsalProvider`. ++1. In the *src* folder, open *index.js* and replace the contents of the file with the following code snippet to use the `msal` packages and bootstrap styling: ++ :::code language="javascript" source="~/ms-identity-docs-code-javascript/react-spa/src/index.js" ::: +++## Next steps ++> [!div class="nextstepaction"] +> [Add Sign-in and Sign-out functionality to your app.](./how-to-single-page-application-react-sign-in-out.md) |
active-directory | How To Single Page Application React Prepare Tenant | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-single-page-application-react-prepare-tenant.md | + + Title: Prepare your tenant to use a React single-page app for authentication. +description: Learn how to configure your Azure Active Directory (AD) for customers tenant for authentication with a React single-page app (SPA). +++++++ Last updated : 05/23/2023++++#Customer intent: As a dev I want to prepare my customer tenant for building a Single Page App with React ++# Prepare your customer tenant for building a Single Page App (SPA) ++Before your applications can interact with Microsoft Identity Platform they must be registered in a customer tenant that you manage and must be associated with a user flow. ++In this article, you learn how to: ++> [!div class="checklist"] +> * Register your application and record identifiers. +> * Create a user flow to allow sign-up and sign-in. +> * Associate the user flow with your application. ++## Prerequisites ++An Azure subscription. If you don't have one, [create a free account](https://aka.ms/ciam-free-trial?wt.mc_id=ciamcustomertenantfreetrial_linkclick_content_cnl) before you begin. ++This Azure account must have permissions to manage applications. Any of the following Azure AD roles include the required permissions: +* Application administrator +* Application developer +* Cloud application administrator ++If you haven't already created your own customer tenant, [create one now](https://aka.ms/ciam-free-trial?wt.mc_id=ciamcustomertenantfreetrial_linkclick_content_cnl). You can use an existing customer tenant if you have one. ++## Register the application and record identifiers ++## Add a platform redirect URL ++## Grant sign-in permissions ++## Create a sign-in and sign-up user flow ++## Associate the application with your user flow ++## Next steps ++> [!div class="nextstepaction"] +> [Start building your React Single Page Application](./how-to-single-page-application-react-prepare-app.md) |
active-directory | How To Single Page Application React Sample | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-single-page-application-react-sample.md | + + Title: Sign in users in a sample React single-page application +description: Learn how to configure a sample React SPA to sign in and sign out users. ++++++++ Last updated : 05/23/2023+++#Customer intent: As a dev, devops, I want to learn about how to configure a sample React Single Page Application to sign in and sign out users with my Azure Active Directory (Azure AD) for customers tenant +++# Sign in users in a sample React single-page application ++This how-to guide uses a sample React single-page application (SPA) to demonstrate how to add authentication to a SPA. This SPA enables users to sign in and sign out by using you Azure Active Directory (Azure AD) for customers tenant. The sample uses the [Microsoft Authentication Library for JavaScript (MSAL.js)](https://github.com/AzureAD/microsoft-authentication-library-for-js) to handle authentication. ++## Prerequisites ++* Although any IDE that supports vanilla JS applications can be used, **Visual Studio Code** is used for this guide. It can be downloaded from the [Downloads](https://visualstudio.microsoft.com/downloads) page. +* [Node.js](https://nodejs.org/en/download/). +* Azure AD for customers tenant. If you don't already have one, [sign up for a free trial](https://aka.ms/ciam-free-trial?wt.mc_id=ciamcustomertenantfreetrial_linkclick_content_cnl). +++## Register the SPA in the Microsoft Entra admin center +++## Grant API permissions +++## Create a user flow +++## Associate the SPA with the user flow +++## Clone or download sample SPA ++To get the sample SPA, you can choose one of the following options: ++* Clone the repository using Git: ++ ```powershell + git clone https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial.git + ``` ++* [Download the sample](https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial/archive/refs/heads/main.zip) ++If you choose to download the `.zip` file, extract the sample app file to a folder where the total length of the path is 260 or fewer characters. ++## Install project dependencies ++1. Open a terminal window in the root directory of the sample project, and enter the following snippet to navigate to the project folder: ++ ```powershell + cd 1-Authentication\1-sign-in-react\SPA + ``` ++1. Install the project dependencies: ++ ```powershell + npm install + ``` ++## Configure the sample SPA ++1. Open _SPA\src\authConfig.js_ and replace the following with the values obtained from the Microsoft Entra admin center + * `clientId` - The identifier of the application, also referred to as the client. Replace `Enter_the_Application_Id_Here` with the **Application (client) ID** value that was recorded earlier from the overview page of the registered application. + * `authority` - The identity provider instance and sign-in audience for the app. Replace `Enter_the_Tenant_Name_Here` with the name of your Azure AD customer tenant. + * The *Tenant ID* is the identifier of the tenant where the application is registered. Replace the `_Enter_the_Tenant_Info_Here` with the **Directory (tenant) ID** value that was recorded earlier from the overview page of the registered application. +1. Save the file. ++## Run your project and sign in ++All the required code snippets have been added, so the application can now be called and tested in a web browser. ++1. Open a new terminal by selecting **Terminal** > **New Terminal**. +1. Run the following command to start your web server. ++ ```powershell + cd 1-Authentication\1-sign-in-react\SPA + npm start + ``` ++1. Open a web browser and navigate to `http://localhost:3000/`. ++1. Sign-in with an account registered to the Azure AD customer tenant. ++1. Once signed in the display name is shown next to the **Sign out** button. ++## Next steps ++Learn how to use the Microsoft Authentication Library (MSAL) for JavaScript to sign in users and acquire tokens to call Microsoft Graph. |
active-directory | How To Single Page Application React Sign In Out | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-single-page-application-react-sign-in-out.md | + + Title: Sign in users with a React single-page-application +description: Learn how to configure a React single-page app (SPA) to sign in and sign out users with your Azure Active Directory (AD) for customers tenant. +++++++ Last updated : 05/23/2023++++#Customer intent: As a developer I want to add sign-in and sign-out functionality to my React Single Page App +++# Create components for sign in and sign out in a React single page app ++Functional components are the building blocks of React apps. This tutorial demonstrates how functional components can be used to build the sign in and sign out experience in a React single-page app (SPA). The `useMsal` hook is used to retrieve an access token to allow user sign in. ++In this tutorial: ++> [!div class="checklist"] +> +> - Add components to the application +> - Create a way of displaying the user's profile information +> - Create a layout that displays the sign in and sign out experience +> - Add the sign in and sign out experiences ++## Prerequisites ++* Completion of the prerequisites and steps in [Prepare an Single Page Application for authentication](how-to-single-page-application-react-prepare-app.md). +++## Adding components to the application ++1. Navigate to the *src* folder in the left panel. +1. Right click on *src*, select **New Folder** and call it *components*. +1. Right click on *components* and using the **New File** option, create the following four files; + - *PageLayout.jsx* + - *SignInButton.jsx* + - *SignOutButton.jsx* ++++Once complete, you should have the following folder structure. ++```txt +reactspalocal/ +Γö£ΓöÇΓöÇ src/ +Γöé Γö£ΓöÇΓöÇ components/ +Γöé Γöé Γö£ΓöÇΓöÇ PageLayout.jsx +Γöé Γöé Γö£ΓöÇΓöÇ SignInButton.jsx +Γöé Γöé ΓööΓöÇΓöÇ SignOutButton.jsx +Γöé ΓööΓöÇΓöÇ ... +ΓööΓöÇΓöÇ ... +``` ++### Adding the page layout ++1. Open *PageLayout.jsx* and add the following code to render the page layout. The [useIsAuthenticated](/javascript/api/@azure/msal-react) hook returns whether or not a user is currently signed-in. ++ ```javascript + /* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ ++ import React from "react"; + import Navbar from "react-bootstrap/Navbar"; ++ import { useIsAuthenticated } from "@azure/msal-react"; + import { SignInButton } from "./SignInButton"; + import { SignOutButton } from "./SignOutButton"; ++ /** + * Renders the navbar component with a sign in or sign out button depending on whether or not a user is authenticated + * @param props + */ + export const PageLayout = (props) => { + const isAuthenticated = useIsAuthenticated(); ++ return ( + <> + <Navbar bg="primary" variant="dark" className="navbarStyle"> + <a className="navbar-brand" href="/"> + Microsoft Identity Platform + </a> + <div className="collapse navbar-collapse justify-content-end"> + {isAuthenticated ? <SignOutButton /> : <SignInButton />} + </div> + </Navbar> + <br /> + <br /> + <h5> + <center> + Welcome to the Microsoft Authentication Library For Javascript - + React SPA Tutorial + </center> + </h5> + <br /> + <br /> + {props.children} + </> + ); + }; + ``` ++1. Save the file. ++### Adding the sign in experience ++1. Open *SignInButton.jsx* and add the following code, which creates a button that signs in the user using either a pop-up or redirect. ++ ```javascript + import React from "react"; + import { useMsal } from "@azure/msal-react"; + import { loginRequest } from "../authConfig"; + import DropdownButton from "react-bootstrap/DropdownButton"; + import Dropdown from "react-bootstrap/Dropdown"; ++ /** + * Renders a drop down button with child buttons for logging in with a popup or redirect + * Note the [useMsal] package + */ ++ export const SignInButton = () => { + const { instance } = useMsal(); ++ const handleLogin = (loginType) => { + if (loginType === "popup") { + instance.loginPopup( + ...loginRequest, + redirectUri: '/redirect', + ).catch((e) => { + console.log(e); + }); + } else if (loginType === "redirect") { + instance.loginRedirect(loginRequest).catch((e) => { + console.log(e); + }); + } + }; + return ( + <DropdownButton + variant="secondary" + className="ml-auto" + drop="start" + title="Sign In" + > + <Dropdown.Item as="button" onClick={() => handleLogin("popup")}> + Sign in using Popup + </Dropdown.Item> + <Dropdown.Item as="button" onClick={() => handleLogin("redirect")}> + Sign in using Redirect + </Dropdown.Item> + </DropdownButton> + ); + }; + ``` ++1. Save the file. ++### Adding the sign out experience ++1. Open *SignOutButton.jsx* and add the following code, which creates a button that signs out the user using either a pop-up or redirect. ++ ```javascript + import React from "react"; + import { useMsal } from "@azure/msal-react"; + import DropdownButton from "react-bootstrap/DropdownButton"; + import Dropdown from "react-bootstrap/Dropdown"; ++ /** + * Renders a sign out button + */ + export const SignOutButton = () => { + const { instance } = useMsal(); ++ const handleLogout = (logoutType) => { + if (logoutType === "popup") { + instance.logoutPopup({ + postLogoutRedirectUri: "/", + mainWindowRedirectUri: "/", + }); + } else if (logoutType === "redirect") { + instance.logoutRedirect({ + postLogoutRedirectUri: "/", + }); + } + }; ++ return ( + <DropdownButton + variant="secondary" + className="ml-auto" + drop="start" + title="Sign Out" + > + <Dropdown.Item as="button" onClick={() => handleLogout("popup")}> + Sign out using Popup + </Dropdown.Item> + <Dropdown.Item as="button" onClick={() => handleLogout("redirect")}> + Sign out using Redirect + </Dropdown.Item> + </DropdownButton> + ); + }; + ``` ++## Change filename and add required imports ++By default, the application runs via a JavaScript file called *App.js*. It needs to be renamed to *App.jsx*, which is an extension that allows a developer to write HTML in React. ++1. Rename App.js to App.jsx. +1. Replace the existing imports with the following snippet; ++ ```javascript + import React, { useState } from 'react'; ++ import { PageLayout } from './components/PageLayout'; + import { loginRequest } from './authConfig'; ++ import { AuthenticatedTemplate, UnauthenticatedTemplate, useMsal } from '@azure/msal-react'; ++ import './App.css'; ++ import Button from 'react-bootstrap/Button'; + ``` ++### Replacing the default function to render authenticated information ++The following code will render based on whether the user is authenticated or not. Replace the default function `App()` to render authenticated information with the following code: ++```javascript +/** +* If a user is authenticated the ProfileContent component above is rendered. Otherwise a message indicating a user is not authenticated is rendered. +*/ +const MainContent = () => { + return ( + <div className="App"> + <AuthenticatedTemplate> + <ProfileContent /> + </AuthenticatedTemplate> + + <UnauthenticatedTemplate> + <h5> + <center> + Please sign-in to see your profile information. + </center> + </h5> + </UnauthenticatedTemplate> + </div> + ); +}; + +export default function App() { + return ( + <PageLayout> + <center> + <MainContent /> + </center> + </PageLayout> + ); +} +``` ++## Run your project and sign in ++All the required code snippets have been added, so the application can now be called and tested in a web browser. ++1. Open a new terminal by selecting **Terminal** > **New Terminal**. +1. Run the following command to start your express web server. ++ ```powershell + npm start + ``` ++1. Open a web browser and navigate to the port specified in [Prepare a Single-page application for authentication](./how-to-single-page-application-react-prepare-app.md). For example, http://localhost:3000/. +1. For the purposes of this how-to, choose the **Sign in using Popup** option. +1. After the popup window appears with the sign-in options, select the account with which to sign-in. +1. A second window may appear indicating that a code will be sent to your email address. If this happens, select **Send code**. Open the email from the sender Microsoft account team, and enter the 7-digit single-use code. Once entered, select **Sign in**. +1. For **Stay signed in**, you can select either **No** or **Yes**. +1. The app will now ask for permission to sign-in and access data. Select **Accept** to continue. ++## Sign out of the application ++1. To sign out of the application, select **Sign out** in the navigation bar. +1. A window appears asking which account to sign out of. +1. Upon successful sign out, a final window appears advising you to close all browser windows. ++## Next steps ++> [!div class="nextstepaction"] +> [Enable self-service password reset](./how-to-enable-password-reset-customers.md) |
active-directory | How To Use App Roles Customers | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-use-app-roles-customers.md | + + Title: Using role-based access control for apps +description: Learn how to define application roles for your customer-facing application and assign those roles to users and groups in customer tenants. +++++++ Last updated : 05/09/2023+++++# Using role-based access control for applications ++Role-based access control (RBAC) is a popular mechanism to enforce authorization in applications. When an organization uses RBAC, an application developer defines roles for the application. An administrator can then assign roles to different users and groups to control who has access to content and functionality in the application. ++Applications typically receive user role information as claims in a security token. Developers have the flexibility to provide their own implementation for how role claims are to be interpreted as application permissions. This interpretation of permissions can involve using middleware or other options provided by the platform of the applications or related libraries. ++## App roles ++Azure AD for customers allows you to define application roles for your application and assign those roles to users and groups. The roles you assign to a user or group define their level of access to the resources and operations in your application. ++When Azure AD for customers issues a security token for an authenticated user, it includes the names of the roles you've assigned the user or group in the security token's roles claim. An application that receives that security token in a request can then make authorization decisions based on the values in the roles claim. ++## Groups ++Developers can also use security groups to implement RBAC in their applications, where the memberships of the user in specific groups are interpreted as their role memberships. When an organization uses security groups, a groups claim is included in the token. The groups claim specifies the identifiers of all of the groups to which the user is assigned within the current customer tenant. ++## App roles vs. groups ++Though you can use app roles or groups for authorization, key differences between them can influence which you decide to use for your scenario. ++| App roles| Groups| +| -- | -- | +| They're specific to an application and are defined in the app registration. | They aren't specific to an app, but to a customer tenant. | +| Can't be shared across applications.| Can be used in multiple applications.| +| App roles are removed when their app registration is removed.| Groups remain intact even if the app is removed.| +| Provided in the `roles` claim.| Provided in `groups` claim. | ++## Declare roles for an application ++1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com) as a Conditional Access Administrator, Security Administrator, or Global Administrator. +1. Make sure you're using the directory that contains your Azure AD customer tenant: Select the **Directories + subscriptions** icon for switching directories in the toolbar, and then find your customer tenant in the list. If it's not the current directory, select **Switch**. +1. In the left menu, under **Applications**, select **App registrations**, and then select the application you want to define app roles in. +1. Select **App roles**, and then select **Create app role**. +1. In the **Create app role** pane, enter the settings for the role. The following table describes each setting and its parameters. + + | Field | Description | Example | + | -- | -- | -- | + | **Display name** | Display name for the app role that appears in the app assignment experiences. This value may contain spaces. | `Orders manager`| + | **Allowed member types** | Specifies whether this app role can be assigned to users, applications, or both. | `Users/Groups` | + | **Value** | Specifies the value of the roles claim that the application should expect in the token. The value should exactly match the string referenced in the application's code. The value can't contain spaces.| `Orders.Manager` | + | **Description** | A more detailed description of the app role displayed during admin app assignment experiences. | `Manage online orders.` | + | **Do you want to enable this app role?** | Specifies whether the app role is enabled. To delete an app role, deselect this checkbox and apply the change before attempting the delete operation.| _Checked_ | ++1. Select **Apply** to create the application role. ++### Assign users and groups to roles ++Once you've added app roles in your application, administrator can assign users and groups to the roles. Assignment of users and groups to roles can be done through the admin center, or programmatically using [Microsoft Graph](/graph/api/user-post-approleassignments). When the users assigned to the various app roles sign in to the application, their tokens have their assigned roles in the `roles` claim. ++To assign users and groups to application roles by using the Azure portal: ++1. In the left menu, under **Applications**, select **Enterprise applications**. +1. Select **All applications** to view a list of all your applications. If your application doesn't appear in the list, use the filters at the top of the **All applications** list to restrict the list, or scroll down the list to locate your application. +1. Select the application in which you want to assign users or security group to roles. +1. Under **Manage**, select **Users and groups**. +1. Select **Add user** to open the **Add Assignment** pane. +1. In the **Add Assignment** pane, select **Users and groups**. A list of users and security groups appears. You can select multiple users and groups in the list. +1. Once you've selected users and groups, choose **Select**. +2. In the **Add assignment** pane, choose **Select a role**. All the roles you defined for the application appear. +3. Select a role, and then choose **Select**. +4. Select **Assign** to finish the assignment of users and groups to the app. +5. Confirm that the users and groups you added appear in the **Users and groups** list. +6. To test your application, sign out and sign in again with the user you assigned the roles. ++## Add group claims to security tokens ++To emit the group membership claims in security tokens, follow these steps: ++1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com) as a Conditional Access Administrator, Security Administrator, or Global Administrator. +1. Make sure you're using the directory that contains your Azure AD customer tenant: Select the **Directories + subscriptions** icon for switching directories in the toolbar, and then find your customer tenant in the list. If it's not the current directory, select **Switch**. +1. In the left menu, under **Applications**, select **App registrations**, and then select the application in which you want to add the groups claim. +1. Under **Manage**, select **Token configuration**. +2. Select **Add groups claim**. +3. Select **group types** to include in the security tokens. +4. For the **Customize token properties by type**, select **Group ID**. +5. Select **Add** to add the groups claim. ++### Add members to a group ++Now that you've added app groups claim in your application, add users to the security groups. If you don't have security group, [create one](../../fundamentals/how-to-manage-groups.md#create-a-basic-group-and-add-members). ++1. In the left menu, select **Groups**, and then select **All groups**. +1. Select the group you want to manage. +1. Select **Members**. +1. Select **+ Add members**. +1. Scroll through the list or enter a name in the search box. You can choose multiple names. When you're ready, choose **Select**. +2. The **Group Overview** page updates to show the number of members who are now added to the group. +3. To test your application, sign out, and then sign in again with the user you added to the security group. ++## Groups and application roles support ++A customer tenant follows the Azure AD user and group management model and application assignment. Many of the core Azure AD features are being phased into customer tenants. ++The following table shows which features are currently available. ++| **Feature** | **Currently available?** | +| | | +| Create an application role for a resource | Yes, by modifying the application manifest | +| Assign an application role to users | Yes | +| Assign an application role to groups | Yes, via Microsoft Graph only | +| Assign an application role to applications | Yes, via application permissions | +| Assign a user to an application role | Yes | +| Assign an application to an application role (application permission) | Yes | +| Add a group to an application/service principal (groups claim) | Yes, via Microsoft Graph only | +| Create/update/delete a customer (local user) via the Microsoft Entra admin center | Yes | +| Reset a password for a customer (local user) via the Microsoft Entra admin center | Yes | +| Create/update/delete a customer (local user) via Microsoft Graph | Yes | +| Reset a password for a customer (local user) via Microsoft Graph | Yes, only if the service principal is added to the Global administrator role | +| Create/update/delete a security group via the Microsoft Entra admin center | Yes | +| Create/update/delete a security group via the Microsoft Graph API | Yes | +| Change security group members using the Microsoft Entra admin center | Yes | +| Change security group members using the Microsoft Graph API | Yes | +| Scale up to 50,000 users and 50,000 groups | Not currently available | +| Add 50,000 users to at least two groups | Not currently available | |
active-directory | How To User Flow Add Application | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-user-flow-add-application.md | + + Title: Add an application to a user flow +description: Learn how to add an application to a user flow to associate the application with a sign-up and sign-in user experience. Get guidance for updating the application configuration with application registration and tenant information. +++++++ Last updated : 05/09/2023++++++# Add your application to the user flow ++A user flow defines the authentication methods a customer can use to sign in to your application and the information they need to provide during sign-up. After you [create a user flow](how-to-user-flow-sign-up-sign-in-customers.md), you can associate it with one or more of the applications registered in your customer tenant. ++Because you might want the same sign-in experience for all of your customer-facing apps, you can add multiple apps to the same user flow. But only one sign-in experience is needed for an application, so you can add each application to just one user flow. ++## Prerequisites ++- **A sign-up and sign-in user flow**: Before you begin, [create the user flow](how-to-user-flow-sign-up-sign-in-customers.md) that you want to associate with your application. +- **Application registration**: In your customer tenant, [register your application](how-to-register-ciam-app.md). ++## Add the application to the user flow ++If you already registered your application in your customer tenant, you can add it to the new user flow. This step activates the sign-up and sign-in experience for users who visit your application. An application can have only one user flow, but a user flow can be used by multiple applications. ++1. In the [Microsoft Entra admin center](https://entra.microsoft.com/), select **Azure Active Directory** > **External Identities** > **User flows**. ++1. From the list, select your user flow. ++1. In the left menu, under **Use**, select **Applications**. ++1. Select **Add application**. ++ :::image type="content" source="media/how-to-user-flow-sign-up-sign-in-customers/assign-user-flow.png" alt-text="Screenshot showing selecting an application for the user flow."::: ++1. Select the application from the list. Or use the search box to find the application, and then select it. ++1. Choose **Select**. ++## Update the application code with your tenant information ++Now you need to update your application code configuration with the application ID from the application registration, your customer tenant name, and a client secret value. ++We have several samples and how-to guides that can help you update your application to integrate with a user flow, based on app type, platform, and language. See [Samples for customer identity and access management (CIAM) in Azure Active Directory](samples-ciam-all.md). ++## Next steps ++- If you selected email with password sign-in, [enable password reset](how-to-enable-password-reset-customers.md). +- Add [Google](how-to-google-federation-customers.md) or [Facebook](how-to-facebook-federation-customers.md) federation. +- [Add multifactor authentication (MFA) to a customer-facing app](how-to-multifactor-authentication-customers.md). |
active-directory | How To User Flow Sign Up Sign In Customers | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-user-flow-sign-up-sign-in-customers.md | + + Title: Create a sign-up and sign-in user flow +description: Learn how to create a sign-up and sign-in user flow for your customer-facing app. +++++++ Last updated : 05/09/2023++++#Customer intent: As a dev, devops, or it admin, I want to +++# Create a sign-up and sign-in user flow for customers ++You can create a simple sign-up and sign-in experience for your customers by adding a user flow to your application. The user flow defines the series of sign-up steps customers follow and the sign-in methods they can use (such as email and password, one-time passcodes, or social accounts from [Google](how-to-google-federation-customers.md) or [Facebook](how-to-facebook-federation-customers.md)). You can also collect information from customers during sign-up by selecting from a series of built-in user attributes or adding your own custom attributes. ++You can create multiple user flows if you have multiple applications that you want to offer to customers. Or, you can use the same user flow for many applications. However, an application can have only one user flow. ++## Prerequisites ++- **An Azure AD customer tenant**: Before you begin, create your Azure AD customer tenant. You can set up a [free trial](https://aka.ms/ciam-free-trial?wt.mc_id=ciamcustomertenantfreetrial_linkclick_content_cnl), or you can create a new customer tenant in Azure AD. +- **Email one-time passcode enabled (optional)**: If you want customers to use their email address and a one-time passcode each time they sign in, make sure Email one-time passcode is enabled at the tenant level (in the [Microsoft Entra admin center](https://entra.microsoft.com/), navigate to **External Identities** > **All Identity Providers** > **Email One-time-passcode**). +- **Custom attributes defined (optional)**: User attributes are values collected from the user during self-service sign-up. Azure AD comes with a built-in set of attributes, but you can [define custom attributes to collect during sign-up](how-to-define-custom-attributes.md). Define custom attributes in advance so they're available when you set up your user flow. Or you can create and add them later. +- **Identity providers defined (optional)**: You can set up federation with [Google](how-to-google-federation-customers.md) or [Facebook](how-to-facebook-federation-customers.md) in advance, and then select them as sign-in options as you create the user flow. ++## Create and customize a user flow ++Follow these steps to create a user flow a customer can use to sign in or sign up for an application. These steps describe how to add a new user flow, select the attributes you want to collect, and change the order of the attributes on the sign-up page. ++### To add a new user flow ++1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com/). ++1. If you have access to multiple tenants, use the **Directories + subscriptions** filter in the top menu to switch to your customer tenant. ++1. In the left pane, select **Azure Active Directory** > **External Identities** > **User flows**. ++1. Select **New user flow**. ++ :::image type="content" source="media/how-to-user-flow-sign-up-sign-in-customers/new-user-flow.png" alt-text="Screenshot of the new user flow option."::: ++1. On the **Create** page, enter a **Name** for the user flow (for example, "SignUpSignIn"). ++1. Under **Identity providers**, select the **Email Accounts** check box, and then select one of these options: ++ - **Email with password**: Allows new users to sign up and sign in using an email address as the sign-in name and a password as their first-factor authentication method. You can also configure options for showing, hiding, or customizing the self-service password reset link on the sign-in page ([learn more](how-to-customize-branding-customers.md#to-customize-self-service-password-reset)). ++ - **Email one-time passcode**: Allows new users to sign up and sign in using an email address as the sign-in name and email one-time passcode as their first-factor authentication method. ++ > [!NOTE] + > Other identity providers will be listed here only after you set up federation with them. For example, if you set up federation with [Google](how-to-google-federation-customers.md) or [Facebook](how-to-facebook-federation-customers.md), you'll be able to select them here ([learn more](concept-authentication-methods-customers.md)). ++ :::image type="content" source="media/how-to-user-flow-sign-up-sign-in-customers/create-user-flow-identity-providers.png" alt-text="Screenshot of Identity provider options on the Create a user flow page."::: ++1. Under **User attributes**, choose the attributes you want to collect from the user during sign-up. Select **Show more** to choose from the full list of attributes, including **Job Title**, **Display Name**, and **Postal Code**. This list also includes any custom attributes you defined. ++ :::image type="content" source="media/how-to-user-flow-sign-up-sign-in-customers/user-attributes.png" alt-text="Screenshot of the user attribute options on the Create a user flow page."::: ++1. Select **OK**. ++1. Select **Create** to create the user flow. ++### To select the layout of the attribute collection page (optional) ++You can choose the order in which the attributes are displayed on the sign-up page. ++1. In the [Microsoft Entra admin center](https://entra.microsoft.com/), select **Azure Active Directory**. ++1. In the left pane, select **Azure Active Directory** > **External Identities** > **User flows**. ++1. From the list, select your user flow. ++1. Under **Customize**, select **Page layouts**. ++ The attributes you chose to collect are listed. You can change the attribute label, type, and whether itΓÇÖs required. You can also change the order of display by selecting an attribute, and then select **Move up**, **Move down**, **Move to the top**, or **Move to the bottom**. ++ :::image type="content" source="media/how-to-user-flow-sign-up-sign-in-customers/page-layouts.png" alt-text="Screenshot of page layout options for a user flow."::: ++1. Select **Save**. ++1. Select **Create**. The new user flow appears in the user flows list. (You might need to refresh the page.) ++## Next steps ++- [Add your application to the user flow](how-to-user-flow-add-application.md) |
active-directory | How To Web App Dotnet Sample Sign In | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-web-app-dotnet-sample-sign-in.md | + + Title: Sign in users to a sample ASP.NET web application +description: Learn how to configure a sample ASP.NET web app to sign in and sign out users by using an Azure AD for customers tenant. +++++++++ Last updated : 05/22/2023+++#Customer intent: As a dev, devops, I want to learn about how to configure a sample ASP.NET web app to sign in and sign out users with my Azure Active Directory (Azure AD) for customers tenant +++# Sign in users for a sample ASP.NET web app in an Azure AD for customers tenant ++This how-to guide uses a sample ASP.NET web application to show the fundamentals of modern authentication using the [Microsoft Authentication Library for .NET](https://github.com/AzureAD/microsoft-authentication-library-for-dotnet) and [Microsoft Identity Web](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-node) for ASP.NET to handle authentication. ++In this article, you'll register a web application in the Microsoft Entra admin center and create a sign in and sign out user flow. You'll associate your web application with the user flow, download and update a sample ASP.NET web application using your own Azure Active Directory (Azure AD) for customers tenant details. Finally, you'll run and test the sample web application. ++## Prerequisites ++- Although any IDE that supports ASP.NET applications can be used, Visual Studio Code is used for this guide. It can be downloaded from the [Downloads](https://visualstudio.microsoft.com/downloads/) page. +- [.NET 7.0 SDK](https://dotnet.microsoft.com/download/dotnet). +- Azure AD for customers tenant. If you don't already have one, [sign up for a free trial](https://aka.ms/ciam-free-trial?wt.mc_id=ciamcustomertenantfreetrial_linkclick_content_cnl). ++## Register the web app +++## Define the platform and URLs +++## Add app client secret +++## Grant API permissions +++## Create a user flow +++## Associate the web application with the user flow +++## Clone or download sample web application ++To get the web app sample code, you can do either of the following tasks: ++- [Download the .zip file](https://github.com/Azure-Samples/ms-identity-ciam-dotnet-tutorial/archive/refs/heads/main.zip). Extract the sample app file to a folder where the total length of the path is 260 or fewer characters. +- Clone the sample web application from GitHub by running the following command: ++ ```powershell + git clone https://github.com/Azure-Samples/ms-identity-ciam-dotnet-tutorial.git + ``` ++## Configure the application ++1. Navigate to the root folder of the sample you have downloaded and directory that contains the ASP.NET sample app: ++ ```powershell + cd 1-Authentication\1-sign-in-aspnet-core-mvc + ``` ++1. Open the *appsettings.json* file. +1. In **Authority**, find `Enter_the_Tenant_Subdomain_Here` and replace it with the subdomain of your tenant. For example, if your tenant primary domain is *caseyjensen@onmicrosoft.com*, the value you should enter is *casyjensen*. +1. Find the `Enter_the_Application_Id_Here` value and replace it with the application ID (clientId) of the app you registered in the Microsoft Entra admin center. +1. Replace `Enter_the_Client_Secret_Here` with the client secret value you set up in [Add app client secret](#add-app-client-secret). ++## Run the code sample ++1. From your shell or command line, execute the following commands: ++ ```powershell + dotnet run + ``` ++1. Open your web browser and navigate to `https://localhost:7274`. ++1. Sign-in with an account registered to the customer tenant. ++1. Once signed in the display name is shown next to the **Sign out** button as shown in the following screenshot. ++ :::image type="content" source="media/how-to-web-app-dotnet-sign-in-sign-in-out/display-aspnet-welcome.png" alt-text="Screenshot of sign in into a ASP.NET web app."::: ++1. To sign-out from the application, select the **Sign out** button. ++## Next steps ++- [Enable password reset](how-to-enable-password-reset-customers.md) +- [Customize the default branding](how-to-customize-branding-customers.md) +- [Configure sign-in with Google](how-to-google-federation-customers.md) +- [Sign in users in your own ASP.NET web application by using an Azure AD for customers tenant](how-to-web-app-dotnet-sign-in-prepare-app.md) |
active-directory | How To Web App Dotnet Sign In Prepare App | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-web-app-dotnet-sign-in-prepare-app.md | + + Title: Prepare your application - Sign in users to an ASP.NET web app +description: Create and prepare an ASP.NET web app for authentication ++++++++ Last updated : 05/23/2023++#Customer intent: As a dev, devops, I want to learn about how to enable authentication in my own ASP.NET web app with Azure Active Directory (Azure AD) for customers tenant. +++# Prepare your application: Sign in users to an ASP.NET web app using an Azure Active Directory (AD) for customers tenant ++After registering an application and creating a user flow in a Azure Active Directory (AD) for customers tenant, an ASP.NET web application can be created using an integrated development environment (IDE). In this article, you'll create an ASP.NET project in your IDE, and configure it for authentication. ++## Prerequisites ++- Completion of the prerequisites and steps in [Sign in users in your own ASP.NET web application by using an Azure AD for customers tenant - Prepare your tenant](./how-to-web-app-dotnet-sign-in-prepare-tenant.md). +- Although any IDE that supports React applications can be used, Visual Studio Code is used for this guide. This can be downloaded from the [Downloads](https://visualstudio.microsoft.com/downloads/) page. +- [.NET 7.0 SDK](https://dotnet.microsoft.com/download/dotnet). ++## Create an ASP.NET project ++1. Open a terminal in your IDE and navigate to the location in which to create your project. +1. Enter the following command to make the project folder and create your project. ++ ```powershell + dotnet new mvc -n aspnet_webapp + ``` ++## Configure the application for authentication ++1. Open the *appsettings.json* file and replace the existing code with the following snippet. ++ ```json + { + "AzureAd": { + "Authority": "https://Enter_the_Tenant_Subdomain_Here.ciamlogin.com/", + "ClientId": "Enter_the_Application_Id_Here", + "ClientCredentials": [ + { + "SourceType": "ClientSecret", + "ClientSecret": "Enter_the_Client_Secret_Here" + } + ], + "CallbackPath": "/signin-oidc", + "SignedOutCallbackPath": "/signout-callback-oidc" + }, + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" + } + ``` ++ * `Authority` - The identity provider instance and sign-in audience for the app. Replace `Enter_the_Tenant_Subdomain_Here` with the sub-domain of your customer tenant. To find this, select **Overview** in the sidebar menu, then switch to the **Overview tab**. Find the **Primary domain**, in the form *caseyjensen.onmicrosoft.com*. The sub-domain is *caseyjensen*. + * `ClientId` - The identifier of the application, also referred to as the client. Replace the text in quotes with the **Application (client) ID** value that was recorded earlier from the overview page of the registered application. + * `ClientSecret` - The value of the client secret you created in [Prepare your tenant](./how-to-web-app-dotnet-sign-in-prepare-tenant.md). Replace the text in quotes with the client secret **value** in the Microsoft Entra admin center. + * `CallbackPath` - Is an identifier to help the server redirect a response to the appropriate application. + +1. Save changes to the file. +1. Open the *Properties/launchSettings.json* file. +1. In the `https` section of `profiles`, change the `https` URL in `applicationUrl` so that it reads `https://localhost:7274`. You used this URL to define the **Redirect URI**. +1. Save the changes to your file. ++## Next steps ++> [!div class="nextstepaction"] +> [Sign in and sign out](how-to-web-app-dotnet-sign-in-sign-out.md) |
active-directory | How To Web App Dotnet Sign In Prepare Tenant | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-web-app-dotnet-sign-in-prepare-tenant.md | + + Title: Prepare your tenant - Sign in users to an ASP.NET web app +description: Learn about how to prepare your Azure Active Directory (AD) for customers tenant for customers to sign in users in your own ASP.NET web application by using Azure AD for customers tenant. +++++++++ Last updated : 05/23/2023++#Customer intent: As a dev, devops, I want to learn about how to enable authentication in my own ASP.NET web app with Azure Active Directory (Azure AD) for customers tenant +++# Prepare your tenant: Sign in users to an ASP.NET web app using an Azure Active Directory (AD) for customers tenant ++This how-to guide demonstrates how to prepare your Azure Active Directory (Azure AD) for customers tenant for authentication. You'll register a web application in the Microsoft Entra admin center, and record its identifiers. You'll then create a sign in and sign out user flow in the Microsoft Entra admin center and associate your web application with the user flow. ++## Prerequisites ++- Azure AD for customers tenant. If you don't already have one, [sign up for a free trial](https://aka.ms/ciam-free-trial?wt.mc_id=ciamcustomertenantfreetrial_linkclick_content_cnl). ++If you have already registered a web application in the Microsoft Entra admin center, and associated it with a user flow, you can skip the steps in this article and move to [Prepare your application](how-to-web-app-dotnet-sign-in-prepare-app.md). ++## Register the web app +++## Define the platform and URLs +++## Add app client secret +++## Grant API permissions +++## Create a user flow +++## Associate the web application with the user flow +++## Next steps ++> [!div class="nextstepaction"] +> [Prepare your application](how-to-web-app-dotnet-sign-in-prepare-app.md) |
active-directory | How To Web App Dotnet Sign In Sign Out | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-web-app-dotnet-sign-in-sign-out.md | + + Title: Sign in and sign out users to an ASP.NET web application +description: Add sign in to an ASP.NET application and sign-in, sign out of an application ++++++++ Last updated : 05/23/2023++#Customer intent: As a dev, devops, I want to learn about how to enable authentication in my own ASP.NET web app with Azure Active Directory (Azure AD) for customers tenant. +++# Sign in and sign out: Sign in users in your own ASP.NET web application by using an Azure Active Directory (AD) for customers tenant ++In the [previous article](./how-to-web-app-dotnet-sign-in-prepare-app.md), an ASP.NET project was created and configured for authentication. This article demonstrates how to install the required packages, add code that implements authentication to the sign in and sign out experience. Finally, you'll sign in and sign out of the application. ++## Prerequisites ++- Completion of the prerequisites and steps in [Sign in users in your own ASP.NET web application by using an Azure AD for customers tenant - Prepare your application](./how-to-web-app-dotnet-sign-in-prepare-app.md). ++## Install identity packages ++Identity related NuGet packages must be installed in the project for authentication of users to be enabled. ++1. In the terminal, navigate to *aspnet_webapp*. +1. Enter the following commands to install the relevant NuGet package: ++ ```powershell + dotnet add package Microsoft.Identity.Web.UI + ``` ++## Add source code to Program and Controller ++1. In your code editor, open *Controllers\HomeController.cs* file. +1. Authorization needs to be added to the controller, add `Microsoft.AspNetCore.Authorization` so that the top of the file is identical to the following snippet: ++ ```cshtml + using System.Diagnostics; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using aspnet_webapp.Models; + ``` ++1. Additionally, add the `[Authorize]` attribute directly above the `HomeController` class definition, which ensures that only authenticated users can use the web app: ++ ```csharp + [Authorize] + ``` ++1. Open *Program.cs* and replace the contents of the file with the following snippet: ++ ```csharp + using Microsoft.AspNetCore.Authentication.OpenIdConnect; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc.Authorization; + using Microsoft.Identity.Web; + using Microsoft.Identity.Web.UI; + using System.IdentityModel.Tokens.Jwt; ++ var builder = WebApplication.CreateBuilder(args); ++ // Add services to the container. + builder.Services.AddControllersWithViews(); ++ // This is required to be instantiated before the OpenIdConnectOptions starts getting configured. + // By default, the claims mapping will map claim names in the old format to accommodate older SAML applications. + // For instance, 'http://schemas.microsoft.com/ws/2008/06/identity/claims/role' instead of 'roles' claim. + // This flag ensures that the ClaimsIdentity claims collection will be built from the claims in the token + JwtSecurityTokenHandler.DefaultMapInboundClaims = false; ++ // Sign-in users with the Microsoft identity platform + builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme) + .AddMicrosoftIdentityWebApp(builder.Configuration) + .EnableTokenAcquisitionToCallDownstreamApi() + .AddInMemoryTokenCaches(); ++ builder.Services.AddControllersWithViews(options => + { + var policy = new AuthorizationPolicyBuilder() + .RequireAuthenticatedUser() + .Build(); + options.Filters.Add(new AuthorizeFilter(policy)); + }).AddMicrosoftIdentityUI(); ++ var app = builder.Build(); ++ // Configure the HTTP request pipeline. + if (!app.Environment.IsDevelopment()) + { + app.UseExceptionHandler("/Home/Error"); + // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. + app.UseHsts(); + } ++ app.UseHttpsRedirection(); + app.UseStaticFiles(); ++ app.UseRouting(); + app.UseAuthorization(); ++ app.MapControllerRoute( + name: "default", + pattern: "{controller=Home}/{action=Index}/{id?}"); ++ app.Run(); ++ ``` ++## Add the sign-in and sign out experience ++After installing the NuGet packages and adding necessary code for authentication, we need to add the sign-in and sign out experiences. ++1. In your IDE, navigate to *Views/Shared*, and create a new file called *_LoginPartial.cshtml*. +1. Open *_LoginPartial.cshtml* and add the following code for adding the sign in and sign out experience. The code reads the ID token claims to check that the user is authenticated and uses `User.Claims` to extract ID token claims. In this case, `preferred_username`. ++ ```csharp + @using System.Security.Principal ++ <ul class="navbar-nav"> + @if (User.Identity is not null && User.Identity.IsAuthenticated) + { + <li class="nav-item"> + <span class="nav-link text-dark">Hello @User.Claims.First(c => c.Type == "preferred_username").Value!</span> + </li> + <li class="nav-item"> + <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignOut">Sign out</a> + </li> + } + else + { + <li class="nav-item"> + <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignIn">Sign in</a> + </li> + } + </ul> + ``` ++1. Next, add a reference to `_LoginPartial` in the *Layout.cshtml* file, which is located in the same folder. It's recommended to place this after the `navbar-collapse` class as shown in the following snippet: ++ ```html + <div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse"> + <partial name="_LoginPartial" /> + </div> + ``` ++## View ID token claims ++Open *Views/Home/Index.cshtml* and replace the contents of the file with the following snippet: ++```csharp +@{ +ViewData["Title"] = "Home Page"; +} ++<style> + table { + border-collapse: collapse; + width: 100%; + } + th, td { + text-align: justify; + padding: 8px; + border-bottom: 1px solid #ddd; + border-top: 1px solid #ddd; + } +</style> ++<div class="text-center"> + <h1 class="display-4">Welcome</h1> ++ @if (@User.Identity is not null && @User.Identity.IsAuthenticated) + { + <p>You are signed in! Below are the claims in your ID token. For more information, visit: <a href="https://learn.microsoft.com/azure/active-directory/develop/id-tokens">Microsoft identity platform ID tokens</a></p> + <table> + <tbody> + + @foreach (var item in @User.Claims) + { + <tr> + <td>@item.Type</td> + <td>@item.Value</td> + </tr> + } + </tbody> + </table> + } ++ <br /> + <p>Learn about <a href="https://learn.microsoft.com/azure/active-directory/develop/v2-overview">building web apps with Microsoft identity platform</a>.</p> +</div> +``` ++Using the token claims, the app checks that the user is authenticated using `User.Identity.IsAuthenticated`, and lists out the ID token claims by looping through each item in `User.Claims`, returning their `Type` and `Value`. ++## Sign-in to the application ++1. Start the application by typing the following in the terminal to launch the `https` profile in the *launchSettings.json* file. ++ ```powershell + dotnet run --launch-profile https + ``` ++1. Open a new private browser, and enter the application URI into the browser, for example `https://localhost:{port}`. +1. Select **No account? Create one**, which starts the sign-up flow. +1. In the **Create account** window, enter the email address registered to your customer tenant, which will start the sign-up flow as a user for your application. +1. After entering a one-time passcode from the customer tenant, enter a new password and more account details, this sign-up flow is completed. + 1. If a window appears prompting you to **Stay signed in**, choose either **Yes** or **No**. +1. The ASP.NET Welcome page appears in your browser as depicted in the following screenshot: ++ :::image type="content" source="media/how-to-web-app-dotnet-sign-in-sign-in-out/display-aspnet-welcome.png" alt-text="Screenshot of sign in into an ASP.NET web app."::: ++## Sign out of the application ++1. To sign out of the application, select **Sign out** in the navigation bar. +1. A window appears asking which account to sign out of. +1. Upon successful sign out, a final window appears advising you to close all browser windows. ++## Next steps ++> [!div class="nextstepaction"] +> [Enable self-service password reset](./how-to-enable-password-reset-customers.md) |
active-directory | How To Web App Node Sample Sign In Call Api | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-web-app-node-sample-sign-in-call-api.md | + + Title: Sign in users and call an API in sample Node.js web application +description: Learn how to configure a sample web app to sign in users and call an API. +++++++++ Last updated : 05/22/2023+++#Customer intent: As a dev, devops, I want to learn about how to configure a sample web app to sign in and sign out users with my CIAM tenant +++# Sign in users and call an API in sample Node.js web application ++This how-to guide uses a sample Node.js web application to show you how to add authentication and authorization. The sample application sign in users to a Node.js web app, which then calls a .NET API. You enable authentication and authorization by using your Azure Active Directory (Azure AD) for customers tenant details. The sample web application uses [Microsoft Authentication Library (MSAL)](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-node) for Node to handle authentication. ++In this article, you complete the following tasks: ++- Register and configure a web API in the Microsoft Entra admin center. ++- Register and configure a client web application in the Microsoft Entra admin center. ++- Create a sign-up and sign-in user flow in the Microsoft Entra admin center, and then associate a client web app with it. ++- Update a sample Node web application and ASP.NET web API to use your Azure AD for customers tenant details. ++- Run and test the sample web application and API. ++## Prerequisites ++- [Node.js](https://nodejs.org). ++- [.NET 7.0](https://dotnet.microsoft.com/learn/dotnet/hello-world-tutorial/install) or later. ++- [Visual Studio Code](https://code.visualstudio.com/download) or another code editor. ++- Azure AD for customers tenant. If you don't already have one, [sign up for free trial](https://aka.ms/ciam-free-trial?wt.mc_id=ciamcustomertenantfreetrial_linkclick_content_cnl). ++## Register a web application and a web API ++In this step, you create the web and the web API application registrations, and you specify the scopes of your web API. ++### Register a web API application +++### Configure API scopes ++This API needs to expose permissions, which a client needs to acquire for calling the API: +++### Configure app roles +++### Configure optional claims +++### Register the web app +++### Create a client secret +++### Grant API permissions to the web app +++## Create a user flow +++## Associate web application with the user flow +++## Clone or download sample web application and web API ++To get the web app and web API sample code, [download the .zip file](https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial/archive/refs/heads/main.zip) or clone the sample web application from GitHub by running the following command: ++```powershell +git clone https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial.git +``` ++If you choose to download the `.zip` file, extract the sample app file to a folder where the total length of the path is 260 or fewer characters. ++## Install project dependencies ++1. Open a console window, and change to the directory that contains the Node.js/Express sample app: ++ ```powershell + cd 2-Authorization\4-call-api-express\App + ``` +1. Run the following commands to install web app dependencies: ++ ```powershell + npm install && npm update + ``` ++## Configure the sample web app and API ++To use your app registration in the client web app sample: ++1. In your code editor, open `App\authConfig.js` file. ++1. Find the placeholder: ++ - `Enter_the_Application_Id_Here` and replace it with the Application (client) ID of the app you registered earlier. + + - `Enter_the_Tenant_Subdomain_Here` and replace it with the Directory (tenant) subdomain. For example, if your tenant primary domain is `contoso.onmicrosoft.com`, use `contoso`. If you don't have your tenant name, learn how to [read your tenant details](how-to-create-customer-tenant-portal.md#get-the-customer-tenant-details). + + - `Enter_the_Client_Secret_Here` and replace it with the app secret value you copied earlier. + + - `Enter_the_Web_Api_Application_Id_Here` and replace it with the Application (client) ID of the web API you copied earlier. ++To use your app registration in the web API sample: ++1. In your code editor, open `API\ToDoListAPI\appsettings.json` file. ++1. Find the placeholder: + + - `Enter_the_Application_Id_Here` and replace it with the Application (client) ID of the web API you copied. + + - `Enter_the_Tenant_Id_Here` and replace it with the Directory (tenant) ID you copied earlier. + + - `Enter_the_Tenant_Subdomain_Here` and replace it with the Directory (tenant) subdomain. For example, if your tenant primary domain is `contoso.onmicrosoft.com`, use `contoso`. If you don't have your tenant name, learn how to [read your tenant details](how-to-create-customer-tenant-portal.md#get-the-customer-tenant-details). +++## Run and test sample web app and API ++1. Open a console window, then run the web API by using the following commands: ++ ```powershell + cd 2-Authorization\4-call-api-express\API\ToDoListAPI + dotnet run + ``` ++1. Run the web app client by using the following commands: ++ ```powershell + cd 2-Authorization\4-call-api-express\App + npm start + ``` ++1. Open your browser, then go to http://localhost:3000. ++1. Select the **Sign In** button. You're prompted to sign in. ++ :::image type="content" source="media/how-to-web-app-node-sample-sign-in-call-api/web-app-node-sign-in.png" alt-text="Screenshot of sign in into a node web app."::: ++1. On the sign-in page, type your **Email address**, select **Next**, type your **Password**, then select **Sign in**. If you don't have an account, select **No account? Create one** link, which starts the sign-up flow. ++1. If you choose the sign-up option, after filling in your email, one-time passcode, new password and more account details, you complete the whole sign-up flow. You see a page similar to the following screenshot. You see a similar page if you choose the sign-in option. ++ :::image type="content" source="media/how-to-web-app-node-sample-sign-in-call-api/sign-in-call-api-view-to-do.png" alt-text="Screenshot of sign in into a node web app and call an API."::: ++### Call API ++1. To call the API, select the **View your todolist** link. You see a page similar to the following screenshot. + + :::image type="content" source="media/how-to-web-app-node-sample-sign-in-call-api/sign-in-call-api-manipulate-to-do.png" alt-text="Screenshot of manipulate API to do list."::: ++1. Manipulate the to-do list by creating and removing items. ++### How it works ++You trigger an API call each time you view, add or remove a task. Each time you trigger an API call, the client web app acquires an access token with the required permissions (scopes) to call an API endpoint. For example, to read a task, the client web app must acquire an access token with `ToDoList.Read` permission/scope. ++On the web API side, the endpoint must validate that the permissions/scopes present in the access token, which the client app presents, is valid. If the access token is valid, the endpoint responds to the HTTP request, otherwise, it responds with a `401 Unauthorized` HTTP error. ++## Next steps ++Learn how to: ++- [Sign in users and call an API in your own Node.js web application](how-to-web-app-node-sign-in-call-api-overview.md). By completing these steps, you build a web app and web API similar to the sample you've run. ++- [Enable password reset](how-to-enable-password-reset-customers.md). ++- [Customize the default branding](how-to-customize-branding-customers.md). ++- [Configure sign-in with Google](how-to-google-federation-customers.md). |
active-directory | How To Web App Node Sample Sign In | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-web-app-node-sample-sign-in.md | + + Title: Sign in users in a sample Node.js web application +description: Learn how to configure a sample web app to sign in and sign out users. +++++++++ Last updated : 05/22/2023+++#Customer intent: As a dev, devops, I want to learn about how to configure a sample Node.js web app to sign in and sign out users with my Azure Active Directory (Azure AD) for customers tenant +++# Sign in users in a sample Node.js web application ++This how-to guide uses a sample Node.js web application to show you how to add authentication to a web application. The sample application enables users to sign in and sign out. The sample web application uses [Microsoft Authentication Library for Node (MSAL Node)](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-node) for Node to handle authentication. ++In this article, you do the following tasks: ++- Register a web application in the Microsoft Entra admin center. ++- Create a sign-in and sign-out user flow in Microsoft Entra admin center. ++- Associate your web application with the user flow. ++- Update a sample Node.js web application using your own Azure Active Directory (Azure AD) for customers tenant details. ++- Run and test the sample web application. ++## Prerequisites ++- [Node.js](https://nodejs.org). ++- [Visual Studio Code](https://code.visualstudio.com/download) or another code editor. ++- Azure AD for customers tenant. If you don't already have one, [sign up for a free trial](https://aka.ms/ciam-free-trial?wt.mc_id=ciamcustomertenantfreetrial_linkclick_content_cnl). ++<!--Awaiting this link http://developer.microsoft.com/identity/customers to go live on Developer hub--> +++## Register the web app +++## Add app client secret +++## Grant API permissions ++Since this app signs-in users, add delegated permissions: +++## Create a user flow +++## Associate the web application with the user flow +++## Clone or download sample web application ++To get the web app sample code, you can do either of the following tasks: ++- [Download the .zip file](https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial/archive/refs/heads/main.zip) or clone the sample web application from GitHub by running the following command: ++ ```console + git clone https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial.git + ``` +If you choose to download the *.zip* file, extract the sample app file to a folder where the total length of the path is 260 or fewer characters. ++## Install project dependencies ++1. Open a console window, and change to the directory that contains the Node.js sample app: ++ ```console + cd 1-Authentication\5-sign-in-express\App + ``` +1. Run the following commands to install app dependencies: ++ ```console + npm install && npm update + ``` ++## Configure the sample web app ++1. In your code editor, open *App\authConfig.js* file. ++1. Find the placeholder: + + 1. `Enter_the_Application_Id_Here` and replace it with the Application (client) ID of the app you registered earlier. + + 1. `Enter_the_Tenant_Subdomain_Here` and replace it with the Directory (tenant) subdomain. For example, if your tenant primary domain is `contoso.onmicrosoft.com`, use `contoso`. If you don't have your tenant name, learn how to [read your tenant details](how-to-create-customer-tenant-portal.md#get-the-customer-tenant-details). + + 1. `Enter_the_Client_Secret_Here` and replace it with the app secret value you copied earlier. ++## Run and test sample web app ++You can now test the sample Node.js web app. You need to start the Node.js server and access it through your browser at `http://localhost:3000`. ++1. In your terminal, run the following command: ++ ```console + npm start + ``` ++1. Open your browser, then go to http://localhost:3000. You should see the page similar to the following screenshot: ++ :::image type="content" source="media/how-to-web-app-node-sample-sign-in/web-app-node-sign-in.png" alt-text="Screenshot of sign in into a node web app."::: ++1. After the page completes loading, select **Sign in** link. You're prompted to sign in. ++1. On the sign-in page, type your **Email address**, select **Next**, type your **Password**, then select **Sign in**. If you don't have an account, select **No account? Create one** link, which starts the sign-up flow. ++1. If you choose the sign-up option, after filling in your email, one-time passcode, new password and more account details, you complete the whole sign-up flow. You see a page similar to the following screenshot. You see a similar page if you choose the sign-in option. ++ :::image type="content" source="media/how-to-web-app-node-sample-sign-in/web-app-node-view-claims.png" alt-text="Screenshot of view ID token claims."::: ++1. Select **Sign out** to sign the user out of the web app or select **View ID token claims** to view ID token claims returned by Microsoft Entra. ++### How it works ++When users select the **Sign in** link, the app initiates an authentication request and redirects users to Azure AD for customers. On the sign-in or sign-up page that appears, once a user successfully signs in or creates an account, Azure AD for customers returns an ID token to the app. The app validates the ID token, reads the claims, and returns a secure page to the users. ++When the users select the **Sign out** link, the app clears its session, the redirect the user to Azure AD for customers sign-out endpoint to notify it that the user has signed out. ++If you want to build an app similar to the sample you've run, complete the steps in [Sign in users in your own Node.js web application](how-to-web-app-node-sign-in-overview.md) article. ++## Next steps ++You may want to: ++- [Enable password reset](how-to-enable-password-reset-customers.md) ++- [Customize the default branding](how-to-customize-branding-customers.md) + +- [Configure sign-in with Google](how-to-google-federation-customers.md) ++- [Sign in users in your own Node.js web application](how-to-web-app-node-sign-in-overview.md) |
active-directory | How To Web App Node Sign In Call Api Call Api | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-web-app-node-sign-in-call-api-call-api.md | + + Title: Sign in users and call an API in a Node.js web application - call an API +description: Learn how to call a protected API in your own Node.js web application. +++++++++ Last updated : 05/22/2023++++# Sign in users and call an API in a Node.js web application - call an API ++In this article, you learn how to call the ASP.NET API from your Node.js client web app using the access token you've acquired in [Acquire access token](how-to-web-app-node-sign-in-call-api-sign-in-acquire-access-token.md#acquire-access-token). ++You add code in *routes/todos.js*, *controller/todolistController.js* and *fetch.js* files to show how the app uses the access token to call an API. +++## Update code ++1. In your code editor, open *routes/todos.js* file, then add the following code: ++ ```javascript + const express = require('express'); + const router = express.Router(); + + const toDoListController = require('../controller/todolistController'); + const authProvider = require('../auth/AuthProvider'); + const { protectedResources } = require('../authConfig'); + + // custom middleware to check auth state + function isAuthenticated(req, res, next) { + if (!req.session.isAuthenticated) { + return res.redirect('/auth/signin'); // redirect to sign-in route + } + + next(); + } + // isAuthenticated checks if user is authenticated + router.get('/',isAuthenticated, authProvider.getToken(protectedResources.toDoListAPI.scopes.read),toDoListController.getToDos); + + router.delete('/', isAuthenticated,authProvider.getToken(protectedResources.toDoListAPI.scopes.write),toDoListController.deleteToDo); + + router.post('/',isAuthenticated,authProvider.getToken(protectedResources.toDoListAPI.scopes.write),toDoListController.postToDo); + + module.exports = router; + ``` ++ This file contains express routes for create, read and delete resource in the protected API. Each route uses three middleware functions, which execute in that sequence: ++ - `isAuthenticated`, checks whether the user is authenticated. + + - `getToken` requests an access token. You defined this function earlier in [Acquire access token](how-to-web-app-node-sign-in-call-api-sign-in-acquire-access-token.md#acquire-access-token). For example, the create resource route (POST request) requests an access token with read and write permissions. + + - Finally, the `postToDo` or `deleteToDo` `getToDos` methods handles the actual logic for manipulating the resource. These functions are defined in *controller/todolistController.js* file. ++1. In your code editor, open *controller/todolistController.js* file, then add the following code: ++ ```javascript + const { callEndpointWithToken } = require('../fetch'); + const { protectedResources } = require('../authConfig'); + + exports.getToDos = async (req, res, next) => { + try { + const todoResponse = await callEndpointWithToken( + protectedResources.toDoListAPI.endpoint, + req.session.accessToken, + 'GET' + ); + res.render('todos', { isAuthenticated: req.session.isAuthenticated, todos: todoResponse.data }); + } catch (error) { + next(error); + } + }; + + exports.postToDo = async (req, res, next) => { + try { + if (!!req.body.description) { + let todoItem = { + description: req.body.description, + }; + + await callEndpointWithToken( + protectedResources.toDoListAPI.endpoint, + req.session.accessToken, + 'POST', + todoItem + ); + res.redirect('todos'); + } else { + throw { error: 'empty request' }; + } + } catch (error) { + next(error); + } + }; + + exports.deleteToDo = async (req, res, next) => { + try { + await callEndpointWithToken( + protectedResources.toDoListAPI.endpoint, + req.session.accessToken, + 'DELETE', + req.body._id + ); + res.redirect('todos'); + } catch (error) { + next(error); + } + }; + ``` ++ Each of these functions collects all the information required to call an API. It then delegates the work to the `callEndpointWithToken` function and waits for a response. The `callEndpointWithToken` function is defined in the *fetch.js* file. For example, to create a resource in the API, the `postToDo` function passes an endpoint, an access token, an HTTP method and a request body to the `callEndpointWithToken` function and waits for a response. It then redirects the user to the *todo.hbs* view to show all tasks. ++ 1. In your code editor, open *fetch.js* file, then add the following code: + + ```javascript + const axios = require('axios'); + + /** + * Makes an Authorization "Bearer" request with the given accessToken to the given endpoint. + * @param endpoint + * @param accessToken + * @param method + */ + const callEndpointWithToken = async (endpoint, accessToken, method, data = null) => { + const options = { + headers: { + Authorization: `Bearer ${accessToken}`, + }, + }; + + switch (method) { + case 'GET': + return await axios.get(endpoint, options); + case 'POST': + return await axios.post(endpoint, data, options); + case 'DELETE': + return await axios.delete(endpoint + `/${data}`, options); + default: + return null; + } + }; + + module.exports = { + callEndpointWithToken, + }; + ``` ++ This function makes the actual API call. It makes any HTTP request as long as you specify the HTTP method. ++ Notice how you include the access token as a bearer token in the HTTP request header: + + ```javascript + //... + headers: { + Authorization: `Bearer ${accessToken}`, + } + //... + ``` ++## Finalize your web app ++1. In your code editor, open *app.js* file, then add the code from [app.js](https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial/blob/main/2-Authorization/4-call-api-express/App/app.js) to it. ++1. In your code editor, open *server.js* file, then add the code from [server.js](https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial/blob/main/2-Authorization/4-call-api-express/App/server.js) to it. ++1. In your code editor, open *package.json* file, then update the `scripts` property to: + + ```json + "scripts": { + "start": "node server.js" + } + ``` + +## Run and test web app and API ++At this point, you're ready to test your client web app and web API. ++1. Use the steps you learned in [Secure an ASP.NET web API](how-to-protect-web-api-dotnet-core-overview.md) article to start your web API. Your web API is now ready to serve client requests. ++1. In your terminal, make sure you're in the project folder that contains your client web app such as `ciam-sign-in-call-api-node-express-web-app`, then run the following command: ++ ```console + npm start + ``` + Your client web app starts. ++1. Use the steps in [Run and test sample web app and API](how-to-web-app-node-sample-sign-in-call-api.md#run-and-test-sample-web-app-and-api) to demonstrate how the client app calls the web API. ++## Next steps ++You may want to: ++- [Customize the default branding](how-to-customize-branding-customers.md) ++- [Configure sign-in with Google](how-to-google-federation-customers.md) ++- [Sign in users in your own Node.js web application](how-to-web-app-node-sign-in-overview.md) |
active-directory | How To Web App Node Sign In Call Api Overview | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-web-app-node-sign-in-call-api-overview.md | + + Title: Sign in users and call an API in a Node.js web application +description: Learn how to sign in users and call an API in your own Node.js web application +++++++++ Last updated : 05/22/2023+++#Customer intent: As a dev, I want to learn about how to Sign in users and call an API in your own Node.js web application by using Azure Active Directory (Azure AD) for customers tenant. +++# Sign in users and call an API in a Node.js web application ++In this article, you learn how to create your Node.js web app that calls your web API. You build the web API by using ASP.NET. You secure the web API by using Azure Active Directory (AD) for customers. To authorize access to the web API, you must serve requests that include a valid access token, which is issued by Azure AD for customers itself. ++To simplify adding authentication and authorization, the Node.js client web app and .NET web API use [Microsoft Authentication Library for Node (MSAL Node)](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-node) and [Microsoft Identity Web](../../develop/microsoft-identity-web.md) respectively. ++We've organized the content into four separate articles so it's easy for you to follow: ++- [Prepare your Azure AD for customers tenant](how-to-web-app-node-sign-in-call-api-prepare-tenant.md) guides you how to register your API, client web app and configure user flows in the Microsoft Entra admin center. ++- [Prepare your web application and API](how-to-web-app-node-sign-in-call-api-prepare-app.md) guides you how to set up your Node.js client app and web API. ++- [Sign-in and acquire access token](how-to-web-app-node-sign-in-call-api-sign-in-acquire-access-token.md) guides you how to add sign in, then request for an access token with the required permissions/scopes. ++- [Call API](how-to-web-app-node-sign-in-call-api-call-api.md) guides you how to make an HTTP call to the web API by using the access token as a bearer token. ++## Overview ++Token-based authentication ensures that requests to a web API include a valid access token. ++The client web app completes the following events: ++- It authenticates users with Azure AD for customers. ++- It acquires an access token with the required permissions (scopes) for the web API endpoint. ++- It passes the access token as a bearer token in the authentication header of the HTTP request. It uses the format: ++ ```http + Authorization: Bearer <token> + ``` +The web API completes the following events: ++- It reads the bearer token from the authorization header of the HTTP request. ++- It validates the [access token](../../develop/access-tokens.md#validate-tokens). ++- It validates the permissions (scopes) in the token. ++- If the access token is valid, the endpoint responds to the HTTP request, otherwise, it responds with a `401 Unauthorized` HTTP error. ++## Prerequisites ++- [Node.js](https://nodejs.org). ++- [.NET 7.0](https://dotnet.microsoft.com/learn/dotnet/hello-world-tutorial/install) or later. ++- [Visual Studio Code](https://code.visualstudio.com/download) or another code editor. ++- Azure AD for customers tenant. If you don't already have one, [sign up for free trial](https://aka.ms/ciam-free-trial?wt.mc_id=ciamcustomertenantfreetrial_linkclick_content_cnl). +++If you want to run a sample Node.js web application that calls a sample web API to get a feel of how things work, complete the steps in [Sign in users and call an API in sample Node.js web application](how-to-web-app-node-sample-sign-in-call-api.md). ++## Next steps ++Next, learn how to prepare your Azure AD for customers tenant. ++> [!div class="nextstepaction"] +> [Prepare your Azure AD for customers tenant for authentication >](how-to-web-app-node-sign-in-call-api-prepare-tenant.md) |
active-directory | How To Web App Node Sign In Call Api Prepare App | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-web-app-node-sign-in-call-api-prepare-app.md | + + Title: Sign in users and call an API a Node.js web application - prepare client app and API +description: Learn about how to prepare your Node.js client web app and ASP.NET web API. The app you here prepare is what you configure later to sign in users, then call an API. +++++++++ Last updated : 05/22/2023++++# Sign in users and call an API a Node.js web application - prepare client app and API ++In this article, you create app projects for both the client web app and web API. Later, you add authentication and authorization to this app. You create app projects for an ASP.NET web API and a Node.js web app client. ++## Prerequisite ++- Install [.NET SDK](https://dotnet.microsoft.com/learn/dotnet/hello-world-tutorial/install) v7 or later in your computer. ++## Build ASP.NET web API ++You must first create a protected web API, which the client web calls by presenting a valid token. To do so, complete the steps in [Secure an ASP.NET web API](how-to-protect-web-api-dotnet-core-overview.md) article. In this article, you learn how to create and protect ASP.NET API endpoints, and run and test the API. ++Before you proceed to this article, make sure you've [registered a web API app in Microsoft Entra admin center](how-to-web-app-node-sign-in-call-api-prepare-tenant.md#register-a-web-application-and-a-web-api). +++## Prepare Node.js client web app ++In this step, you prepare the Node.js client web app that calls the ASP.NET web API. ++### Create the Node.js project ++Create a folder to host your node application, such as `ciam-sign-in-call-api-node-express-web-app`: ++1. In your terminal, change directory into your Node web app folder, such as `cd ciam-sign-in-call-api-node-express-web-app`, then run `npm init -y`. This command creates a default package.json file for your Node.js project. This command creates a default `package.json` file for your Node.js project. ++1. Create more folders and files to achieve the following project structure: ++ ``` + ciam-sign-in-call-api-node-express-web-app/ + Γö£ΓöÇΓöÇ server.js + ΓööΓöÇΓöÇ app.js + ΓööΓöÇΓöÇ authConfig.js + ΓööΓöÇΓöÇ fetch.js + ΓööΓöÇΓöÇ package.json + ΓööΓöÇΓöÇ auth/ + ΓööΓöÇΓöÇ AuthProvider.js + ΓööΓöÇΓöÇ controller/ + ΓööΓöÇΓöÇ authController.js + ΓööΓöÇΓöÇ todolistController.js + ΓööΓöÇΓöÇ routes/ + ΓööΓöÇΓöÇ auth.js + ΓööΓöÇΓöÇ index.js + ΓööΓöÇΓöÇ todos.js + ΓööΓöÇΓöÇ users.js + ΓööΓöÇΓöÇ views/ + ΓööΓöÇΓöÇ layouts.hbs + ΓööΓöÇΓöÇ error.hbs + ΓööΓöÇΓöÇ id.hbs + ΓööΓöÇΓöÇ index.hbs + ΓööΓöÇΓöÇ todos.hbs + ΓööΓöÇΓöÇ public/stylesheets/ + ΓööΓöÇΓöÇ style.css + ``` ++## Install app dependencies ++In your terminal, install `axios`, `cookie-parser`, `dotenv`, `express`, `express-session`, `hbs`, `http-errors`, `morgan`, `body-parser`, `method-override` and `@azure/msal-node` packages by running the following commands: ++```console + npm install express dotenv hbs express-session axios cookie-parser http-errors body-parser morgan method-override @azure/msal-node +``` ++### Build app UI components +++1. In your code editor, open *views/index.hbs* file, then add the following code: ++ ```html + <h1>{{title}}</h1> + {{#if isAuthenticated }} + <p>Hi {{username}}!</p> + <a href="/users/id">View your ID token claims</a> + <br> + <a href="/todos">View your todolist</a> + <br> + <a href="/auth/signout">Sign out</a> + {{else}} + <p>Welcome to {{title}}</p> + <a href="/auth/signin">Sign in</a> + {{/if}} + ``` + In this view, if the user is authenticated, we show their username. We also show links to allow the user to visit `/auth/signout`, `/todos` and `/users/id` endpoints, otherwise, user needs to visit the `/auth/signin` endpoint to sign in. We define the express routes for these endpoints later in this article. ++1. In your code editor, open `views/id.hbs` file, then add the following code: ++ ```html + <h1>Azure AD</h1> + <h3>ID Token</h3> + <table> + <tbody> + {{#each idTokenClaims}} + <tr> + <td>{{@key}}</td> + <td>{{this}}</td> + </tr> + {{/each}} + </tbody> + </table> + <a href="/">Go back</a> + ``` + We use this view to display ID token claims that Azure AD for customers returns to this app after a user successfully signs in. ++1. In your code editor, open *views/error.hbs* file, then add the following code: ++ ```html + <h1>{{message}}</h1> + <h2>{{error.status}}</h2> + <pre>{{error.stack}}</pre> + ``` ++ We use this view to display any errors that occur when the app runs. ++1. In your code editor, open *views/layout.hbs* file, then add the following code: ++ ```html + <!DOCTYPE html> + <html> + <head> + <title>{{title}}</title> + <link rel='stylesheet' href='/stylesheets/style.css' /> + </head> + <body> + {{{body}}} + </body> + </html> + ``` + The `layout.hbs` file is in the layout file. It contains the HTML code that we require throughout the application view. ++1. In your code editor, open *views/todos.hbs* file, then add the following code: ++ ```html + <h1>Todolist</h1> + <div> + <form action="/todos" method="POST"> + <input type="text" name="description" class="form-control" placeholder="Enter a task" aria-label="Enter a task" + aria-describedby="button-addon"> + <button type="submit" id="button-addon">Add</button> + </form> + </div> + <div class="row" style="margin: 10px;"> + <ol id="todoListItems" class="list-group"> + {{#each todos}} + <li class="todoListItem" id="todoListItem"> + <span>{{description}}</span> + <form action='/todos?_method=DELETE' method='POST'> + <span><input type='hidden' name='_id' value='{{id}}'></span> + <span><button type='submit'>Remove</button></span> + </form> + </li> + {{/each}} + </ol> + </div> + <a href="/">Go back</a> + ``` ++ This view allows the user to perform tasks that initiate an API call. For instance, after a user signs in, and the app acquires an access token, the user can create a resource (task) in the API app by submitting a form. ++1. In your code editor, open *public/stylesheets/style.css*, file, then add the following code: ++ ```css + body { + padding: 50px; + font: 14px "Lucida Grande", Helvetica, Arial, sans-serif; + } + + a { + color: #00B7FF; + } + ``` +++## Next steps ++Next, learn how to sign-in users and acquire an access token: ++> [!div class="nextstepaction"] +> [Sign-in users and acquire an access token >](how-to-web-app-node-sign-in-call-api-sign-in-acquire-access-token.md) |
active-directory | How To Web App Node Sign In Call Api Prepare Tenant | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-web-app-node-sign-in-call-api-prepare-tenant.md | + + Title: Sign in users and call an API in a Node.js web application - prepare your tenant +description: Learn about how to prepare your Azure Active Directory (Azure AD) tenant for customers to sign in users and call an API in your own Node.js web application. +++++++++ Last updated : 05/22/2023++++# Sign in users and call an API in a Node.js web application - prepare your tenant ++In this article, you prepare your Azure Active Directory (Azure AD) for customers tenant for authentication and authorization. To prepare your tenant, you do the following tasks: ++- Register a web API and configure permissions/scopes in the Microsoft Entra admin center. ++- Register a client web application and grant it API permissions in the Microsoft Entra admin center. ++- Create a sign in and sign out user flow in Microsoft Entra admin center. ++- Associate your client web application with the user flow. ++After you complete the tasks, you collect: ++- *Application (client) ID* for your client web app and one for your web API. ++- A *Client secret* for your client web app. ++- A *Directory (tenant) ID* for your Azure AD for customers tenant. ++- Web API permissions/scopes. ++- App permissions/roles. ++If you've already registered a client web application and a web API in the Microsoft Entra admin center, and created a sign in and sign up user flow, you can skip the steps in this article, then proceed to [Prepare your web application and API](how-to-web-app-node-sign-in-call-api-prepare-app.md). ++## Register a web application and a web API ++In this step, you create the web and the web API application registrations, and you specify the scopes of your web API. ++### Register a web API application +++### Configure API scopes +++### Configure app roles +++### Configure optional claims +++### Register the web app +++### Create a client secret +++### Grant API permissions to the web app +++## Create a user flow +++## Associate web application with the user flow ++++## Next steps ++Next, learn how to prepare your web application and API. ++> [!div class="nextstepaction"] +> [Start building your web application and API >](how-to-web-app-node-sign-in-call-api-prepare-app.md) |
active-directory | How To Web App Node Sign In Call Api Sign In Acquire Access Token | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-web-app-node-sign-in-call-api-sign-in-acquire-access-token.md | + + Title: Sign in users and call an API in a Node.js web application - acquire an access token +description: Learn how to sign-in users and acquire an access token for calling an API in your own Node.js web application. +++++++++ Last updated : 05/22/2023++++# Sign in users and call an API in a Node.js web application - acquire an access token ++In this article, you add sign in, then acquire an access token to the web app project that you prepared in the previous chapter, [Prepare your client app and API](how-to-web-app-node-sign-in-call-api-prepare-app.md). The application you build uses [Microsoft Authentication Library (MSAL) for Node](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-node) to simplify adding authentication and authorization to your node web application. ++## Create MSAL configuration object ++In your code editor, open *authConfig.js* file, then add the following code: ++```javascript + require('dotenv').config(); + + const TENANT_SUBDOMAIN = process.env.TENANT_SUBDOMAIN || 'Enter_the_Tenant_Subdomain_Here'; + const REDIRECT_URI = process.env.REDIRECT_URI || 'http://localhost:3000/auth/redirect'; + const POST_LOGOUT_REDIRECT_URI = process.env.POST_LOGOUT_REDIRECT_URI || 'http://localhost:3000'; + + /** + * Configuration object to be passed to MSAL instance on creation. + * For a full list of MSAL Node configuration parameters, visit: + * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-node/docs/configuration.md + */ + const msalConfig = { + auth: { + clientId: process.env.CLIENT_ID || 'Enter_the_Application_Id_Here', // 'Application (client) ID' of app registration in Azure portal - this value is a GUID + authority: process.env.AUTHORITY || `https://${TENANT_SUBDOMAIN}.ciamlogin.com/`, + clientSecret: process.env.CLIENT_SECRET || 'Enter_the_Client_Secret_Here', // Client secret generated from the app registration in Azure portal + }, + system: { + loggerOptions: { + loggerCallback(loglevel, message, containsPii) { + console.log(message); + }, + piiLoggingEnabled: false, + logLevel: 'Info', + }, + }, + }; + + const toDoListReadScope = process.env.TODOLIST_READ || 'api://Enter_the_Web_Api_Application_Id_Here/ToDoList.Read'; + const toDoListReadWriteScope = process.env.TODOLIST_READWRITE || 'api://Enter_the_Web_Api_Application_Id_Here/ToDoList.ReadWrite'; + + const protectedResources = { + toDoListAPI: { + endpoint: 'https://localhost:44351/api/todolist', + scopes: { + read: [toDoListReadScope], + write: [toDoListReadWriteScope], + }, + }, + }; + module.exports = { + msalConfig, + protectedResources, + TENANT_SUBDOMAIN, + REDIRECT_URI, + POST_LOGOUT_REDIRECT_URI, + }; +``` ++The `msalConfig` object contains a set of configuration options that you use to customize the behavior of your authentication flows. ++In your `authConfig.js` file, replace: ++- `Enter_the_Application_Id_Here` with the Application (client) ID of the client web app that you registered earlier. ++- `Enter_the_Tenant_Subdomain_Here` and replace it with the Directory (tenant) subdomain. For example, if your tenant primary domain is `contoso.onmicrosoft.com`, use `contoso`. If you don't have your tenant name, learn how to [read your tenant details](how-to-create-customer-tenant-portal.md#get-the-customer-tenant-details). ++- `Enter_the_Client_Secret_Here` with the client web app secret value that you copied earlier. ++- `Enter_the_Web_Api_Application_Id_Here` with the Application (client) ID of the web API app that you copied earlier. ++Notice that the `todolistReadScope` and `todolistReadWriteScope` variables hold the full scope URLs that you set earlier in [Prepare your client app and API](how-to-web-app-node-sign-in-call-api-prepare-app.md). They're packaged in the `protectedResources` object. +++## Add express routes ++The Express routes provide the endpoints that enable us the execute operations such as sign in, sign out and view ID token claims. ++### App entry point ++In your code editor, open *routes/index.js* file, then add the following code: ++```javascript + const express = require('express'); + const router = express.Router(); + + router.get('/', function (req, res, next) { + res.render('index', { + Title: 'MSAL Node & Express Web App', + isAuthenticated: req.session.isAuthenticated, + username: req.session.account?.username !== '' ? req.session.account?.username : req.session.account?.name, + }); + }); + + module.exports = router; +``` +The `/` route is the entry point to the application. It renders the `views/index.hbs` that you created earlier in [Build app UI components](how-to-web-app-node-sign-in-call-api-prepare-app.md#build-app-ui-components). The `isAuthenticated` is a boolean variable that determines what you see in the view. ++### Sign-in and sign-out ++1. In your code editor, open *routes/auth.js* file, then add the code from [auth.js](https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial/blob/main/2-Authorization/4-call-api-express/App/routes/auth.js) to it. ++1. In your code editor, open *controller/authController.js* file, then add the code from [authController.js](https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial/blob/main/2-Authorization/4-call-api-express/App/controller/authController.js) to it. ++1. In your code editor, open *auth/AuthProvider.js* file, then add the code from [AuthProvider.js](https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial/blob/main/2-Authorization/4-call-api-express/App/auth/AuthProvider.js) to it. ++The `/signin`, `/signout` and `/redirect` routes are defined in the *routes/auth.js* file, but their logic live in *auth/AuthProvider.js* file. ++- The `login` method handles`/signin` route: + + - Initiates sign-in flow by triggering the first leg of auth code flow. + + - Initializes a [confidential client application](../../../active-directory/develop/msal-client-applications.md) instance by using `msalConfig` MSAL configuration object. + + ```javascript + const msalInstance = this.getMsalInstance(this.config.msalConfig); + ``` + + The `getMsalInstance` method is defined in the `AuthProvider` class as: ++ ```javascript + getMsalInstance(msalConfig) { + return new msal.ConfidentialClientApplication(msalConfig); + } + ``` + - The first leg of auth code flow generates an authorization code request URL, then redirects to that URL to obtain the authorization code. This first leg is implemented in the `redirectToAuthCodeUrl` method: + + ```javascript + async redirectToAuthCodeUrl(req, res, next, authCodeUrlRequestParams, authCodeRequestParams, msalInstance) { + // Generate PKCE Codes before starting the authorization flow + const { verifier, challenge } = await this.cryptoProvider.generatePkceCodes(); + + // Set generated PKCE codes and method as session vars + req.session.pkceCodes = { + challengeMethod: 'S256', + verifier: verifier, + challenge: challenge, + }; + + /** + * By manipulating the request objects below before each request, we can obtain + * auth artifacts with desired claims. For more information, visit: + * https://azuread.github.io/microsoft-authentication-library-for-js/ref/modules/_azure_msal_node.html#authorizationurlrequest + * https://azuread.github.io/microsoft-authentication-library-for-js/ref/modules/_azure_msal_node.html#authorizationcoderequest + **/ + + req.session.authCodeUrlRequest = { + ...authCodeUrlRequestParams, + redirectUri: this.config.redirectUri, + responseMode: 'form_post', // recommended for confidential clients + codeChallenge: req.session.pkceCodes.challenge, + codeChallengeMethod: req.session.pkceCodes.challengeMethod, + }; + + req.session.authCodeRequest = { + ...authCodeRequestParams, + redirectUri: this.config.redirectUri, + code: '', + }; + + try { + const authCodeUrlResponse = await msalInstance.getAuthCodeUrl(req.session.authCodeUrlRequest); + res.redirect(authCodeUrlResponse); + } catch (error) { + next(error); + } + } + ``` + + Notice how we use MSALs [getAuthCodeUrl](/javascript/api/@azure/msal-node/confidentialclientapplication#@azure-msal-node-confidentialclientapplication-getauthcodeurl) method to generate authorization code URL: + + ```javascript + //... + const authCodeUrlResponse = await msalInstance.getAuthCodeUrl(req.session.authCodeUrlRequest); + //... + ``` + + We then redirect to the authorization code URL itself. + + ```javascript + //... + res.redirect(authCodeUrlResponse); + //... + ``` ++- The `handleRedirect` method handles `/redirect` route: + + - You set this route as Redirect URI for the web app in the Microsoft Entra admin center earlier in [Register the web app](how-to-web-app-node-sample-sign-in-call-api.md#register-the-web-app). + + - This endpoint implements the second leg of auth code flow uses. It uses the authorization code to request an ID token by using MSAL's [acquireTokenByCode](/javascript/api/@azure/msal-node/confidentialclientapplication#@azure-msal-node-confidentialclientapplication-acquiretokenbycode) method. + + ```javascript + //... + const tokenResponse = await msalInstance.acquireTokenByCode(authCodeRequest, req.body); + //... + ``` ++ - After you receive a response, you can create an Express session and store whatever information you want in it. You need to include `isAuthenticated` and set it to `true`: + + ```javascript + //... + req.session.idToken = tokenResponse.idToken; + req.session.account = tokenResponse.account; + req.session.isAuthenticated = true; + //... + ``` + +- The `logout` method handles `/signout` route: + + - It initiates sign out process. + + - When you want to sign the user out of the application, it isn't enough to end the user's session. You must redirect the user to the *logout URI*. Otherwise, the user might be able to reauthenticate to your applications without reentering their credentials. If the name of your tenant is *contoso*, then the *logout URI* looks similar to `https://contoso.ciamlogin.com/contoso.onmicrosoft.com/oauth2/v2.0/logout?post_logout_redirect_uri=http://localhost:3000`. + + ```javascript + //... + const logoutUri = `${this.config.msalConfig.auth.authority}${TENANT_SUBDOMAIN}.onmicrosoft.com/oauth2/v2.0/logout?post_logout_redirect_uri=${POST_LOGOUT_REDIRECT_URI}`; ++ req.session.destroy(() => { + res.redirect(logoutUri); + }); + //... + ``` +### View ID token claims +In your code editor, open *routes/users.js* file, then add the following code: +```javascript + const express = require('express'); + const router = express.Router(); + + // custom middleware to check auth state + function isAuthenticated(req, res, next) { + if (!req.session.isAuthenticated) { + return res.redirect('/auth/signin'); // redirect to sign-in route + } + + next(); + }; + + router.get('/id', + isAuthenticated, // check if user is authenticated + async function (req, res, next) { + res.render('id', { idTokenClaims: req.session.account.idTokenClaims }); + } + ); + + module.exports = router; +``` +If the user is authenticated, the `/id` route displays ID token claims by using the `views/id.hbs` view. You added this view earlier in [Build app UI components](how-to-web-app-node-sign-in-prepare-app.md#build-app-ui-components). +To extract a specific ID token claim, such as *given name*: +```javascript + const givenName = req.session.account.idTokenClaims.given_name +``` ++## Acquire access token ++The `getToken` method in the `AuthProvider` class shows how to request for an access token: ++```javascript + getToken(scopes) { + return async function (req, res, next) { + const msalInstance = authProvider.getMsalInstance(authProvider.config.msalConfig); + try { + msalInstance.getTokenCache().deserialize(req.session.tokenCache); ++ const silentRequest = { + account: req.session.account, + scopes: scopes, + }; ++ const tokenResponse = await msalInstance.acquireTokenSilent(silentRequest); ++ req.session.tokenCache = msalInstance.getTokenCache().serialize(); + req.session.accessToken = tokenResponse.accessToken; + next(); + } catch (error) { + if (error instanceof msal.InteractionRequiredAuthError) { + req.session.csrfToken = authProvider.cryptoProvider.createNewGuid(); ++ const state = authProvider.cryptoProvider.base64Encode( + JSON.stringify({ + redirectTo: 'http://localhost:3000/todos', + csrfToken: req.session.csrfToken, + }) + ); + + const authCodeUrlRequestParams = { + state: state, + scopes: scopes, + }; ++ const authCodeRequestParams = { + state: state, + scopes: scopes, + }; ++ authProvider.redirectToAuthCodeUrl( + req, + res, + next, + authCodeUrlRequestParams, + authCodeRequestParams, + msalInstance + ); + } ++ next(error); + } + }; + } +``` ++- First, the function attempts to acquire an access token silently (without prompting the user for credentials): ++ ```javascript + const silentRequest = { + account: req.session.account, + scopes: scopes, + }; ++ const tokenResponse = await msalInstance.acquireTokenSilent(silentRequest); + ``` +- If you successfully acquire a token silently, store it in a session. You retrieve the token from the session when you call an API. ++ ```javascript + req.session.accessToken = tokenResponse.accessToken; + ``` ++- If you fail to acquire the token silently (such as with `InteractionRequiredAuthError` exception), request an access token afresh. ++## Next steps ++> [!div class="nextstepaction"] +> [Call an API >](how-to-web-app-node-sign-in-call-api-call-api.md) |
active-directory | How To Web App Node Sign In Overview | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-web-app-node-sign-in-overview.md | + + Title: Sign in users in your own Node.js web application +description: Learn about how to Sign in users in your own Node.js web application. +++++++++ Last updated : 05/22/2023+++#Customer intent: As a dev, devops, I want to learn about how to enable authentication in my own Node.js web app with Azure Active Directory (Azure AD) for customers tenant +++# Sign in users in your own Node.js web application ++In this article, you learn how to sign in users in your own Node.js web application that you build. You add authentication to your web application against your Azure Active Directory (Azure AD) for customers tenant. ++We've organized the content into three separate articles so it's easy for you to follow: ++- [Prepare your Azure AD for customers tenant](how-to-web-app-node-sign-in-prepare-tenant.md) tenant guides you how to register your app and configure user flows in the Microsoft Entra admin center. ++- [Prepare your web application](how-to-web-app-node-sign-in-prepare-app.md) guides you how to set up your Node.js app structure. ++- [Add sign-in and sign-out](how-to-web-app-node-sign-in-sign-in-out.md) guides you how to add authentication to your application by using MSAL. ++## Overview ++OpenID Connect (OIDC) is an authentication protocol that's built on OAuth 2.0. You can use OIDC to securely sign users in to an application. The application you build uses [Microsoft Authentication Library (MSAL) for Node](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-node) to simplify adding authentication to your node web application. ++The sign-in flow involves the following steps: ++1. Users go to the web app and initiate a sign-in flow. ++1. The app initiates an authentication request and redirects users to Azure AD for customers. ++1. Users sign up, sign in or reset the password. Users cal also sign in with a social account it's configured. ++1. After users sign in successfully, Azure AD for customers returns an ID token to the web app. ++1. The web app reads the ID token claims, and then displays a secure page to users. ++## Prerequisites ++- [Node.js](https://nodejs.org). ++- [Visual Studio Code](https://code.visualstudio.com/download) or another code editor. ++- Azure AD for customers tenant. If you don't already have one, [sign up for a free trial](https://aka.ms/ciam-free-trial?wt.mc_id=ciamcustomertenantfreetrial_linkclick_content_cnl). +++If you want to run a sample Node.js web application to get a feel of how things work, complete the steps in [Sign in users in a sample Node.js web application](how-to-web-app-node-sample-sign-in.md) ++## Next steps ++Next, learn how to prepare your Azure AD for customers tenant. ++> [!div class="nextstepaction"] +> [Prepare your Azure AD for customers tenant for authentication >](how-to-web-app-node-sign-in-prepare-tenant.md) |
active-directory | How To Web App Node Sign In Prepare App | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-web-app-node-sign-in-prepare-app.md | + + Title: Sign in users in your own Node.js web application - prepare your app +description: Learn about how to prepare an app that signs in users. +++++++++ Last updated : 05/22/2023+++#Customer intent: As a dev, devops, I want to learn about how to enable authentication in my own Node.js web app with Azure Active Directory (Azure AD) for customers tenant +++# Sign in users in your own Node.js web application - prepare your app ++In this article, you create a Node.js(Express) project and organize all the folders and files you require. You add authentication to the application you build here. This Node.js(Express) web application's views use [Handlebars](https://handlebarsjs.com). ++## Create the Node.js project ++Create a folder to host your node application, such as `ciam-sign-in-node-express-web-app`: ++1. In your terminal, change directory into your Node web app folder, such as `cd ciam-sign-in-node-express-web-app`, then run `npm init -y`. This command creates a default package.json file for your Node.js project. This command creates a default `package.json` file for your Node.js project. ++1. Create more folders and files to achieve the following project structure: ++ ``` + ciam-sign-in-node-express-web-app/ + Γö£ΓöÇΓöÇ server.js + ΓööΓöÇΓöÇ app.js + ΓööΓöÇΓöÇ authConfig.js + ΓööΓöÇΓöÇ package.json + ΓööΓöÇΓöÇ .env + ΓööΓöÇΓöÇ auth/ + ΓööΓöÇΓöÇ AuthProvider.js + ΓööΓöÇΓöÇ controller/ + ΓööΓöÇΓöÇ authController.js + ΓööΓöÇΓöÇ routes/ + ΓööΓöÇΓöÇ auth.js + ΓööΓöÇΓöÇ index.js + ΓööΓöÇΓöÇ users.js + ΓööΓöÇΓöÇ views/ + ΓööΓöÇΓöÇ layouts.hbs + ΓööΓöÇΓöÇ error.hbs + ΓööΓöÇΓöÇ id.hbs + ΓööΓöÇΓöÇ index.hbs + ΓööΓöÇΓöÇ public/stylesheets/ + ΓööΓöÇΓöÇ style.css + ``` ++## Install app dependencies ++In your terminal, install `axios`, `cookie-parser`, `dotenv`, `express`, `express-session`, `hbs`, `http-errors`, `morgan` and `@azure/msal-node` packages by running the following commands: ++```console + npm install express dotenv hbs express-session axios cookie-parser http-errors morgan @azure/msal-node +``` ++## Build app UI components ++1. In your code editor, open *views/index.hbs* file, then add the following code: ++ ```html + <h1>{{title}}</h1> + {{#if isAuthenticated }} + <p>Hi {{username}}!</p> + <a href="/users/id">View ID token claims</a> + <br> + <a href="/auth/signout">Sign out</a> + {{else}} + <p>Welcome to {{title}}</p> + <a href="/auth/signin">Sign in</a> + {{/if}} + ``` + In this view, if the user is authenticated, we show their username and links to visit `/auth/signout` and `/users/id` endpoints, otherwise, user needs to visit the `/auth/signin` endpoint to sign in. We define the express routes for these endpoints later in this article. ++1. In your code editor, open *views/id.hbs* file, then add the following code: ++ ```html + <h1>Azure AD for customers</h1> + <h3>ID Token</h3> + <table> + <tbody> + {{#each idTokenClaims}} + <tr> + <td>{{@key}}</td> + <td>{{this}}</td> + </tr> + {{/each}} + </tbody> + </table> + <a href="/">Go back</a> + ``` + We use this view to display ID token claims that Azure AD for customers returns to this app after a user successfully signs in. ++1. In your code editor, open *views/error.hbs* file, then add the following code: ++ ```html + <h1>{{message}}</h1> + <h2>{{error.status}}</h2> + <pre>{{error.stack}}</pre> + ``` ++ We use this view to display any errors that occur when the app runs. ++1. In your code editor, open *views/layout.hbs* file, then add the following code: ++ ```html + <!DOCTYPE html> + <html> + <head> + <title>{{title}}</title> + <link rel='stylesheet' href='/stylesheets/style.css' /> + </head> + <body> + {{{body}}} + </body> + </html> + ``` + + The `layout.hbs` file is in the layout file. It contains the HTML code that we require throughout the application view. ++1. In your code editor, open *public/stylesheets/style.css*, file, then add the following code: ++ ```css + body { + padding: 50px; + font: 14px "Lucida Grande", Helvetica, Arial, sans-serif; + } + + a { + color: #00B7FF; + } + ``` ++## Next steps ++Next, learn how to sign user in and sign of your web app: ++> [!div class="nextstepaction"] +> [Add sign in and sign out >](how-to-web-app-node-sign-in-sign-in-out.md) |
active-directory | How To Web App Node Sign In Prepare Tenant | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-web-app-node-sign-in-prepare-tenant.md | + + Title: Sign in users in your own Node.js web application - prepare your tenant +description: Learn how to prepare your Azure Active Directory (Azure AD) tenant for customers to sign in users in your own Node.js web application. +++++++++ Last updated : 05/22/2023+++#Customer intent: As a dev, devops, I want to learn about how to enable authentication in my own Node.js web app with Azure Active Directory (Azure AD) for customers tenant +++# Sign in users in your own Node.js web application - prepare your tenant ++In this article, you prepare your Azure Active Directory (Azure AD) for customers tenant for authentication. To prepare your tenant, you do the following tasks: ++- Register a web application in the Microsoft Entra admin center. ++- Create a sign in and sign out user flow in Microsoft Entra admin center. ++- Associate your web application with the user flow. ++After you complete the tasks, you'll collect an *Application (client) ID*, a *Client secret* and a *Directory (tenant) ID*. ++If you've already registered a web application in the Microsoft Entra admin center, and associated it with a user flow, you can skip the steps in this article and move to [Prepare your Node.js web app](how-to-web-app-node-sign-in-prepare-app.md). ++## Register the web app +++## Add app client secret +++## Grant API permissions +++## Create a user flow +++## Associate the web application with the user flow +++## Next steps ++> [!div class="nextstepaction"] +> [Start building your Node.js web app >](how-to-web-app-node-sign-in-prepare-app.md) |
active-directory | How To Web App Node Sign In Sign In Out | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-web-app-node-sign-in-sign-in-out.md | + + Title: Sign in users in a Node.js web application - add sign-in and sign-out +description: Learn about how to add sign-in and sign-out in your own Node.js web application. +++++++++ Last updated : 05/22/2023+++#Customer intent: As a dev, devops, I want to learn about how to enable authentication in my own Node.js web app with Azure Active Directory (Azure AD) for customers tenant +++# Sign in users in a Node.js web application - add sign-in and sign-out ++In this article, you add sign in and sign out to the web app project that you prepared in the previous chapter, [Prepare your web app](how-to-web-app-node-sign-in-prepare-app.md). The application you build uses [Microsoft Authentication Library (MSAL) for Node](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-node) to simplify adding authentication to your node web application. ++## Create MSAL configuration object ++In your code editor, open *authConfig.js* file, then add the following code: ++```javascript + require('dotenv').config(); + + const TENANT_SUBDOMAIN = process.env.TENANT_SUBDOMAIN || 'Enter_the_Tenant_Subdomain_Here'; + const REDIRECT_URI = process.env.REDIRECT_URI || 'http://localhost:3000/auth/redirect'; + const POST_LOGOUT_REDIRECT_URI = process.env.POST_LOGOUT_REDIRECT_URI || 'http://localhost:3000'; + + /** + * Configuration object to be passed to MSAL instance on creation. + * For a full list of MSAL Node configuration parameters, visit: + * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-node/docs/configuration.md + */ + const msalConfig = { + auth: { + clientId: process.env.CLIENT_ID || 'Enter_the_Application_Id_Here', // 'Application (client) ID' of app registration in Azure portal - this value is a GUID + authority: process.env.AUTHORITY || `https://${TENANT_SUBDOMAIN}.ciamlogin.com/`, // replace "Enter_the_Tenant_Subdomain_Here" with your tenant name + clientSecret: process.env.CLIENT_SECRET || 'Enter_the_Client_Secret_Here', // Client secret generated from the app registration in Azure portal + }, + system: { + loggerOptions: { + loggerCallback(loglevel, message, containsPii) { + console.log(message); + }, + piiLoggingEnabled: false, + logLevel: 'Info', + }, + }, + }; + + module.exports = { + msalConfig, + REDIRECT_URI, + POST_LOGOUT_REDIRECT_URI, + TENANT_SUBDOMAIN + }; +``` ++The `msalConfig` object contains a set of configuration options that you use to customize the behavior of your authentication flows. ++In your *authConfig.js* file, replace: ++- `Enter_the_Application_Id_Here` with the Application (client) ID of the app you registered earlier. ++- `Enter_the_Tenant_Subdomain_Here` and replace it with the Directory (tenant) subdomain. For example, if your tenant primary domain is `contoso.onmicrosoft.com`, use `contoso`. If you don't have your tenant name, learn how to [read your tenant details](how-to-create-customer-tenant-portal.md#get-the-customer-tenant-details). + +- `Enter_the_Client_Secret_Here` with the app secret value you copied earlier. ++If you use the *.env* file to store your configuration information: ++1. In your project folder such as `ciam-sign-in-node-express-web-app`, create a *.env* file. ++1. In your code editor, open *.env* file, then add the following code. ++ ``` + CLIENT_ID=Enter_the_Application_Id_Here + TENANT_SUBDOMAIN=Enter_the_Tenant_Subdomain_Here + CLIENT_SECRET=Enter_the_Client_Secret_Here + REDIRECT_URI=http://localhost:3000/auth/redirect + POST_LOGOUT_REDIRECT_URI=http://localhost:3000 + ``` ++1. Replace the `Enter_the_Application_Id_Here`, `Enter_the_Tenant_Subdomain_Here` and `Enter_the_Client_Secret_Here` placeholders as explained earlier. ++You export `msalConfig`, `REDIRECT_URI`, `TENANT_SUBDOMAIN` and `POST_LOGOUT_REDIRECT_URI` variables in the *authConfig.js* file. This makes them accessible wherever you require the file. ++## Add express routes ++The Express routes provide the endpoints that enable us the execute operations such as sign in, sign out and view ID token claims. ++### App entry point ++In your code editor, open *routes/index.js* file, then add the following code: ++```javascript + const express = require('express'); + const router = express.Router(); + + router.get('/', function (req, res, next) { + res.render('index', { + Title: 'MSAL Node & Express Web App', + isAuthenticated: req.session.isAuthenticated, + username: req.session.account?.username !== '' ? req.session.account?.username : req.session.account?.name, + }); + }); + module.exports = router; +``` ++The `/` route is the entry point to the application. It renders the *views/index.hbs* view that you created earlier in [Build app UI components](how-to-web-app-node-sign-in-prepare-app.md#build-app-ui-components). `isAuthenticated` is a boolean variable that determines what you see in the view. ++### Sign in and sign out ++1. In your code editor, open *routes/auth.js* file, then add the code from [auth.js](https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial/blob/main/1-Authentication/5-sign-in-express/App/routes/auth.js) to it. ++1. In your code editor, open *controller/authController.js* file, then add the code from [authController.js](https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial/blob/main/1-Authentication/5-sign-in-express/App/controller/authController.js) to it. ++1. In your code editor, open *auth/AuthProvider.js* file, then add the code from [AuthProvider.js](https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial/blob/main/1-Authentication/5-sign-in-express/App/auth/AuthProvider.js) to it. ++ The `/signin`, `/signout` and `/redirect` routes are defined in the *routes/auth.js* file, but their logic live in the *auth/AuthProvider.js* class. ++- The `login` method handles `/signin` route: + + - It initiates sign-in flow by triggering the first leg of auth code flow. + + - It initializes a [confidential client application](../../../active-directory/develop/msal-client-applications.md) instance by using MSAL configuration object, `msalConfig`. + + ```javascript + const msalInstance = this.getMsalInstance(this.config.msalConfig); + ``` + + The `getMsalInstance` method is defined as: ++ ```javascript + getMsalInstance(msalConfig) { + return new msal.ConfidentialClientApplication(msalConfig); + } + ``` + - The first leg of auth code flow generates an authorization code request URL, then redirects to that URL to obtain the authorization code. This first leg is implemented in the `redirectToAuthCodeUrl` method. Notice how we use MSALs [getAuthCodeUrl](/javascript/api/@azure/msal-node/confidentialclientapplication#@azure-msal-node-confidentialclientapplication-getauthcodeurl) method to generate authorization code URL: ++ ```javascript + //... + const authCodeUrlResponse = await msalInstance.getAuthCodeUrl(req.session.authCodeUrlRequest); + //... + ``` + + We then redirect to the authorization code URL itself. ++ ```javascript + //... + res.redirect(authCodeUrlResponse); + //... + ``` + ++- The `handleRedirect` method handles `/redirect` route: + + - You set this as Redirect URI for the web app in the Microsoft Entra admin center earlier in [Register the web app](how-to-web-app-node-sample-sign-in.md#register-the-web-app). + + - This endpoint implements the second leg of auth code flow uses. It uses the authorization code to request an ID token by using MSAL's [acquireTokenByCode](/javascript/api/@azure/msal-node/confidentialclientapplication#@azure-msal-node-confidentialclientapplication-acquiretokenbycode) method. + + ```javascript + //... + const tokenResponse = await msalInstance.acquireTokenByCode(authCodeRequest, req.body); + //... + ``` + + - After you receive a response, you can create an Express session and store whatever information you want in it. You need to include `isAuthenticated` and set it to `true`: + + ```javascript + //... + req.session.idToken = tokenResponse.idToken; + req.session.account = tokenResponse.account; + req.session.isAuthenticated = true; + //... + ``` ++- The `logout` method handles `/signout` route: + + ```javascript + async logout(req, res, next) { + /** + * Construct a logout URI and redirect the user to end the + * session with Azure AD. For more information, visit: + * https://docs.microsoft.com/azure/active-directory/develop/v2-protocols-oidc#send-a-sign-out-request + */ + const logoutUri = `${this.config.msalConfig.auth.authority}${TENANT_SUBDOMAIN}.onmicrosoft.com/oauth2/v2.0/logout?post_logout_redirect_uri=${this.config.postLogoutRedirectUri}`; + + req.session.destroy(() => { + res.redirect(logoutUri); + }); + } + ``` + - It initiates sign out request. + + - When you want to sign the user out of the application, it isn't enough to end the user's session. You must redirect the user to the *logoutUri*. Otherwise, the user might be able to reauthenticate to your applications without reentering their credentials. If the name of your tenant is *contoso*, then the *logoutUri* looks similar to `https://contoso.ciamlogin.com/contoso.onmicrosoft.com/oauth2/v2.0/logout?post_logout_redirect_uri=http://localhost:3000`. + + +### View ID token claims ++In your code editor, open *routes/users.js* file, then add the following code: ++```javascript + const express = require('express'); + const router = express.Router(); + + // custom middleware to check auth state + function isAuthenticated(req, res, next) { + if (!req.session.isAuthenticated) { + return res.redirect('/auth/signin'); // redirect to sign-in route + } + + next(); + }; + + router.get('/id', + isAuthenticated, // check if user is authenticated + async function (req, res, next) { + res.render('id', { idTokenClaims: req.session.account.idTokenClaims }); + } + ); + module.exports = router; +``` ++If the user is authenticated, the `/id` route displays ID token claims by using the *views/id.hbs* view. You added this view earlier in [Build app UI components](how-to-web-app-node-sign-in-prepare-app.md#build-app-ui-components). ++To extract a specific ID token claim, such as *given name*: ++```javascript + const givenName = req.session.account.idTokenClaims.given_name +``` ++## Finalize your web app ++1. In your code editor, open *app.js* file, then add the code from [app.js](https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial/blob/main/1-Authentication/5-sign-in-express/App/app.js) to it. ++1. In your code editor, open *server.js* file, then add the code from [server.js](https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial/blob/main/1-Authentication/5-sign-in-express/App/server.js) to it. ++1. In your code editor, open *package.json* file, then update the `scripts` property to: ++ ```json + "scripts": { + "start": "node server.js" + } + ``` ++## Run and test the web app ++1. In your terminal, make sure you're in the project folder that contains your web app such as `ciam-sign-in-node-express-web-app`. ++1. Use the steps in [Run and test the web app](how-to-web-app-node-sample-sign-in.md#run-and-test-sample-web-app) article to test your web app. ++## Next steps ++Learn how to: ++- [Enable password reset](how-to-enable-password-reset-customers.md). ++- [Customize the default branding](how-to-customize-branding-customers.md). + +- [Configure sign-in with Google](how-to-google-federation-customers.md). ++- [Use client certificate for authentication in your Node.js web app instead of a client secret](how-to-web-app-node-use-certificate.md). |
active-directory | How To Web App Node Use Certificate | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/how-to-web-app-node-use-certificate.md | + + Title: Use client certificate for authentication in your Node.js web app +description: Learn how to use client certificate instead of secrets for authentication in your Node.js web app +++++++++ Last updated : 05/22/2023+++#Customer intent: As a dev, devops, I want to learn Learn how to use client certificate instead of secrets for authentication in my Node.js web app +++# Use client certificate for authentication in your Node.js web app ++Azure Active Directory (Azure AD) for customers supports two types of authentication for [confidential client applications](../../../active-directory/develop/msal-client-applications.md); password-based authentication (such as client secret) and certificate-based authentication. For a higher level of security, we recommend using a certificate (instead of a client secret) as a credential in your confidential client applications. ++In production, you should purchase a certificate signed by a well-known certificate authority, and use [Azure Key Vault](https://azure.microsoft.com/products/key-vault/) to manage certificate access and lifetime for you. However, for testing purposes, you can create a self-signed certificate and configure your apps to authenticate with it. ++In this article, you learn to generate a self-signed certificate by using [Azure Key Vault](https://azure.microsoft.com/products/key-vault/) on the Azure portal, OpenSSL or Windows PowerShell. ++When needed, you can also create a self-signed certificate programmatically by using [.NET](/azure/key-vault/certificates/quick-create-net), [Node.js](/azure/key-vault/certificates/quick-create-node), [Go](/azure/key-vault/certificates/quick-create-go), [Python](/azure/key-vault/certificates/quick-create-python) or [Java](/azure/key-vault/certificates/quick-create-java) client libraries. ++## Prerequisites ++- [Node.js](https://nodejs.org). ++- [Visual Studio Code](https://code.visualstudio.com/download) or another code editor. ++- Azure AD for customers tenant. If you don't already have one, [sign up for a free trial](https://aka.ms/ciam-free-trial?wt.mc_id=ciamcustomertenantfreetrial_linkclick_content_cnl). ++- [OpenSSL](https://wiki.openssl.org/index.php/Binaries) or you can easily install [OpenSSL](https://community.chocolatey.org/packages/openssl) in Windows via [Chocolatey](https://chocolatey.org/). ++- [Windows PowerShell](/powershell/scripting/windows-powershell/install/installing-windows-powershell) or Azure subscription. ++## Create a self-signed certificate ++If you have an existing self-signed certificate in your local computer, you can skip this step, then proceed to [Upload certificate to your app registration](#upload-certificate-to-your-app-registration). ++# [Azure Key Vault - via Azure portal](#tab/azure-key-vault) +You can use [Azure Key Vault](/azure/key-vault/certificates/quick-create-portal) to generate a self-signed certificate for your app. By using Azure Key Vault, you enjoy benefits, such as, assigning a partner Certificate Authority (CA) and automating certificate rotation. ++If you have an existing self-signed certificate in Azure Key Vault, and you want to use it without downloading it, skip this step, then proceed to [Use a self-signed certificate directly from Azure Key Vault](#use-a-self-signed-certificate-directly-from-azure-key-vault). Otherwise, use the following steps to generate your certificate ++1. Follow the steps in [Set and retrieve a certificate from Azure Key Vault using the Azure portal](/azure/key-vault/certificates/quick-create-portal) to create and download your certificate. ++1. After you create your certificate, download both the *.cer* file and the *.pfx* file such as *ciam-client-app-cert.cer* and *ciam-client-app-cert.pfx*. The *.cer* file contains the public key and is what you upload to your Microsoft Entra admin center. ++1. In your terminal, run the following command to extract the private key from the *.pfx* file. When prompted to type a pass phrase, just press **Enter** key you if you don't want to set one. Otherwise type a pass phrase of your choice: ++ ```console + openssl pkcs12 -in ciam-client-app-cert.pfx -nocerts -out ciam-client-app-cert.key + ``` + + The *ciam-client-app-cert.key* file is what you use in your app. + ++# [Windows PowerShell](#tab/windows-powershell) ++1. Use the steps in [Create a self-signed public certificate to authenticate your application](/azure/active-directory/develop/howto-create-self-signed-certificate). Make sure you export your public certificate with its private key. For the `certificateName`, use *ciam-client-app-cert*. ++1. In your terminal, run the following command to extract the private key from the *.pfx* file. When prompted to type in your pass phrase, type a pass phrase of your choice: ++ ```console + openssl pkcs12 -in ciam-client-app-cert.pfx -nocerts -out ciam-client-app-cert.key + ``` +After you complete these steps, you should have a *.cer* file and the *.key* file, such as *ciam-client-app-cert.key* and *ciam-client-app-cert.cer*. The *.key* file is what you use in your app. The *.cer* file is what you upload to your Microsoft Entra admin center. ++++# [OpenSSL](#tab/openssl) ++In your terminal, run the following command. When prompted to type in your pass phrase, type a pass phrase of your choice: ++```console +openssl req -x509 -newkey rsa:2048 -keyout ciam-client-app-cert.key -out ciam-client-app-cert.crt -subj "/CN=ciamclientappcert.com" +``` ++After the command finishes execution, you should have a *.crt* and a *.key* files, such as *ciam-client-app-cert.key* and *ciam-client-app-cert.crt*. The *.key* file is what you use in your app. The *.cer* file is what you upload to your Microsoft Entra admin center. ++ ++## Upload certificate to your app registration +++## Configure your Node.js app to use certificate ++Once you associate your app registration with the certificate, you need to update your app code to start using the certificate: ++1. Locate the file that contains your MSAL configuration object, such as `msalConfig` in *authConfig.js*, then update it to look similar to the following code: ++ ```javascript + require('dotenv').config(); + const fs = require('fs'); //// import the fs module for reading the key file + const crypto = require('crypto'); + const TENANT_SUBDOMAIN = process.env.TENANT_SUBDOMAIN || 'Enter_the_Tenant_Subdomain_Here'; + const REDIRECT_URI = process.env.REDIRECT_URI || 'http://localhost:3000/auth/redirect'; + const POST_LOGOUT_REDIRECT_URI = process.env.POST_LOGOUT_REDIRECT_URI || 'http://localhost:3000'; + + const privateKeySource = fs.readFileSync('PATH_TO_YOUR_PRIVATE_KEY_FILE') + + const privateKeyObject = crypto.createPrivateKey({ + key: privateKeySource, + passphrase: 'Add_Passphrase_Here', + format: 'pem' + }); + + const privateKey = privateKeyObject.export({ + format: 'pem', + type: 'pkcs8' + }); + + /** + * Configuration object to be passed to MSAL instance on creation. + * For a full list of MSAL Node configuration parameters, visit: + * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-node/docs/configuration.md + */ + const msalConfig = { + auth: { + clientId: process.env.CLIENT_ID || 'Enter_the_Application_Id_Here', // 'Application (client) ID' of app registration in Azure portal - this value is a GUID + authority: process.env.AUTHORITY || `https://${TENANT_SUBDOMAIN}.ciamlogin.com/`, + //clientSecret: process.env.CLIENT_SECRET || 'Enter_the_Client_Secret_Here', // Client secret generated from the app registration in Azure portal + clientCertificate: { + thumbprint: "YOUR_CERT_THUMBPRINT", // replace with thumbprint obtained during step 2 above + privateKey: privateKey + } + }, + //... Rest of code in the msalConfig object + }; + + module.exports = { + msalConfig, + REDIRECT_URI, + POST_LOGOUT_REDIRECT_URI, + TENANT_SUBDOMAIN + }; + ``` + In your code, replace the placeholders: + + - `Add_Passphrase_Here` with the pass phrase you used to encrypt your private key. + + - `YOUR_CERT_THUMBPRINT` with the **Thumbprint** value you recorded earlier. + + - `PATH_TO_YOUR_PRIVATE_KEY_FILE` with the file path to your private key file. + + - `Enter_the_Application_Id_Here` with the Application (client) ID of the app you registered earlier. + + - `Enter_the_Tenant_Subdomain_Here` and replace it with the Directory (tenant) subdomain. For example, if your tenant primary domain is `contoso.onmicrosoft.com`, use `contoso`. If you don't have your tenant name, learn how to [read your tenant details](how-to-create-customer-tenant-portal.md#get-the-customer-tenant-details). ++ We encrypted the key (we recommend that you do so), so we have to decrypt it before we pass it to MSAL configuration object. ++ ```javascript + //... + const privateKeyObject = crypto.createPrivateKey({ + key: privateKeySource, + passphrase: 'Add_Passphrase_Here', + format: 'pem' + }); + + const privateKey = privateKeyObject.export({ + format: 'pem', + type: 'pkcs8' + }); + //... + ``` +1. Use the steps in [Run and test the web app](how-to-web-app-node-sign-in-sign-in-out.md#run-and-test-the-web-app) to test your app. ++## Use a self-signed certificate directly from Azure Key Vault ++You can use your existing certificate directly from Azure Key Vault: ++1. Locate the file that contains your MSAL configuration object, such as `msalConfig` in *authConfig.js*, then comment the `clientSecret` property: + + ```java + const msalConfig = { + auth: { + clientId: process.env.CLIENT_ID || 'Enter_the_Application_Id_Here', // 'Application (client) ID' of app registration in Azure portal - this value is a GUID + authority: process.env.AUTHORITY || `https://${TENANT_SUBDOMAIN}.ciamlogin.com/`, + //clientSecret: process.env.CLIENT_SECRET || 'Enter_the_Client_Secret_Here', // Client secret generated from the app registration in Azure portal + }, + //... + }; + ``` ++1. Install [Azure CLI](/cli/azure/install-azure-cli), then on your console, type the following command to sign-in: +++ ```console + az login --tenant YOUR_TENANT_ID + ``` + Replace the placeholder `YOUR_TENANT_ID` with the Directory (tenant) ID you copied earlier. ++1. On your console, type the following command to install the required packages: ++ ```console + npm install --save @azure/identity @azure/keyvault-certificates @azure/keyvault-secrets + ``` ++1. In your client app, use the following code to generate `thumbprint` and `privateKey`; ++ ```javascript + const identity = require("@azure/identity"); + const keyvaultCert = require("@azure/keyvault-certificates"); + const keyvaultSecret = require('@azure/keyvault-secrets'); ++ const KV_URL = process.env["KEY_VAULT_URL"] || "ENTER_YOUR_KEY_VAULT_URL" + const CERTIFICATE_NAME = process.env["CERTIFICATE_NAME"] || "ENTER_THE_NAME_OF_YOUR_CERTIFICATE_ON_KEY_VAULT"; ++ // Initialize Azure SDKs + const credential = new identity.DefaultAzureCredential(); + const certClient = new keyvaultCert.CertificateClient(KV_URL, credential); + const secretClient = new keyvaultSecret.SecretClient(KV_URL, credential); ++ async function getKeyAndThumbprint() { ++ // Grab the certificate thumbprint + const certResponse = await certClient.getCertificate(CERTIFICATE_NAME).catch(err => console.log(err)); + const thumbprint = certResponse.properties.x509Thumbprint.toString('hex') ++ // When you upload a certificate to Key Vault, a secret containing your private key is automatically created + const secretResponse = await secretClient.getSecret(CERTIFICATE_NAME).catch(err => console.log(err));; ++ // secretResponse contains both public and private key, but we only need the private key + const privateKey = secretResponse.value.split('--BEGIN CERTIFICATE--\n')[0] + } ++ getKeyAndThumbprint(); + ``` + + In your code, replace the placeholders: ++ - `ENTER_YOUR_KEY_VAULT_URL` with your Azure Key Vault URL. + + - `ENTER_THE_NAME_OF_YOUR_CERTIFICATE_ON_KEY_VAULT` with the name of your certificate in Azure Key Vault. + +1. Use the `thumbprint` and `privateKey` values to update your configuration: ++ ```javascript + let clientCert = { + thumbprint: thumbprint, + privateKey: privateKey, + }; ++ msalConfig.auth.clientCertificate = clientCert; //For this to work, you can't declares your msalConfig using const modifier + ``` ++1. Then proceed to instantiate your confidential client as shown in the `getMsalInstance` method: ++ ```javascript + class AuthProvider { + //... + getMsalInstance(msalConfig) { + return new msal.ConfidentialClientApplication(msalConfig); + } + //... + } + ``` ++1. Use the steps in [Run and test the web app](how-to-web-app-node-sign-in-sign-in-out.md#run-and-test-the-web-app) to test your app. ++## Next steps ++Learn how to: ++- [Sign in users and call an API in your own Node.js web application](how-to-web-app-node-sign-in-call-api-overview.md). |
active-directory | Overview Customers Ciam | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/overview-customers-ciam.md | + + Title: Overview - Customer identity access management (CIAM) +description: Learn about customer identity access management (CIAM), a solution that lets you create secure, customized sign-in experiences for your customer-facing apps and services. +++++++ Last updated : 05/07/2023++++#Customer intent: As a dev, devops, or it admin, I want to learn about identity solutions for customer-facing apps +++# What is Azure Active Directory for customers? ++Azure Active Directory (Azure AD) for customers is MicrosoftΓÇÖs new customer identity and access management (CIAM) solution. For organizations and businesses that want to make their public-facing applications available to consumers, Azure AD makes it easy to add CIAM features like self-service registration, personalized sign-in experiences, and customer account management. Because these CIAM capabilities are built into Azure AD, you also benefit from platform features like enhanced security, compliance, and scalability. +++> [!IMPORTANT] +> Azure AD for customers is currently in preview. See the [Supplemental Terms of Use for Microsoft Azure Previews](https://azure.microsoft.com/support/legal/preview-supplemental-terms/) for legal terms that apply to Azure features that are in beta, preview, or otherwise not yet released into general availability. ++## Add customized sign-in to your customer-facing apps ++Azure AD for customers is intended for businesses that want to make applications available to their customers using the Microsoft Entra platform for identity and access. ++- **Add sign-up and sign-in pages to your apps.** Quickly add intuitive, user-friendly sign-up and sign-up experiences for your customer apps. With a single identity, a customer can securely access all the applications you want them to use. ++- **Add single sign-on (SSO) with social and enterprise identities.** Customers can choose a social, enterprise, or managed identity to sign in with a username and password, email, or one-time passcode. ++- **Add your company branding to the sign-up page.** Customize the look and feel of your sign-up and sign-in experiences, including both the default experience and the experience for specific browser languages. ++- **Easily customize and extend your sign-up flows.** Tailor your identity user flows to your needs. Choose the attributes you want to collect from a customer during sign-up, or add your own custom attributes. If the information your app needs is contained in an external system, create custom authentication extensions to collect and add data to authentication tokens. ++- **Integrate multiple app languages and platforms.** With Microsoft Entra, you can quickly set up and deliver secure, branded authentication flows for multiple app types, platforms, and languages. ++- **Provide self-service account management.** Customers can register for your online services by themselves, manage their profile, delete their account, enroll in a multifactor authentication (MFA) method, or reset their password with no admin or help desk assistance. ++Learn more about [adding sign-in and sign-up to your app](concept-planning-your-solution.md) and [customizing the sign-in look and feel](concept-branding-customers.md). ++## Manage apps and users in a dedicated customer tenant ++Azure AD for customers uses the standard tenant model and overlays it with customized onboarding journeys for workforce or customer scenarios. B2B collaboration is part of workforce configurations. With the introduction of Azure AD for customers, Microsoft Entra now offers two different types of tenants that you can create and manage: *workforce tenants* and *customer tenants*. ++A **workforce tenant** contains your employees and the apps and resources that are internal to your organization. If you've worked with Azure Active Directory, a workforce tenant is the type of tenant you're already familiar with. You might already have an existing workforce tenant for your organization. ++In contrast, a **customer tenant** represents your customer-facing app, resources, and directory of customer accounts. A customer tenant is distinct and separate from your workforce tenant. A customer tenant is the first resource you need to create to get started with Azure AD for customers. To establish a CIAM solution for a customer-facing app or service, you create a new customer tenant. A customer tenant contains: ++- **A directory**: The directory stores your customers' credentials and profile data. When a customer signs up for your app, a local account is created for them in your customer tenant. ++- **Application registrations**: Microsoft Entra performs identity and access management only for registered applications. Registering your app establishes a trust relationship and allows you to integrate your app with Microsoft Entra ++- **User flows**: The customer tenant contains the self-service sign-up, sign-in, and password reset experiences that you enable for your customers. ++- **Extensions**: If you need to add user attributes and data from external systems, you can create custom authentication extensions for your user flows. ++- **Sign-in methods**: You can enable various options for signing in to your app, including username and password, one-time passcode, and Google or Facebook identities. Learn more ++- **Encryption keys**: Add and manage encryption keys for signing and validating tokens, client secrets, certificates, and passwords. +++There are two types of user accounts you can manage in a customer tenant: ++- **Customer account**: Accounts that represent the customers who access your applications. ++- **Admin account**: Users with work accounts can manage resources in a tenant, and with an administrator role, can also manage tenants. Users with work accounts can create new consumer accounts, reset passwords, block/unblock accounts, and set permissions or assign an account to a security group. ++Learn more about managing [customer accounts](how-to-manage-customer-accounts.md) and [admin accounts](how-to-manage-admin-accounts.md) in your customer tenant. ++## Design user flows for self-service sign-up ++You can create a simple sign-up and sign-in experience for your customers by adding a user flow to your application. The user flow defines the series of sign-up steps customers follow and the sign-in methods they can use (such as email and password, one-time passcodes, or social accounts from [Google](how-to-google-federation-customers.md) or [Facebook](how-to-facebook-federation-customers.md)). You can also collect information from customers during sign-up by selecting from a series of user built-in attributes or adding your own custom attributes. ++Several user flow settings let you control how the customer signs up for the application, including: ++- Sign-in methods and social identity providers (Google or Facebook) +- Attributes to be collected from the customer signing up, such as first name, postal code, or country/region of residency +- Company branding and language customization ++For details about configuring a user flow, see [Create a sign-up and sign-in user flow for customers](how-to-user-flow-sign-up-sign-in-customers.md). ++## Add your own business logic ++Azure AD for customers is designed for flexibility by allowing you to define additional actions at certain points within the authentication flow. Using a custom authentication extension, you can add claims from external systems to the token just before it's issued to your application. ++Learn more about [adding your own business logic](concept-custom-extensions.md) with custom authentication extensions. +++## Microsoft Entra security and reliability ++Azure AD for customers represents the convergence of business-to-consumer (B2C) features into the Azure AD platform. You benefit from platform features like enhanced security, compliance with regulations, and the ability to scale your identity and access management processes. ++- **Microsoft Entra security.** Get all the security and data privacy benefits of Microsoft Entra, including Conditional Access, multifactor authentication, and governance. Protect access to your apps using strong authentication and risk-based adaptive access policies. Because customers are managed in a separate tenant, you can tailor your access policies to users who typically use personal and shared devices instead of managed ones. ++- **Microsoft Entra reliability and scalability**. Create highly customized sign-in experiences and manage customer accounts at a large scale. Ensure a good customer experience by taking advantage of Microsoft Entra performance, resiliency, business continuity, low-latency, and high throughput. ++Learn more about the [security and governance](concept-security-customers.md) features that are available in a customer tenant. ++## Next steps ++- Learn more about [planning for Azure AD for customers](concept-planning-your-solution.md). +- See also the [Azure AD for customers Developer Center](https://aka.ms/ciam/dev) for the latest developer content and resources. |
active-directory | Overview Solutions Customers | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/overview-solutions-customers.md | + + Title: Overview of the Woodgrove Groceries demo +description: Learn about the customer identity and access management solutions for your customer-facing apps that are provided by Azure AD for customers. +++++++ Last updated : 05/10/2023+++++# Overview of the Woodgrove Groceries demo ++Azure Active Directory (Azure AD) for customers offers solutions that let you quickly add intuitive, user-friendly sign-up and sign-up experiences for your customer apps. The Woodgrove Groceries demo environment illustrates several of the most common authentication experiences that can be configured for your customer-facing apps. ++## Get started ++To try out the demo environment, go to [Woodgrove Groceries](https://wggdemo.net/) and select from a list of use cases that illustrate different sign-in options and business cases. +++## Use cases ++### Sign-up with an email and password ++One of the most common ways for users to sign up for an app is by creating an account using their email and a password. The **Common use case** option illustrates how to create an account from the sign-in page by selecting **No account? Create one**. +++When you enter an email address to create an account, your email is verified through a one-time passcode. Then you can create a new password and provide more details, such as your name, country or region, and other information. Once your account is create, your email becomes your sign-in ID. ++### Self-service password reset ++Self-service password reset (SSPR) gives users the ability to change or reset their password, with no administrator or help desk involvement. If a user's account is locked or they forget their password, they can follow prompts to unblock themselves and get back to work. ++Before you start, make sure you've run one of the sign-up use cases to create an account with Woodgrove Groceries. Then select the password reset use case to try it out. On the sign-in page, enter your email, and select **Next**. Then, select the **Forgot password?** link. Enter the verification code sent to your mailbox, and select next. Then, enter a password, and reenter the password, and select next. ++To set up self-service password reset for your customers see the [Enable self-service password reset](how-to-enable-password-reset-customers.md) article. ++### Sign-in with a social account ++You can offer your customers the ability to sign in with their existing social or enterprise accounts, without having to create a new account. On the sign-in page, select one of the identity providers, such as Google or Facebook. Then you're redirected to the selected provider's to complete the sign-in process. +++To allow your customers to sign up and sign in using their social accounts, you can navigate to **External Identities** > **All identity providers** in the admin center. You can find the exact steps for adding Google and Facebook as identity providers in the following links for [Google](how-to-google-federation-customers.md) and for [Facebook](how-to-facebook-federation-customers.md). ++### Sign-up with a one-time passcode ++Email one-time passcode sign-in method is a type of passwordless authentication option for your email account identity provider. With email one-time passcode, users can sign up and sign-in to your app using an email as their primary sign-in identifier. They don't need to create and remember passwords. During the sign-in, users are asked to enter their email address, to which Azure AD sends a one-time passcode. The users then open they mailbox and enter the passcode set to them into the sign-in page. +++You can enable email one-time passcode in the admin center under **Authentication methods**. For the exact steps, see [Enable email one-time passcode](how-to-enable-password-reset-customers.md#enable-email-one-time-passcode). ++### Sign-in using your own business logic ++When users authenticate to your application with Azure Active Directory, a security token is returned to your application. The security token contains claims that are statements about the user, such as name, unique identifier, or application roles. Beyond the default set of claims that are contained in the security token you can define your own custom claims from external systems using a REST API you develop. + +In this use case, you can sign in or sign up with your credentials. Then after you're successfully authenticated, from the Woodgrove top bar select your name and check your profile. It contains information that return by the Azure AD custom extension REST API. ++If you want to understand how custom extensions work, you can refer to the [Custom extension overview](/azure/active-directory/develop/custom-extension-overview) article. For information on custom claims providers, you can check out the [Custom claims provider](/azure/active-directory/develop/custom-claims-provider-overview) article. ++### Edit your account ++Profile editing policy lets you manage your profile attributes, like display name, surname, given name, city, and others. After you update your profile, sign out and sign in again. ++To edit your profile on the **Woodgrove Groceries** page, select the icon with your name, located in the top-right corner of the page. After making your changes, select **Save**. ++### Delete your account ++If you would like to delete your account and personal information, visit the **Delete my account** page. Once you delete your account, you can't reactivate it. After a couple of minutes, you'll be able to sign up again with the same credentials. ++To delete your account on the **Woodgrove Groceries** page, select the icon with your name located in the top-right corner of the page. On the **Edit your profile** page select **Delete your account**. + |
active-directory | Quickstart Trial Setup | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/quickstart-trial-setup.md | + + Title: Quickstart - Set up a customer tenant free trial +description: Use our quickstart to set up the customer tenant free trial. +++++++ Last updated : 05/10/2023++++#Customer intent: As a dev, devops, or it admin, I want to set up the customer tenant free trial. ++# Quickstart: Get started with Azure AD for customers (Preview) ++Get started with Azure AD for customers (Preview) that lets you create secure, customized sign-in experiences for your customer-facing apps and services. With these built-in customer tenant features, Azure AD for customers can serve as the identity provider and access management service for your customers. ++Your free trial of a customer tenant provides you with the opportunity to try new features and build applications and processes during the free trial period. Organization (tenant) admins can invite other users. Each user account can only have one active free trial tenant at a time. The free trial isn't designed for scale testing. Trial tenant will support up to 10K resources, learn more about Azure AD service limits [here](/azure/active-directory/enterprise-users/directory-service-limits-restrictions). During your free trial, you'll have the option to unlock the full set of features by upgrading to [Azure free account](https://azure.microsoft.com/free/). ++ > [!NOTE] + > At the end of the free trial period, your free trial tenant will be disabled and deleted. + +During the free trial period, you'll have access to all product features with few exceptions. See the following table for comparison: ++| Features | Azure AD for customers Trial (without credit card) | Azure Active Directory account includes Partners (needs credit card) | +|-|--|| +| **Self-service account experiences** (Sign-up, sign-in, and password recovery.) | :heavy_check_mark: | :heavy_check_mark: | +| **MFA** (With email OTP.) | :heavy_check_mark: | :heavy_check_mark: | +| **Custom token augmentation** (From external sources.) | :heavy_check_mark: | :heavy_check_mark: | +| **Social identity providers** | :heavy_check_mark: | :heavy_check_mark: | +| **Identity Protection** (Conditional access for adaptive risk-based policies.) | :x: | :heavy_check_mark: | +| Default, least-access privileges for CIAM end-users. | :heavy_check_mark: | :heavy_check_mark: | +| **Rich authorization** (Including group and role management.) | :heavy_check_mark: | :heavy_check_mark: | +| **Customizable** (Sign-in/sign-up experiences - background, logo, strings.) | :heavy_check_mark: | :heavy_check_mark: | +| Group and User management. | :heavy_check_mark: | :heavy_check_mark: | +| **Cloud-agnostic solution** with multi-language auth SDK support. | :heavy_check_mark: | :heavy_check_mark: | ++> [!IMPORTANT] +> Azure AD for customers is currently in preview. See the [Supplemental Terms of Use for Microsoft Azure Previews](https://azure.microsoft.com/support/legal/preview-supplemental-terms/) for legal terms that apply to Azure features that are in beta, preview, or otherwise not yet released into general availability. ++## Sign up to your customer tenant free trial ++1. Open your browser and visit [https://aka.ms/ciam-free-trial](https://aka.ms/ciam-free-trial?wt.mc_id=ciamcustomertenantfreetrial_linkclick_content_cnl). +1. You can sign in to the customer trial tenant using your personal account, and your Microsoft account (MSA) or GitHub account. +1. You'll notice that a domain name and location have been set for you. The domain name and the data location can't be changed later in the free trial. Select **Change settings** if you would like to adjust them. +1. Select **Continue** and hang on while we set up your trial. It will take a few minutes for the trial to become ready for the next step. ++ :::image type="content" source="media/quickstart-trial-setup/setting-up-free-trial.png" alt-text="Screenshot of the loading page while setting up the customer tenant free trial."::: ++## Customize your sign-in experience ++You can customize your customer's sign-in and sign-up experience in the Azure AD for customers tenant. Follow the guide that will help you set up the tenant in three easy steps. First you must specify how would you like your customer to sign in. At this step you can choose between two options: **Email and password** or **Email and one-time passcode**. You can configure social accounts later, which would allow your customers to sign in using their [Google](how-to-google-federation-customers.md) or [Facebook](how-to-facebook-federation-customers.md) account. You can also [define custom attributes](how-to-define-custom-attributes.md) to collect from the user during sign-up. ++If you prefer, you can add your company logo, change the background color or adjust the sign-in layout. These optional changes will apply to the look and feel of all your apps in this customer tenant. After you have the created customer tenant, additional branding options are available. You can [customize the default branding](how-to-customize-branding-customers.md) and [add languages](how-to-customize-languages-customers.md). Once you're finished with the customization, select **Continue**. +++## Try out the sign-up experience and create your first user ++1. The guide will configure your tenant with the options you have selected. Once the configuration is complete, the button will change its text from **Setting up...** to **Run it now**. +1. Select the **Run it now** button. A new browser tab will open with the sign-in page for your customer tenant that can be used to create and sign in users. +1. Select **No account? Create one** to create a new user in the customer tenant. +1. Add your new user's email address and select **Next**. Don't use the same email you used to create your trial. +1. Complete the sign-up steps on the screen. Typically, once the user has signed in, they're redirected back to your app. However, since you havenΓÇÖt set up an app at this step, you'll be redirected to JWT.ms instead, where you can view the contents of the token issued during the sign-in process. +1. Go back to the guide tab. At this stage, you can either exit the guide and go to the admin center to explore the full range of configuration options for your tenant. Or you can **Continue** and set up a sample app. We recommend setting up the sample app, so that you can use it to test any further configuration changes you make ++ :::image type="content" source="media/quickstart-trial-setup/successful-trial-setup.png" alt-text="Screenshot that shows the successful creation of the sign-up experience."::: ++## Set up a sample app ++The get started guide will automatically configure sample apps for the below app types and languages: ++- Single Page Application (SPA): JavaScript, React, Angular +- Web app: Node.js (Express), ASP.NET Core ++Follow the steps below, to download and run the sample app. ++1. Proceed to set up the sample app by selecting the app type. +1. Select your language and **Download sample app** on your machine. +1. Follow the instructions to install and run the app. Sign into the sample app. ++ :::image type="content" source="media/quickstart-trial-setup/sample-app-setup.png" alt-text="Screenshot of the sample app setup."::: ++1. You've completed the process of creating a trial tenant, configuring the sign-in experience, creating your first user, and setting up a sample app. Select **Continue** to go to the summary page, where you can either go to the admin center or you can restart the guide to choose different options. ++## Explore Azure AD for customers ++Follow the articles below to learn more about the configuration the guide created for you or to configure your own apps. You can always come back to the [admin center](https://entra.microsoft.com/) to customize your tenant and explore the full range of configuration options for your tenant. ++## Next steps + - [Register an app in CIAM](how-to-register-ciam-app.md) + - [Customize user experience for your customers](how-to-customize-branding-customers.md) + - [Create a sign-up and sign-in user flow](how-to-user-flow-sign-up-sign-in-customers.md) + - See the [Azure AD for customers Developer Center](https://aka.ms/ciam/dev) for the latest developer content and resources + |
active-directory | Reference Group App Roles Support | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/reference-group-app-roles-support.md | + + Title: Groups and app roles support in customer tenants +description: Find out which core Azure AD features related to the user and group management model and application assignment are available in customer tenants. +++++++ Last updated : 05/01/2023+++++# Groups and application roles support ++A customer tenant follows the Azure Active Directory (Azure AD) user and group management model and application assignment. Many of the core Azure AD features are being phased into customer tenants. The following table shows which features are currently available. ++| **Feature** | **Currently available?** | +| | | +| Create an application role for a resource | Yes, by modifying the application manifest | +| Assign an application role to users | Yes | +| Assign an application role to groups | Yes, via Microsoft Graph only | +| Assign an application role to applications | Yes, via application permissions | +| Assign a user to an application role | Yes | +| Assign an application to an application role (application permission) | Yes | +| Add a group to an application/service principal (groups claim) | Yes, via Microsoft Graph only | +| Create/update/delete a customer (local user) via the Microsoft Entra admin center | Yes | +| Reset a password for a customer (local user) via the Microsoft Entra admin center | Yes | +| Create/update/delete a customer (local user) via Microsoft Graph | Yes | +| Reset a password for a customer (local user) via Microsoft Graph | Yes, only if the service principal is added to the Global administrator role | +| Create/update/delete a security group via the Microsoft Entra admin center | Yes | +| Create/update/delete a security group via the Microsoft Graph API | Yes | +| Change security group members using the Microsoft Entra admin center | Yes | +| Change security group members using the Microsoft Graph API | Yes | +| Scale up to 50,000 users and 50,000 groups | Not currently available | +| Add 50,000 users to at least two groups | Not currently available | |
active-directory | Reference User Permissions | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/reference-user-permissions.md | + + Title: User default permissions in customer tenants +description: Learn about the default permissions for users in a customer tenant. +++++++ Last updated : 05/01/2023+++++# Default user permissions in customer tenants ++A customer tenant provides clear separation between your corporate workforce directory and your customer-facing app directory. Furthermore, users created in your customer tenant are restricted from accessing information about other users in the customer tenant. By default, customers canΓÇÖt access information about other users, groups, or devices. ++The following table describes the default permissions assigned to a customer. ++| **Area** | **Customer user permissions** | +| | | +| Users and contacts | - Read and update their own profile through the app profile management experience <br>- Change their own password <br>- Sign in with a local or social account | +| Applications | - Access customer-facing applications <br>- Revoke consent to applications | |
active-directory | Samples Ciam All | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/external-identities/customers/samples-ciam-all.md | + + Title: Code samples for customer tenants +description: Find code samples for applications you can run in a customer tenant. Find samples by app type or language. +++++++ Last updated : 05/10/2023++++++# Samples for customer identity and access management (CIAM) in Azure Active Directory ++Microsoft maintains code samples that demonstrate how to integrate various application types with Azure AD for customers. We provide instructions for downloading and using samples or building your own app based on common authentication and authorization scenarios, development languages, and platforms. Included are instructions for building the project (if applicable) and running the sample application. Within the sample code, comments help you understand how these libraries are used in the application to perform authentication and authorization in a customer tenant. ++## Samples and guides ++Use the tabs to sort samples either by app type or your preferred language/platform. ++# [**By app type**](#tab/apptype) ++### Single-page application (SPA) ++These samples and how-to guides demonstrate how to integrate a single-page application with Azure AD for customers. ++> [!div class="mx-tdCol2BreakAll"] +> | Language/<br/>Platform | Code sample guide | Build and integrate guide | +> | - | -- | - | +> | JavaScript, Vanilla | • [Sign in users](how-to-single-page-app-vanillajs-sample-sign-in.md) | • [Sign in users](how-to-single-page-app-vanillajs-prepare-tenant.md) | +> | JavaScript, Angular | • [Sign in users](how-to-single-page-application-angular-sample.md) | | +> | JavaScript, React | • [Sign in users](how-to-single-page-application-react-sample.md) | • [Sign in users](how-to-single-page-application-react-prepare-tenant.md) | ++### Web app ++These samples and how-to guides demonstrate how to write a web application that integrates with Azure AD for customers. ++> [!div class="mx-tdCol2BreakAll"] +> | Language/<br/>Platform | Code sample guide | Build and integrate guide | +> | - | -- | - | +> | JavaScript, Node.js (Express) | • [Sign in users](how-to-web-app-node-sample-sign-in.md)<br/> • [Sign in users and call an API](how-to-web-app-node-sample-sign-in-call-api.md) | • [Sign in users](how-to-web-app-node-sign-in-overview.md)<br/> • [Sign in users and call an API](how-to-web-app-node-sign-in-call-api-overview.md) | +> | ASP.NET Core | • [Sign in users](how-to-web-app-dotnet-sample-sign-in.md) | • [Sign in users](how-to-web-app-dotnet-sign-in-prepare-tenant.md) | ++### Web API ++These samples and how-to guides demonstrate how to protect a web API with the Microsoft identity platform, and how to call a downstream API from the web API. ++> [!div class="mx-tdCol2BreakAll"] +> | Language/<br/>Platform | Code sample guide | Build and integrate guide | +> | - | -- | - | +> | ASP.NET Core | | • [Secure an ASP.NET web API](how-to-protect-web-api-dotnet-core-overview.md) | ++### Browserless ++These samples and how-to guides demonstrate how to write a browserless application that integrates with Azure AD for customers. ++> [!div class="mx-tdCol2BreakAll"] +> | Language/<br/>Platform | Code sample guide | Build and integrate guide | +> | - | -- | - | +> | JavaScript, Node | • [Sign in users](how-to-browserless-app-node-sample-sign-in.md) | • [Sign in users](how-to-browserless-app-node-sign-in-overview.md ) | +> | .NET | • [Sign in users](how-to-browserless-app-dotnet-sample-sign-in.md) | • [Sign in users](how-to-browserless-app-dotnet-sign-in-overview.md) | +++### Desktop ++These samples and how-to guides demonstrate how to write a desktop application that integrates with Azure AD for customers. ++> [!div class="mx-tdCol2BreakAll"] +> | Language/<br/>Platform | Code sample guide | Build and integrate guide | +> | - | -- | - | +> | JavaScript, Electron | • [Sign in users](how-to-desktop-app-electron-sample-sign-in.md) | | +> | ASP.NET (MAUI) | • [Sign in users](how-to-desktop-app-maui-sample-sign-in.md) | | ++### Mobile ++These samples and how-to guides demonstrate how to write a public client mobile application that integrates with Azure AD for customers. ++> [!div class="mx-tdCol2BreakAll"] +> | Language/<br/>Platform | Code sample guide | Build and integrate guide | +> | -- | -- |-- | +> | ASP.NET Core MAUI | • [Sign in users](how-to-mobile-app-maui-sample-sign-in.md) | | ++### Daemon ++These samples and how-to guides demonstrate how to write a daemon application that integrates with Azure AD for customers. ++> [!div class="mx-tdCol2BreakAll"] +> | Language/<br/>Platform | Code sample guide | Build and integrate guide | +> | -- | -- |-- | +> | Node.js | • [Call an API](how-to-daemon-node-sample-call-api.md) | • [Call an API](how-to-daemon-node-call-api-overview.md) | ++# [**By language/platform**](#tab/language) ++### .NET ++> [!div class="mx-tdCol2BreakAll"] +> | App type | Code sample guide | Build and integrate guide | +> | - | -- | - | +> | Browserless | • [Sign in users](how-to-browserless-app-dotnet-sample-sign-in.md) | • [Sign in users](how-to-browserless-app-dotnet-sign-in-overview.md) | +++### ASP.NET Core ++> [!div class="mx-tdCol2BreakAll"] +> | App type | Code sample guide | Build and integrate guide | +> | - | -- | - | +> | Web API| | • [Secure an ASP.NET web API](how-to-protect-web-api-dotnet-core-overview.md) | +> | Web app | • [Sign in users](how-to-web-app-dotnet-sample-sign-in.md) | • [Sign in users](how-to-web-app-dotnet-sign-in-prepare-tenant.md) | ++### .NET (MAUI) ++> [!div class="mx-tdCol2BreakAll"] +> | App type | Code sample guide | Build and integrate guide | +> | - | -- | - | +> | Desktop | • [Sign in users](how-to-desktop-app-maui-sample-sign-in.md) | | +> | Mobile | • [Sign in users](how-to-mobile-app-maui-sample-sign-in.md) | | +++### JavaScript, Vanilla ++> [!div class="mx-tdCol2BreakAll"] +> | App type | Code sample guide | Build and integrate guide | +> | - | -- | - | +> | Single-page application | • [Sign in users](how-to-single-page-app-vanillajs-sample-sign-in.md) | • [Sign in users](how-to-single-page-app-vanillajs-prepare-tenant.md) | ++### JavaScript, Angular ++> [!div class="mx-tdCol2BreakAll"] +> | App type | Code sample guide | Build and integrate guide | +> | - | -- | - | +> | Single-page application | • [Sign in users](how-to-single-page-application-angular-sample.md) | | ++### JavaScript, React ++> [!div class="mx-tdCol2BreakAll"] +> | App type | Code sample guide | Build and integrate guide | +> | - | -- | - | +> | Single-page application| • [Sign in users](how-to-single-page-application-react-sample.md) | • [Sign in users](how-to-single-page-application-react-prepare-tenant.md) | ++### JavaScript, Node ++> [!div class="mx-tdCol2BreakAll"] +> | App type | Code sample guide | Build and integrate guide | +> | - | -- | - | +> | Browserless | • [Sign in users](how-to-browserless-app-node-sample-sign-in.md) | • [Sign in users](how-to-browserless-app-node-sign-in-overview.md ) | +> | Daemon | • [Call an API](how-to-daemon-node-sample-call-api.md) | • [Call an API](how-to-daemon-node-call-api-overview.md) | +++### JavaScript, Node.js (Express) ++> [!div class="mx-tdCol2BreakAll"] +> | App type | Code sample guide | Build and integrate guide | +> | - | -- | - | +> | Web app |• [Sign in users](how-to-web-app-node-sample-sign-in.md)<br/> • [Sign in users and call an API](how-to-web-app-node-sample-sign-in-call-api.md) | • [Sign in users](how-to-web-app-node-sign-in-overview.md)<br/> • [Sign in users and call an API](how-to-web-app-node-sign-in-call-api-overview.md) | ++### JavaScript, Electron ++> [!div class="mx-tdCol2BreakAll"] +> | App type | Code sample guide | Build and integrate guide | +> | - | -- | - | +> | Desktop | • [Sign in users](how-to-desktop-app-electron-sample-sign-in.md) | | ++ |
active-directory | Concept Fundamentals Security Defaults | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/fundamentals/concept-fundamentals-security-defaults.md | After security defaults are enabled in your tenant, all authentication requests Organizations use various Azure services managed through the Azure Resource Manager API, including: - Azure portal +- Microsoft Entra Admin Center - Azure PowerShell - Azure CLI |
active-directory | Customize Branding | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/fundamentals/customize-branding.md | The **Global Administrator** role is required to customize company branding. ## Before you begin -You can customize the sign-in experience when users sign in to your organization's tenant-specific apps, such as `https://outlook.com/woodgrove.com`, or when passing a domain variable, such as `https://passwordreset.microsoftonline.com/?whr=woodgrove.com`. +You can customize the sign-in experience when users sign in to your organization by passing a domain variable: +Microsoft 365 Portal: `https://login.microsoftonline.com/?whr=contoso.com` +Outlook: `https://outlook.com/contoso.com` +Teams: `https://teams.microsoft.com/?tenantId=contoso.com` +MyApps: `http://myapps.microsoft.com/?whr=contoso.com` +Azure AD Self-service Password Reset: `https://passwordreset.microsoftonline.com/?whr=contoso.com` Custom branding appears after users sign in. Users that start the sign-in process at a site like www\.office.com won't see the branding. After users sign in, the branding may take at least 15 minutes to appear. |
active-directory | Users Default Permissions | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/fundamentals/users-default-permissions.md | You can restrict default permissions for member users in the following ways: The **Restrict non-admin users from creating tenants** option is shown [below](https://portal.azure.com/#view/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/~/UserSettings) ## Restrict guest users' default permissions |
active-directory | How To Connect Sync Staging Server | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/hybrid/connect/how-to-connect-sync-staging-server.md | You may need to perform a failover of the Sync Servers for several reasons, such #### Change currently Active Sync Server to staging mode -We need to ensure that only one Sync Server is syncing changes at any given time throughout this process. If the currently Active Sync Server is reachable you can perform the below steps to move it to Staging Mode. If it is not reachable, ensure that the server or VM does not regain access unexpectedly either by shutting down the server or isolating it from outbound connections and proceed to the steps on how to change the currently Staging Sync Server to Active Mode. +We need to ensure that only one Sync Server is syncing changes at any given time throughout this process. If the currently active Sync Server is reachable you can perform the below steps to move it to Staging Mode. If it is not reachable, ensure that the server or VM does not regain access unexpectedly either by shutting down the server or isolating it from outbound connections. -1. For the currently Active Azure AD Connect server, open the Azure AD Connect Console and click "Configure staging mode" then Next: +1. For the currently active Azure AD Connect server, open the Azure AD Connect wizard and click "Configure staging mode" then Next: > [!div class="mx-imgBorder"] >  We need to ensure that only one Sync Server is syncing changes at any given time > [!div class="mx-imgBorder"] >  -4. The Azure AD Connect server will check for installed components and then prompt you whether you want to start the sync process: +4. The Azure AD Connect server will check for installed components and then prompt you whether you want to start the sync process when the configuration change completes: > [!div class="mx-imgBorder"] >  Since the server will be in staging mode, it will not write changes to Azure AD, but retain any changes to the AD in its Connector Space, ready to write them. -It is recommended to leave the sync process on for the server in Staging Mode, so if it becomes active, it will quickly take over and won't have to do a large sync to catch up to the current state of the AD/Azure AD sync. +It is recommended to leave the sync process on for the server in Staging Mode, so if it becomes active, it will quickly take over and won't have to do a large sync to catch up to the current state of the AD/Azure AD objects in scope. -5. After selecting whether to start or stop the sync process and clicking Configure, the Azure AD Connect server will configure itself into Staging Mode. +5. After selecting to start the sync process and clicking Configure, the Azure AD Connect server will be configured into Staging Mode. When this is completed, you will be prompted with a screen that confirms Staging Mode is enabled. -You can click Exit to finish this. +You can click Exit to finish. -6. You can confirm that the server is successfully in Staging Mode by opening the Synchronization Service console. -From here, there should be no more Export jobs since the change and Full & Delta Imports will be suffixed with "(Stage Only)" like below: +6. You can confirm that the server is successfully in Staging Mode by opening Windows PowerShell, load the "ADSync" module and verify the ADSync Scheduler configuration, using the following commands: ++```powershell +Import-Module ADSync +Get-ADSyncScheduler +``` + +From the results, verify the value of the "StagingModeEnabled" setting. If the server was successfully switched to staging mode the value of this setting should be _**True**_ like in the example below: > [!div class="mx-imgBorder"]- >  + >  #### Change current Staging Sync server to active mode At this point, all of our Azure AD Connect Sync Servers should be in Staging Mode and not exporting changes. We can now move our Staging Sync Server to Active mode and actively sync changes. -1. Now move to the Azure AD Connect server that was originally in Staging Mode and open the Azure AD Connect console. +1. Now move to the Azure AD Connect server that was originally in Staging Mode and open the Azure AD Connect wizard. Click on "Configure staging mode" and click Next: > [!div class="mx-imgBorder"] >  - The message at the bottom of the Console indicates this server is in Staging Mode. + The message at the bottom of the wizard indicates this server is in Staging Mode. 2. Sign into Azure AD, then go to the Staging Mode screen. We can now move our Staging Sync Server to Active mode and actively sync changes > [!div class="mx-imgBorder"] >  -5. You can again confirm that this is working by opening the Sync Service Console and checking if Export jobs are running: +5. You can confirm that this is working by opening the Sync Service Console and checking if Export jobs are running: > [!div class="mx-imgBorder"] >  |
active-directory | Howto Troubleshoot Upn Changes | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/hybrid/connect/howto-troubleshoot-upn-changes.md | Title: Plan and troubleshoot Azure User Principal name (UPN) changes -description: Understand known issues and mitigations for UPN changes + Title: Plan and troubleshoot User Principal Name changes in Azure Active Directory +description: Understand known issues and mitigations for User Principal Name (UPN) changes Previously updated : 01/18/2023 Last updated : 05/23/2023 Users might experience single sign-on issues with applications that depend on Az ### Workaround -Allow enough time for the UPN change to sync to Azure AD. After you verify the new UPN appears in the Azure portal, ask the user to select the "Other user" tile to sign in with their new UPN. You can verify using PowerShell. See, [Get-AzureADUser](/powershell/module/azuread/get-azureaduser?view=azureadps-2.0&preserve-view=true). After users sign in with a new UPN, references to the old UPN might appear on the **Access work or school** Windows setting. +Allow enough time for the UPN change to sync to Azure AD. After you verify the new UPN appears in the Azure portal, ask the user to select the "Other user" tile to sign in with their new UPN. You can verify using Microsoft Graph PowerShell. See, [Get-MgUser](/powershell/module/microsoft.graph.users/get-mguser). After users sign in with a new UPN, references to the old UPN might appear on the **Access work or school** Windows setting.  |
active-directory | Myapps Overview | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/manage-apps/myapps-overview.md | To download and install the extension: An icon is added to the right of the address bar, which enables sign in and customization of the extension. +> [!NOTE] +> Sign-in into the extension is currently not supported for Guest B2B Microsoft Accounts (MSA). + ### Permissions Permissions that have been granted to an application can be reviewed by looking at the permissions tab for it. To access the permissions tab, select the upper right corner of the tile that represents the application and then select **Manage your application**. |
active-directory | Tutorial Windows Vm Ua Arm | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/active-directory/managed-identities-azure-resources/tutorial-windows-vm-ua-arm.md | Update-AzVM -ResourceGroupName TestRG -VM $vm -IdentityType "UserAssigned" -Iden This section shows how to grant your user-assigned identity access to a Resource Group in Azure Resource Manager. Managed identities for Azure resources provide identities that your code can use to request access tokens to authenticate to resource APIs that support Azure AD authentication. In this tutorial, your code will access the Azure Resource Manager API. -Before your code can access the API, you need to grant the identity access to a resource in Azure Resource Manager. In this case, the Resource Group in which the VM is contained. Update the value for `<SUBSCRIPTION ID>` as appropriate for your environment. +Before your code can access the API, you need to grant the identity access to a resource in Azure Resource Manager. In this case, the Resource Group in which the VM is contained. Update the value for `<SUBSCRIPTIONID>` as appropriate for your environment. ```azurepowershell-interactive $spID = (Get-AzUserAssignedIdentity -ResourceGroupName myResourceGroupVM -Name ID1).principalid New-AzRoleAssignment -ObjectId $spID -RoleDefinitionName "Reader" -Scope "/subsc The response contains details for the role assignment created, similar to the following example: ```azurepowershell-RoleAssignmentId: /subscriptions/80c696ff-5efa-4909-a64d-f1b616f423ca/resourcegroups/myResourceGroupVM/providers/Microsoft.Authorization/roleAssignments/f9cc753d-265e-4434-ae19-0c3e2ead62ac -Scope: /subscriptions/80c696ff-5efa-4909-a64d-f1b616f423ca/resourcegroups/myResourceGroupVM +RoleAssignmentId: /subscriptions/<SUBSCRIPTIONID>/resourcegroups/myResourceGroupVM/providers/Microsoft.Authorization/roleAssignments/f9cc753d-265e-4434-ae19-0c3e2ead62ac +Scope: /subscriptions/<SUBSCRIPTIONID>/resourcegroups/myResourceGroupVM DisplayName: ID1 SignInName: RoleDefinitionName: Reader |
advisor | Advisor Get Started | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/advisor/advisor-get-started.md | You may have resource groups or subscriptions for which you do not want to recei This procedure configures the average CPU utilization rule for the low usage virtual machine recommendation. -Advisor monitors your virtual machine usage for 7 days and then identifies low-utilization virtual machines. Virtual machines are considered low-utilization if their CPU utilization is 5% or less and their network utilization is less than 2% or if the current workload can be accommodated by a smaller virtual machine size. +Advisor monitors your virtual machine usage for 7 days by default and then identifies low-utilization virtual machines. +Virtual machines are considered low-utilization if their CPU utilization is 5% or less and their network utilization is less than 2% or if the current workload can be accommodated by a smaller virtual machine size. -If you would like to be more aggressive at identifying low usage virtual machines, you can adjust the average CPU utilization rule on a per subscription basis. The CPU utilization rule can be set to 5%, 10%, 15%, or 20%. +If you would like to be more aggressive at identifying low usage virtual machines, you can adjust the average CPU utilization rule and the look back period on a per subscription basis. +The CPU utilization rule can be set to 5%, 10%, 15%, 20%, or 100%(Default). In case the trigger is selected as 100%, it will present recommendations for virtual machines with less than 5%, 10%, 15%, and 20% of CPU utilization. +You can select how far back in historical data you want to analyze: 7 days (default), 14, 21, 30, 60, or 90 days. > [!NOTE] > To adjust the average CPU utilization rule for identifying low usage virtual machines, you must be a subscription *Owner*. If you do not have the required permissions for a subscription or resource group, the option to include or exclude it will be disabled in the user interface. |
aks | Auto Upgrade Node Image | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/aks/auto-upgrade-node-image.md | Title: Automatically upgrade Azure Kubernetes Service (AKS) cluster node operating system images description: Learn how to automatically upgrade Azure Kubernetes Service (AKS) cluster node operating system images. + Last updated 02/03/2023 az provider register --namespace Microsoft.ContainerService If using the `node-image` cluster auto-upgrade channel or the `NodeImage` node OS auto-upgrade channel, Linux [unattended upgrades][unattended-upgrades] are disabled by default. You can't change node OS auto-upgrade channel value if your cluster auto-upgrade channel is `node-image`. In order to set the node OS auto-upgrade channel values, make sure the [cluster auto-upgrade channel][Autoupgrade] isn't `node-image`. -The nodeosupgradechannel isn't supported on Windows OS nodepools. Mariner support is now rolled out and is expected to be available in all regions soon. +The nodeosupgradechannel isn't supported on Windows OS nodepools. Azure Linux support is now rolled out and is expected to be available in all regions soon. ## Using node OS auto-upgrade The following upgrade channels are available: |Channel|Description|OS-specific behavior| ||| | `None`| Your nodes won't have security updates applied automatically. This means you're solely responsible for your security updates|N/A|-| `Unmanaged`|OS updates are applied automatically through the OS built-in patching infrastructure. Newly allocated machines are unpatched initially and will be patched at some point by the OS's infrastructure|Ubuntu applies security patches through unattended upgrade roughly once a day around 06:00 UTC. Windows and Mariner don't apply security patches automatically, so this option behaves equivalently to `None`| +| `Unmanaged`|OS updates are applied automatically through the OS built-in patching infrastructure. Newly allocated machines are unpatched initially and will be patched at some point by the OS's infrastructure|Ubuntu applies security patches through unattended upgrade roughly once a day around 06:00 UTC. Windows and Azure Linux don't apply security patches automatically, so this option behaves equivalently to `None`| | `SecurityPatch`|AKS regularly updates the node's virtual hard disk (VHD) with patches from the image maintainer labeled "security only". There maybe disruptions when the security patches are applied to the nodes. When the patches are applied, the VHD is updated and existing machines are upgraded to that VHD, honoring maintenance windows and surge settings. This option incurs the extra cost of hosting the VHDs in your node resource group. If you use this channel, Linux [unattended upgrades][unattended-upgrades] are disabled by default.|N/A| | `NodeImage`|AKS updates the nodes with a newly patched VHD containing security fixes and bug fixes on a weekly cadence. The update to the new VHD is disruptive, following maintenance windows and surge settings. No extra VHD cost is incurred when choosing this option. If you use this channel, Linux [unattended upgrades][unattended-upgrades] are disabled by default.| |
aks | Automated Deployments | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/aks/automated-deployments.md | Title: Automated deployments for Azure Kubernetes Service (Preview) description: Learn how to use automated deployments to simplify the process of adding GitHub Actions to your Azure Kubernetes Service (AKS) project Previously updated : 7/21/2022+ Last updated : 05/10/2023 Automated deployments simplify the process of setting up a GitHub Action and cre ## Prerequisites -* A GitHub account. -* An AKS cluster. +* A GitHub account +* An AKS cluster * An Azure Container Registry (ACR)+* An application to deploy -## Deploy an application to your AKS cluster +## Configure an automated deployment -1. In the Azure portal, navigate to the resource group containing the AKS cluster you want to deploy the application to. +In the Azure portal, navigate to the resource group containing the AKS cluster you want to deploy the application to. -1. Select your AKS cluster, and then select **Automated deployments (preview)** on the left blade. Select **Create an automated deployment**. +Select your AKS cluster, and then select **Automated deployments (preview)** on the left blade. Upon selecting **Create**, you'll be presented with two options. If you have an application that isn't yet containerized, you can select **Automatically containerize and deploy** to allow Azure to take care of the process for you. If you already have a containerized application, select **Deploy an application**. - :::image type="content" source="media/automated-deployments/ad-homescreen.png" alt-text="The automated deployments screen in the Azure portal." lightbox="media/automated-deployments/ad-homescreen-expanded.png"::: -1. Name your workflow and click **Authorize** to connect your Azure account with your GitHub account. After your accounts are linked, choose which repository and branch you would like to create the GitHub Action for. +Name your workflow and click **Authorize** to connect your Azure account with your GitHub account. After your accounts are linked, choose which repository and branch you would like to create the GitHub Action for. - - **GitHub**: Authorize and select the repository for your GitHub account. +- **GitHub**: Authorize and select the repository for your GitHub account. - :::image type="content" source="media/automated-deployments/ad-ghactivate-repo.png" alt-text="The authorize and repository selection screen." lightbox="media/automated-deployments/ad-ghactivate-repo-expanded.png"::: + :::image type="content" source="media/automated-deployments/ad-ghactivate-repo.png" alt-text="The authorize and repository selection screen." lightbox="media/automated-deployments/ad-ghactivate-repo-expanded.png"::: -1. Pick your dockerfile and your ACR and image. +Next, follow along with the section below that relates to the option you chose. - :::image type="content" source="media/automated-deployments/ad-image.png" alt-text="The image selection screen." lightbox="media/automated-deployments/ad-image-expanded.png"::: +### Automatically containerize and deploy an application to your AKS cluster -1. Determine whether you'll deploy with Helm or regular Kubernetes manifests. Once decided, pick the appropriate deployment files from your repository and decide which namespace you want to deploy into. +Fill out the fields, providing details about your application that will be used to automatically generate deployment artifacts. - :::image type="content" source="media/automated-deployments/ad-deployment-details.png" alt-text="The deployment details screen." lightbox="media/automated-deployments/ad-deployment-details-expanded.png"::: -1. Review your deployment before creating the pull request. +Proceed to review and verify the automated deployment. ++### Deploy an already containerized application to your AKS cluster ++Pick your dockerfile and your ACR and image. +++Determine whether you'll deploy with Helm or regular Kubernetes manifests. Once decided, pick the appropriate deployment files from your repository and decide which namespace you want to deploy into. +++Proceed to review and verify the automated deployment. ++## Review and verify the automated deployment ++1. When finished, select **Next: Deployment details** and **Next: Review**, and review your deployment. Finally, select **Next: Deploy** to finish the creation of the automated deployment. 1. Click **view pull request** to see your GitHub Action. |
aks | Azure Cni Powered By Cilium | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/aks/azure-cni-powered-by-cilium.md | Title: Configure Azure CNI Powered by Cilium in Azure Kubernetes Service (AKS) (Preview) + Title: Configure Azure CNI Powered by Cilium in Azure Kubernetes Service (AKS) description: Learn how to create an Azure Kubernetes Service (AKS) cluster with Azure CNI Powered by Cilium. - Previously updated : 10/24/2022+ Last updated : 05/24/2023 -# Configure Azure CNI Powered by Cilium in Azure Kubernetes Service (AKS) (Preview) +# Configure Azure CNI Powered by Cilium in Azure Kubernetes Service (AKS) -Azure CNI Powered by Cilium combines the robust control plane of Azure CNI with the dataplane of [Cilium](https://cilium.io/) to provide high-performance networking and security. +Azure CNI Powered by Cilium combines the robust control plane of Azure CNI with the data plane of [Cilium](https://cilium.io/) to provide high-performance networking and security. By making use of eBPF programs loaded into the Linux kernel and a more efficient API object structure, Azure CNI Powered by Cilium provides the following benefits: - Functionality equivalent to existing Azure CNI and Azure CNI Overlay plugins+ - Faster service routing+ - More efficient network policy enforcement+ - Better observability of cluster traffic+ - Support for larger clusters (more nodes, pods, and services) ## IP Address Management (IPAM) with Azure CNI Powered by Cilium Azure CNI Powered by Cilium can be deployed using two different methods for assigning pod IPs: -- assign IP addresses from a VNet (similar to existing Azure CNI with Dynamic Pod IP Assignment)-- assign IP addresses from an overlay network (similar to Azure CNI Overlay mode)+- Assign IP addresses from a virtual network (similar to existing Azure CNI with Dynamic Pod IP Assignment) ++- Assign IP addresses from an overlay network (similar to Azure CNI Overlay mode) If you aren't sure which option to select, read ["Choosing a network model to use"](./azure-cni-overlay.md#choosing-a-network-model-to-use). Cilium enforces [network policies to allow or deny traffic between pods](./opera Azure CNI powered by Cilium currently has the following limitations: * Available only for new clusters.+ * Available only for Linux and not for Windows.+ * Cilium L7 policy enforcement is disabled.+ * Hubble is disabled.+ * Not compatible with Istio or other sidecar-based service meshes ([Istio issue #27619](https://github.com/istio/istio/issues/27619)).+ * Kubernetes services with `internalTrafficPolicy=Local` aren't supported ([Cilium issue #17796](https://github.com/cilium/cilium/issues/17796)).+ * Multiple Kubernetes services can't use the same host port with different protocols (for example, TCP or UDP) ([Cilium issue #14287](https://github.com/cilium/cilium/issues/14287)).+ * Network policies may be enforced on reply packets when a pod connects to itself via service cluster IP ([Cilium issue #19406](https://github.com/cilium/cilium/issues/19406)). ## Prerequisites -* Azure CLI version 2.41.0 or later. Run `az --version` to see the currently installed version. If you need to install or upgrade, see [Install Azure CLI](/cli/azure/install-azure-cli). -* Azure CLI with aks-preview extension 0.5.135 or later. +* Azure CLI version 2.48.1 or later. Run `az --version` to see the currently installed version. If you need to install or upgrade, see [Install Azure CLI](/cli/azure/install-azure-cli). + * If using ARM templates or the REST API, the AKS API version must be 2022-09-02-preview or later. > [!NOTE] > Previous AKS API versions (2022-09-02preview to 2023-01-02preview) used the field [`networkProfile.ebpfDataplane=cilium`](https://github.com/Azure/azure-rest-api-specs/blob/06dbe269f7d9c709cc225c92358b38c3c2b74d60/specification/containerservice/resource-manager/Microsoft.ContainerService/aks/preview/2022-09-02-preview/managedClusters.json#L6939-L6955). AKS API versions since 2023-02-02preview use the field [`networkProfile.networkDataplane=cilium`](https://github.com/Azure/azure-rest-api-specs/blob/06dbe269f7d9c709cc225c92358b38c3c2b74d60/specification/containerservice/resource-manager/Microsoft.ContainerService/aks/preview/2023-02-02-preview/managedClusters.json#L7152-L7173) to enable Azure CNI Powered by Cilium. -## Install the aks-preview Azure CLI extension ---To install the aks-preview extension, run the following command: --```azurecli -az extension add --name aks-preview -``` --Run the following command to update to the latest version of the extension released: --```azurecli -az extension update --name aks-preview -``` --## Register the 'CiliumDataplanePreview' feature flag --Register the `CiliumDataplanePreview` feature flag by using the [az feature register][az-feature-register] command, as shown in the following example: --```azurecli-interactive -az feature register --namespace "Microsoft.ContainerService" --name "CiliumDataplanePreview" -``` --It takes a few minutes for the status to show *Registered*. Verify the registration status by using the [az feature show][az-feature-show] command: --```azurecli-interactive -az feature show --namespace "Microsoft.ContainerService" --name "CiliumDataplanePreview" -``` --When the status reflects *Registered*, refresh the registration of the *Microsoft.ContainerService* resource provider by using the [az provider register][az-provider-register] command: --```azurecli-interactive -az provider register --namespace Microsoft.ContainerService -``` - ## Create a new AKS Cluster with Azure CNI Powered by Cilium -### Option 1: Assign IP addresses from a VNet +### Option 1: Assign IP addresses from a virtual network -Run the following commands to create a resource group and VNet with a subnet for nodes and a subnet for pods. +Run the following commands to create a resource group and virtual network with a subnet for nodes and a subnet for pods. ```azurecli-interactive # Create the resource group az group create --name <resourceGroupName> --location <location> ``` ```azurecli-interactive-# Create a VNet with a subnet for nodes and a subnet for pods +# Create a virtual network with a subnet for nodes and a subnet for pods az network vnet create -g <resourceGroupName> --location <location> --name <vnetName> --address-prefixes <address prefix, example: 10.0.0.0/8> -o none az network vnet subnet create -g <resourceGroupName> --vnet-name <vnetName> --name nodesubnet --address-prefixes <address prefix, example: 10.240.0.0/16> -o none az network vnet subnet create -g <resourceGroupName> --vnet-name <vnetName> --name podsubnet --address-prefixes <address prefix, example: 10.241.0.0/16> -o none az aks create -n <clusterName> -g <resourceGroupName> -l <location> \ ### Option 2: Assign IP addresses from an overlay network -Run this commands to create a cluster with an overlay network and Cilium. Replace the values for `<clusterName>`, `<resourceGroupName>`, and `<location>`: +Use the following commands to create a cluster with an overlay network and Cilium. Replace the values for `<clusterName>`, `<resourceGroupName>`, and `<location>`: ```azurecli-interactive az aks create -n <clusterName> -g <resourceGroupName> -l <location> \ az aks create -n <clusterName> -g <resourceGroupName> -l <location> \ ## Frequently asked questions -- *Can I customize Cilium configuration?*+- **Can I customize Cilium configuration?** - No, the Cilium configuration is managed by AKS and can't be modified. We recommend that customers who require more control use [AKS BYO CNI](./use-byo-cni.md) and install Cilium manually. + No, AKS manages the Cilium configuration and it can't be modified. We recommend that customers who require more control use [AKS BYO CNI](./use-byo-cni.md) and install Cilium manually. -- *Can I use `CiliumNetworkPolicy` custom resources instead of Kubernetes `NetworkPolicy` resources?*+- **Can I use `CiliumNetworkPolicy` custom resources instead of Kubernetes `NetworkPolicy` resources?** `CiliumNetworkPolicy` custom resources aren't officially supported. We recommend that customers use Kubernetes `NetworkPolicy` resources to configure network policies. -- *Does AKS configure CPU or memory limits on the Cilium daemonset?*+- **Does AKS configure CPU or memory limits on the Cilium `daemonset`?** - No, AKS does not configure CPU or memory limits on the Cilium daemonset because Cilium is a critical system component for pod networking and network policy enforcement. + No, AKS doesn't configure CPU or memory limits on the Cilium `daemonset` because Cilium is a critical system component for pod networking and network policy enforcement. ## Next steps Learn more about networking in AKS in the following articles: * [Use a static IP address with the Azure Kubernetes Service (AKS) load balancer](static-ip.md)+ * [Use an internal load balancer with Azure Container Service (AKS)](internal-lb.md) * [Create a basic ingress controller with external network connectivity][aks-ingress-basic]-* [Enable the HTTP application routing add-on][aks-http-app-routing] -* [Create an ingress controller that uses an internal, private network and IP address][aks-ingress-internal] -* [Create an ingress controller with a dynamic public IP and configure Let's Encrypt to automatically generate TLS certificates][aks-ingress-tls] -* [Create an ingress controller with a static public IP and configure Let's Encrypt to automatically generate TLS certificates][aks-ingress-static-tls] <!-- LINKS - Internal --> [aks-ingress-basic]: ingress-basic.md-[aks-ingress-tls]: ingress-tls.md -[aks-ingress-static-tls]: ingress-static-ip.md -[aks-http-app-routing]: http-application-routing.md -[aks-ingress-internal]: ingress-internal-ip.md -[az-provider-register]: /cli/azure/provider#az-provider-register -[az-feature-register]: /cli/azure/feature#az-feature-register -[az-feature-show]: /cli/azure/feature#az-feature-show |
aks | Cluster Configuration | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/aks/cluster-configuration.md | Title: Cluster configuration in Azure Kubernetes Services (AKS) description: Learn how to configure a cluster in Azure Kubernetes Service (AKS) -+ Last updated 02/16/2023 By using `containerd` for AKS nodes, pod startup latency improves and node resou Azure supports [Generation 2 (Gen2) virtual machines (VMs)](../virtual-machines/generation-2.md). Generation 2 VMs support key features not supported in generation 1 VMs (Gen1). These features include increased memory, Intel Software Guard Extensions (Intel SGX), and virtualized persistent memory (vPMEM). -Generation 2 VMs use the new UEFI-based boot architecture rather than the BIOS-based architecture used by generation 1 VMs. -Only specific SKUs and sizes support Gen2 VMs. Check the [list of supported sizes](../virtual-machines/generation-2.md#generation-2-vm-sizes), to see if your SKU supports or requires Gen2. +Generation 2 VMs use the new UEFI-based boot architecture rather than the BIOS-based architecture used by generation 1 VMs. Only specific SKUs and sizes support Gen2 VMs. Check the [list of supported sizes](../virtual-machines/generation-2.md#generation-2-vm-sizes), to see if your SKU supports or requires Gen2. Additionally, not all VM images support Gen2 VMs. On AKS, Gen2 VMs use [AKS Ubuntu 22.04 or 18.04 image](#os-configuration) or [AKS Windows Server 2022 image](#os-configuration). These images support all Gen2 SKUs and sizes. +Gen2 VMs are supported on Linux. Gen2 VMs on Windows are supported for WS2022 only. ++### Generation 2 virtual machines on Windows (preview) +++* Generation 2 VMs are supported on Windows for WS2022 only. +* Generation 2 VMs are default for Windows clusters greater than or equal to Kubernetes 1.25. + * If your Kubernetes version is greater than 1.25, you only need to set the `vm_size` to get the generation 2 node pool. You can still use WS2019 generation 1 if you define that in the `os_sku`. + * If your Kubernetes version less than 1.25, you can set the `os_sku` to WS2022 and set the `vm_size` to generation 2 to get the generation 2 node pool. ++Follow the Azure CLI commands to use generation 2 VMs on Windows: ++```azurecli +# Sample command ++az aks nodepool add --resource-group myResourceGroup --cluster-name myAKSCluster --name gen2np +--kubernetes-version 1.23.5 --node-vm-size Standard_D32_v4 --os-type Windows --os_sku Windows2022 ++# Default command ++az aks nodepool add --resource-group myResourceGroup --cluster-name myAKSCluster --name gen2np --os-type Windows --kubernetes-version 1.23.5 ++``` ++To determine if you're on generation 1 or generation 2, run the following command from the nodepool level and check that the `nodeImageVersion` contains `gen2`: ++```azurecli +az aks nodepool show +``` ++To determine available generation 2 VM sizes, run the following command: ++```azurecli +az vm list -skus -l $region +``` ++For more information, see [Support for generation 2 VMs on Azure](../virtual-machines/generation-2.md). + ## Default OS disk sizing When you create a new cluster or add a new node pool to an existing cluster, by default the OS disk size is determined by the number for vCPUs. The number of vCPUs is based on the VM SKU, and in the following table we list the default values: az aks nodepool add --name ephemeral --cluster-name myAKSCluster --resource-grou If you want to create node pools with network-attached OS disks, you can do so by specifying `--node-osdisk-type Managed`. -## Mariner OS +## Azure Linux container host for AKS -Mariner can be deployed on AKS through Azure CLI or ARM templates. +You can deploy the Azure Linux container host for through Azure CLI or ARM templates. ### Prerequisites 1. You need the Azure CLI version 2.44.1 or later installed and configured. Run `az --version` to find the version currently installed. If you need to install or upgrade, see [Install Azure CLI][azure-cli-install]. 1. If you don't already have kubectl installed, install it through Azure CLI using `az aks install-cli` or follow the [upstream instructions](https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/). -### Deploy an AKS Mariner cluster with Azure CLI +### Deploy an Azure Linux AKS cluster with Azure CLI -Use the following example commands to create a Mariner cluster. +Use the following example commands to create an Azure Linux cluster. ```azurecli-az group create --name MarinerTest --location eastus +az group create --name AzureLinuxTest --location eastus -az aks create --name testMarinerCluster --resource-group MarinerTest --os-sku mariner --generate-ssh-keys +az aks create --name testAzureLinuxCluster --resource-group AzureLinuxTest --os-sku AzureLinux --generate-ssh-keys -az aks get-credentials --resource-group MarinerTest --name testMarinerCluster +az aks get-credentials --resource-group AzureLinuxTest --name testAzureLinuxCluster kubectl get pods --all-namespaces ``` -### Deploy an AKS Mariner cluster with an ARM template +### Deploy an Azure Linux AKS cluster with an ARM template -To add Mariner to an existing ARM template, you need to do the following: +To add Azure Linux to an existing ARM template, you need to do the following: -- Add `"osSKU": "mariner"` and `"mode": "System"` to agentPoolProfiles property.+- Add `"osSKU": "AzureLinux"` and `"mode": "System"` to agentPoolProfiles property. - Set the apiVersion to 2021-03-01 or newer: `"apiVersion": "2021-03-01"` -The following deployment uses the ARM template `marineraksarm.json`. +The following deployment uses the ARM template `azurelinuxaksarm.json`. ```json { The following deployment uses the ARM template `marineraksarm.json`. "parameters": { "clusterName": { "type": "string",- "defaultValue": "marinerakscluster", + "defaultValue": "azurelinuxakscluster", "metadata": { "description": "The name of the Managed Cluster resource." } The following deployment uses the ARM template `marineraksarm.json`. }, "dnsPrefix": { "type": "string",- "defaultValue": "mariner", + "defaultValue": "azurelinux", "metadata": { "description": "Optional DNS prefix to use with hosted Kubernetes API server FQDN." } The following deployment uses the ARM template `marineraksarm.json`. }, "osSKU": { "type": "string",- "defaultValue": "mariner", + "defaultValue": "azurelinux", "allowedValues": [- "mariner", + "AzureLinux", "Ubuntu", ], "metadata": { The following deployment uses the ARM template `marineraksarm.json`. } ``` -Create this file on your system and include the settings defined in the `marineraksarm.json` file. +Create this file on your system and include the settings defined in the `azurelinuxaksarm.json` file. ```azurecli-az group create --name MarinerTest --location eastus +az group create --name AzureLinuxTest --location eastus -az deployment group create --resource-group MarinerTest --template-file marineraksarm.json --parameters linuxAdminUsername=azureuser sshRSAPublicKey=`<contents of your id_rsa.pub>` +az deployment group create --resource-group AzureLinuxTest --template-file azurelinuxaksarm.json --parameters linuxAdminUsername=azureuser sshRSAPublicKey=`<contents of your id_rsa.pub>` -az aks get-credentials --resource-group MarinerTest --name testMarinerCluster +az aks get-credentials --resource-group AzureLinuxTest --name testAzureLinuxCluster kubectl get pods --all-namespaces ``` -### Deploy an AKS Mariner cluster with Terraform +### Deploy an Azure Linux AKS cluster with Terraform -To deploy a Mariner cluster with Terraform, you first need to set your `azurerm` provider to version 2.76 or higher. +To deploy an Azure Linux cluster with Terraform, you first need to set your `azurerm` provider to version 2.76 or higher. ``` required_providers { required_providers { } ``` -Once you've updated your `azurerm` provider, you can specify the Mariner `os_sku` in `default_node_pool`. +Once you've updated your `azurerm` provider, you can specify the AzureLinux `os_sku` in `default_node_pool`. ``` default_node_pool { name = "default" node_count = 2 vm_size = "Standard_D2_v2"- os_sku = "mariner" + os_sku = "AzureLinux" } ``` -Similarly, you can specify the Mariner `os_sku` in [`azurerm_kubernetes_cluster_node_pool`][azurerm-mariner]. +Similarly, you can specify the AzureLinux `os_sku` in [`azurerm_kubernetes_cluster_node_pool`][azurerm-azurelinux]. ## Custom resource group name az aks update -n aksTest -g aksTest ΓÇô-nrg-lockdown-restriction-level Unrestric <!-- LINKS - external --> [aks-release-notes]: https://github.com/Azure/AKS/releases-[azurerm-mariner]: https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/kubernetes_cluster_node_pool#os_sku +[azurerm-azurelinux]: https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/kubernetes_cluster_node_pool#os_sku [general-usage]: https://kubernetes.io/docs/tasks/debug/debug-cluster/crictl/#general-usage [client-config-options]: https://github.com/kubernetes-sigs/cri-tools/blob/master/docs/crictl.md#client-configuration-options az aks update -n aksTest -g aksTest ΓÇô-nrg-lockdown-restriction-level Unrestric [az-aks-create]: /cli/azure/aks#az-aks-create [az-aks-update]: /cli/azure/aks#az-aks-update [baseline-reference-architecture-aks]: /azure/architecture/reference-architectures/containers/aks/baseline-aks-[whatis-nrg]: ./concepts-clusters-workloads.md#node-resource-group +[whatis-nrg]: ./concepts-clusters-workloads.md#node-resource-group |
aks | Concepts Clusters Workloads | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/aks/concepts-clusters-workloads.md | Title: Concepts - Kubernetes basics for Azure Kubernetes Services (AKS) description: Learn the basic cluster and workload components of Kubernetes and how they relate to features in Azure Kubernetes Service (AKS) + Last updated 10/31/2022- # Kubernetes core concepts for Azure Kubernetes Service (AKS) The control plane includes the following core Kubernetes components: | *kube-apiserver* | The API server is how the underlying Kubernetes APIs are exposed. This component provides the interaction for management tools, such as `kubectl` or the Kubernetes dashboard. | | *etcd* | To maintain the state of your Kubernetes cluster and configuration, the highly available *etcd* is a key value store within Kubernetes. | | *kube-scheduler* | When you create or scale applications, the Scheduler determines what nodes can run the workload and starts them. | -| *kube-controller-manager* | The Controller Manager oversees a number of smaller Controllers that perform actions such as replicating pods and handling node operations. | +| *kube-controller-manager* | The Controller Manager oversees a number of smaller controllers that perform actions such as replicating pods and handling node operations. | AKS provides a single-tenant control plane, with a dedicated API server, scheduler, etc. You define the number and size of the nodes, and the Azure platform configures the secure communication between the control plane and nodes. Interaction with the control plane occurs through Kubernetes APIs, such as `kubectl` or the Kubernetes dashboard. To configure or directly access a control plane, deploy a self-managed Kubernete For associated best practices, see [Best practices for cluster security and upgrades in AKS][operator-best-practices-cluster-security]. -For AKS cost management information, see [AKS cost basics](https://learn.microsoft.com/azure/architecture/aws-professional/eks-to-aks/cost-management#aks-cost-basics) and [Pricing for AKS](https://azure.microsoft.com/pricing/details/kubernetes-service/#pricing). +For AKS cost management information, see [AKS cost basics](/azure/architecture/aws-professional/eks-to-aks/cost-management#aks-cost-basics) and [Pricing for AKS](https://azure.microsoft.com/pricing/details/kubernetes-service/#pricing). ## Nodes and node pools To run your applications and supporting services, you need a Kubernetes *node*. The Azure VM size for your nodes defines CPUs, memory, size, and the storage type available (such as high-performance SSD or regular HDD). Plan the node size around whether your applications may require large amounts of CPU and memory or high-performance storage. Scale out the number of nodes in your AKS cluster to meet demand. For more information on scaling, see [Scaling options for applications in AKS](concepts-scale.md). -In AKS, the VM image for your cluster's nodes is based on Ubuntu Linux, [Mariner Linux](use-mariner.md), or Windows Server 2019. When you create an AKS cluster or scale out the number of nodes, the Azure platform automatically creates and configures the requested number of VMs. Agent nodes are billed as standard VMs, so any VM size discounts (including [Azure reservations][reservation-discounts]) are automatically applied. +In AKS, the VM image for your cluster's nodes is based on Ubuntu Linux, [Azure Linux](use-azure-linux.md), or Windows Server 2019. When you create an AKS cluster or scale out the number of nodes, the Azure platform automatically creates and configures the requested number of VMs. Agent nodes are billed as standard VMs, so any VM size discounts (including [Azure reservations][reservation-discounts]) are automatically applied. For managed disks, the default disk size and performance will be assigned according to the selected VM SKU and vCPU count. For more information, see [Default OS disk sizing](cluster-configuration.md#default-os-disk-sizing). Two types of resources are reserved: 1. **`kubelet` daemon** The `kubelet` daemon is installed on all Kubernetes agent nodes to manage container creation and termination. - By default on AKS, `kubelet` daemon has the *memory.available<750Mi* eviction rule, ensuring a node must always have at least 750 Mi allocatable at all times. When a host is below that available memory threshold, the `kubelet` will trigger to terminate one of the running pods and free up memory on the host machine. + By default on AKS, `kubelet` daemon has the *memory.available<750Mi* eviction rule, ensuring a node must always have at least 750Mi allocatable at all times. When a host is below that available memory threshold, the `kubelet` will trigger to terminate one of the running pods and free up memory on the host machine. 2. **A regressive rate of memory reservations** for the kubelet daemon to properly function (*kube-reserved*). - 25% of the first 4 GB of memory Two types of resources are reserved: >[!NOTE] > AKS reserves an additional 2GB for system process in Windows nodes that are not part of the calculated memory. -Memory and CPU allocation rules: -* Keep agent nodes healthy, including some hosting system pods critical to cluster health. -* Cause the node to report less allocatable memory and CPU than it would if it were not part of a Kubernetes cluster. +Memory and CPU allocation rules are designed to do the following: ++* Keep agent nodes healthy, including some hosting system pods critical to cluster health. +* Cause the node to report less allocatable memory and CPU than it would report if it weren't part of a Kubernetes cluster. The above resource reservations can't be changed. The node resource group has the following limitations: If you modify or delete Azure-created tags and other resource properties in the node resource group, you could get unexpected results, such as scaling and upgrading errors. As AKS manages the lifecycle of infrastructure in the Node Resource Group, any changes will move your cluster into an [unsupported state][aks-support]. -A common scenario where customers want to modify resources is through tags. AKS allows you to create and modify tags that are propogated to resources in the Node Resource Group, and you can add those tags when [creating or updating][aks-tags] the cluster. You might want to create or modify custom tags, for example, to assign a business unit or cost center. This can also be achieved by creating Azure Policies with a scope on the managed resource group. +A common scenario where customers want to modify resources is through tags. AKS allows you to create and modify tags that are propagated to resources in the Node Resource Group, and you can add those tags when [creating or updating][aks-tags] the cluster. You might want to create or modify custom tags, for example, to assign a business unit or cost center. This can also be achieved by creating Azure Policies with a scope on the managed resource group. Modifying any **Azure-created tags** on resources under the node resource group in the AKS cluster is an unsupported action, which breaks the service-level objective (SLO). For more information, see [Does AKS offer a service-level agreement?][aks-service-level-agreement] A breakdown of the deployment specifications in the YAML manifest file is as fol | `.apiVersion` | Specifies the API group and API resource you want to use when creating the resource. | | `.kind` | Specifies the type of resource you want to create. | | `.metadata.name` | Specifies the name of the deployment. This file will run the *nginx* image from Docker Hub. | -| `.spec.replicas` | Specifies how many pods to create. This file will create three deplicated pods. | +| `.spec.replicas` | Specifies how many pods to create. This file will create three duplicate pods. | | `.spec.selector` | Specifies which pods will be affected by this deployment. |-| `.spec.selector.matchLabels` | Contains a map of *{key, value}* pairs that allows the deployment to find and manage the created pods. | +| `.spec.selector.matchLabels` | Contains a map of *{key, value}* pairs that allow the deployment to find and manage the created pods. | | `.spec.selector.matchLabels.app` | Has to match `.spec.template.metadata.labels`. | | `.spec.template.labels` | Specifies the *{key, value}* pairs attached to the object. | | `.spec.template.app` | Has to match `.spec.selector.matchLabels`. | A breakdown of the deployment specifications in the YAML manifest file is as fol | `.spec.spec.containers.name` | Specifies the name of the container specified as a DNS label. | | `.spec.spec.containers.image` | Specifies the container image name. | | `.spec.spec.containers.ports` | Specifies the list of ports to expose from the container. | -| `.spec.spec.containers.ports.containerPort` | Specifies the number of port to expose on the pod's IP address. | +| `.spec.spec.containers.ports.containerPort` | Specifies the number of ports to expose on the pod's IP address. | | `.spec.spec.resources` | Specifies the compute resources required by the container. | | `.spec.spec.resources.requests` | Specifies the minimum amount of compute resources required. | | `.spec.spec.resources.requests.cpu` | Specifies the minimum amount of CPU required. | To use Helm, install the Helm client on your computer, or use the Helm client in ## StatefulSets and DaemonSets -Using the Kubernetes Scheduler, the Deployment Controller runs replicas on any available node with available resources. While this approach may be sufficient for stateless applications, The Deployment Controller is not ideal for applications that require: -* A persistent naming convention or storage. +Using the Kubernetes Scheduler, the Deployment Controller runs replicas on any available node with available resources. While this approach may be sufficient for stateless applications, the Deployment Controller isn't ideal for applications that require: ++* A persistent naming convention or storage. * A replica to exist on each select node within a cluster. Two Kubernetes resources, however, let you manage these types of applications: For more information, see [Kubernetes DaemonSets][kubernetes-daemonset]. ## Namespaces -Kubernetes resources, such as pods and deployments, are logically grouped into a *namespace* to divide an AKS cluster and restrict create, view, or manage access to resources. For example, you can create namespaces to separate business groups. Users can only interact with resources within their assigned namespaces. +Kubernetes resources, such as pods and deployments, are logically grouped into a *namespace* to divide an AKS cluster and create, view, or manage access to resources. For example, you can create namespaces to separate business groups. Users can only interact with resources within their assigned namespaces.  This article covers some of the core Kubernetes components and how they apply to [configure-nrg]: ./cluster-configuration.md#fully-managed-resource-group-preview [aks-service-level-agreement]: faq.md#does-aks-offer-a-service-level-agreement [aks-tags]: use-tags.md-[aks-support]: support-policies.md#user-customization-of-agent-nodes +[aks-support]: support-policies.md#user-customization-of-agent-nodes |
aks | Concepts Security | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/aks/concepts-security.md | Title: Concepts - Security in Azure Kubernetes Services (AKS) description: Learn about security in Azure Kubernetes Service (AKS), including master and node communication, network policies, and Kubernetes secrets. + Last updated 02/28/2023 You can control access to the API server using Kubernetes role-based access cont AKS nodes are Azure virtual machines (VMs) that you manage and maintain. -* Linux nodes run optimized versions of Ubuntu or Mariner. +* Linux nodes run optimized versions of Ubuntu or Azure Linux. * Windows Server nodes run an optimized Windows Server 2019 release using the `containerd` or Docker container runtime. When an AKS cluster is created or scaled up, the nodes are automatically deployed with the latest OS security updates and configurations. |
aks | Concepts Vulnerability Management | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/aks/concepts-vulnerability-management.md | Title: Vulnerability management for Azure Kubernetes Service description: Learn how Microsoft manages security vulnerabilities for Azure Kubernetes Service (AKS) clusters. + Last updated 03/17/2023- # Vulnerability management for Azure Kubernetes Service (AKS) Microsoft identifies and patches vulnerabilities and missing security updates fo - Windows Server 2022 OS worker nodes: The Windows Server operating system is patched on the second Tuesday of every month. SLAs should be the same as per their support contract and severity. -- Mariner OS Nodes: Mariner provides AKS with OS builds that have all available security updates applied.+- Azure Linux OS Nodes: Azure Linux provides AKS with OS builds that have all available security updates applied. ## AKS Container Images The following table describes vulnerability severity categories: ## How vulnerabilities are updated -AKS patches CVE's that has a *vendor fix* every week. CVE's without a fix are waiting on a *vendor fix* before it can be remediated. The fixed container images are cached in the next corresponding Virtual Hard Disk (VHD) build, which also contains the updated Ubuntu/Mariner/Windows patched CVE's. As long as you're running the updated VHD, you shouldn't be running any container image CVE's with a vendor fix that is over 30 days old. +AKS patches CVE's that has a *vendor fix* every week. CVE's without a fix are waiting on a *vendor fix* before it can be remediated. The fixed container images are cached in the next corresponding Virtual Hard Disk (VHD) build, which also contains the updated Ubuntu/Azure Linux/Windows patched CVE's. As long as you're running the updated VHD, you shouldn't be running any container image CVE's with a vendor fix that is over 30 days old. For the OS-based vulnerabilities in the VHD, AKS uses **Unattended Update** by default, so any security updates should be applied to the existing VHD's daily. If **Unattended Update** is disabled, then it's a recommended best practice that you apply a Node Image update on a regular cadence to ensure the latest OS and Image security updates are applied. |
aks | Configure Kubenet Dual Stack | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/aks/configure-kubenet-dual-stack.md | description: Learn how to configure dual-stack kubenet networking in Azure Kuber -+ Last updated 12/15/2021 This article shows you how to use dual-stack networking with an AKS cluster. For ## Limitations * Azure Route Tables have a hard limit of 400 routes per table. Because each node in a dual-stack cluster requires two routes, one for each IP address family, dual-stack clusters are limited to 200 nodes.-* In Mariner node pools, service objects are only supported with `externalTrafficPolicy: Local`. +* In Azure Linux node pools, service objects are only supported with `externalTrafficPolicy: Local`. * Dual-stack networking is required for the Azure Virtual Network and the pod CIDR - single stack IPv6-only isn't supported for node or pod IP addresses. Services can be provisioned on IPv4 or IPv6. * Features **not supported on dual-stack kubenet** include: * [Azure network policies](use-network-policies.md#create-an-aks-cluster-and-enable-network-policy) nginx-55649fd747-r2rqh 10.244.1.2,fd12:3456:789a:0:1::2 aks-nodepool1-145084 > [!IMPORTANT] > There are currently two limitations pertaining to IPv6 services in AKS. These are both preview limitations and work is underway to remove them.-> * Azure Load Balancer sends health probes to IPv6 destinations from a link-local address. In Mariner node pools, this traffic cannot be routed to a pod and thus traffic flowing to IPv6 services deployed with `externalTrafficPolicy: Cluster` will fail. IPv6 services MUST be deployed with `externalTrafficPolicy: Local`, which causes `kube-proxy` to respond to the probe on the node, in order to function. +> * Azure Load Balancer sends health probes to IPv6 destinations from a link-local address. In Azure Linux node pools, this traffic cannot be routed to a pod and thus traffic flowing to IPv6 services deployed with `externalTrafficPolicy: Cluster` will fail. IPv6 services MUST be deployed with `externalTrafficPolicy: Local`, which causes `kube-proxy` to respond to the probe on the node, in order to function. > * Only the first IP address for a service will be provisioned to the load balancer, so a dual-stack service will only receive a public IP for its first listed IP family. In order to provide a dual-stack service for a single deployment, please create two services targeting the same selector, one for IPv4 and one for IPv6. IPv6 services in Kubernetes can be exposed publicly similarly to an IPv4 service. |
aks | Dapr Settings | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/aks/dapr-settings.md | description: Learn how to configure the Dapr extension specifically for your Azu + Last updated 01/09/2023 If you want to use an outbound proxy with the Dapr extension for AKS, you can do - `NO_PROXY` 1. [Installing the proxy certificate in the sidecar](https://docs.dapr.io/operations/configuration/install-certificates/). -## Using Mariner-based images +## Using Azure Linux-based images -From Dapr version 1.8.0, you can use Mariner images with the Dapr extension. To use them, set the`global.tag` flag: +From Dapr version 1.8.0, you can use Azure Linux images with the Dapr extension. To use them, set the`global.tag` flag: ```azurecli az k8s-extension upgrade --cluster-type managedClusters \ az k8s-extension upgrade --cluster-type managedClusters \ --resource-group myResourceGroup \ --name dapr \ --extension-type Microsoft.Dapr \set global.tag=1.10.0-mariner+--set global.tag=1.10.0-AzureLinux ``` -- [Learn more about using Mariner-based images with Dapr.][dapr-mariner]-- [Learn more about deploying Mariner on AKS.][aks-mariner]+- [Learn more about using AzureLinux-based images with Dapr][dapr-azurelinux]. +- [Learn more about deploying AzureLinux on AKS][aks-azurelinux]. ## Disable automatic CRD updates Once you have successfully provisioned Dapr in your AKS cluster, try deploying a [install-cli]: /cli/azure/install-azure-cli [dapr-migration]: ./dapr-migration.md [dapr-settings]: ./dapr-settings.md-[aks-mariner]: ./cluster-configuration.md#mariner-os +[aks-azurelinux]: ./cluster-configuration.md#azure-linux-container-host-for-aks <!-- LINKS EXTERNAL --> Once you have successfully provisioned Dapr in your AKS cluster, try deploying a [dapr-supported-version]: https://docs.dapr.io/operations/support/support-release-policy/#supported-versions [dapr-troubleshooting]: https://docs.dapr.io/operations/troubleshooting/common_issues/ [supported-cloud-regions]: https://azure.microsoft.com/global-infrastructure/services/?products=azure-arc-[dapr-mariner]: https://docs.dapr.io/operations/hosting/kubernetes/kubernetes-deploy/#using-mariner-based-images +[dapr-azurelinux]: https://docs.dapr.io/operations/hosting/kubernetes/kubernetes-deploy/#using-azurelinux-based-images |
aks | Gpu Multi Instance | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/aks/gpu-multi-instance.md | This article will walk you through how to create a multi-instance GPU node pool ## GPU Instance Profile -GPU Instance Profiles define how a GPU will be partitioned. The following table shows the available GPU Instance Profile for the `Standard_ND96asr_v4`, the only instance type that supports the A100 GPU at this time. +GPU Instance Profiles define how a GPU will be partitioned. The following table shows the available GPU Instance Profile for the `Standard_ND96asr_v4` | Profile Name | Fraction of SM |Fraction of Memory | Number of Instances created | kubectl describe node mignode ``` If you're using single strategy, you'll see: ```-Allocable: +Allocatable: nvidia.com/gpu: 56 ``` If you're using mixed strategy, you'll see: ```-Allocable: +Allocatable: nvidia.com/mig-1g.5gb: 56 ``` ### Schedule work-Use the `kubectl` run command to schedule work using single strategy: -``` -kubectl run -it --rm \ image=nvidia/cuda:11.0-base \restart=Never \limits=nvidia.com/gpu=1 \-single-strategy-example -- nvidia-smi -L -``` -Use the `kubectl` run command to schedule work using mixed strategy: -``` -kubectl run -it --rm \ image=nvidia/cuda:11.0-base \restart=Never \limits=nvidia.com/mig-1g.5gb=1 \-mixed-strategy-example -- nvidia-smi -L -``` +The following examples are based on cuda base image version 12.1.1 for Ubuntu22.04, tagged as `12.1.1-base-ubuntu22.04`. ++- Single strategy ++1. Create a file named `single-strategy-example.yaml` and copy in the following manifest. ++ ```yaml + apiVersion: v1 + kind: Pod + metadata: + name: nvidia-single + spec: + containers: + - name: nvidia-single + image: nvidia/cuda:12.1.1-base-ubuntu22.04 + command: ["/bin/sh"] + args: ["-c","sleep 1000"] + resources: + limits: + "nvidia.com/gpu": 1 + ``` ++2. Deploy the application using the `kubectl apply` command and specify the name of your YAML manifest. ++ ``` + kubectl apply -f single-strategy-example.yaml + ``` + +3. Verify the allocated GPU devices using the `kubectl exec` command. This command returns a list of the cluster nodes. ++ ``` + kubectl exec nvidia-single -- nvidia-smi -L + ``` ++ The following example resembles output showing successfully created deployments and services. ++ ```output + GPU 0: NVIDIA A100 40GB PCIe (UUID: GPU-48aeb943-9458-4282-da24-e5f49e0db44b) + MIG 1g.5gb Device 0: (UUID: MIG-fb42055e-9e53-5764-9278-438605a3014c) + MIG 1g.5gb Device 1: (UUID: MIG-3d4db13e-c42d-5555-98f4-8b50389791bc) + MIG 1g.5gb Device 2: (UUID: MIG-de819d17-9382-56a2-b9ca-aec36c88014f) + MIG 1g.5gb Device 3: (UUID: MIG-50ab4b32-92db-5567-bf6d-fac646fe29f2) + MIG 1g.5gb Device 4: (UUID: MIG-7b6b1b6e-5101-58a4-b5f5-21563789e62e) + MIG 1g.5gb Device 5: (UUID: MIG-14549027-dd49-5cc0-bca4-55e67011bd85) + MIG 1g.5gb Device 6: (UUID: MIG-37e055e8-8890-567f-a646-ebf9fde3ce7a) + ``` ++- Mixed mode strategy ++1. Create a file named `mixed-strategy-example.yaml` and copy in the following manifest. ++ ```yaml + apiVersion: v1 + kind: Pod + metadata: + name: nvidia-mixed + spec: + containers: + - name: nvidia-mixed + image: nvidia/cuda:12.1.1-base-ubuntu22.04 + command: ["/bin/sh"] + args: ["-c","sleep 100"] + resources: + limits: + "nvidia.com/mig-1g.5gb": 1 + ``` ++2. Deploy the application using the `kubectl apply` command and specify the name of your YAML manifest. ++ ``` + kubectl apply -f mixed-strategy-example.yaml + ``` + +3. Verify the allocated GPU devices using the `kubectl exec` command. This command returns a list of the cluster nodes. ++ ``` + kubectl exec nvidia-mixed -- nvidia-smi -L + ``` ++ The following example resembles output showing successfully created deployments and services. ++ ```output + GPU 0: NVIDIA A100 40GB PCIe (UUID: GPU-48aeb943-9458-4282-da24-e5f49e0db44b) + MIG 1g.5gb Device 0: (UUID: MIG-fb42055e-9e53-5764-9278-438605a3014c) + ``` +> [!IMPORTANT] +> The "latest" tag for CUDA images has been deprecated on Docker Hub. +> Please refer to [NVIDIA's repository](https://hub.docker.com/r/nvidia/cuda/tags) for the latest images and corresponding tags ## Troubleshooting - If you do not see multi-instance GPU capability after the node pool has been created, confirm the API version is not older than 2021-08-01. |
aks | Howto Deploy Java Liberty App | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/aks/howto-deploy-java-liberty-app.md | Title: Deploy a Java application with Open Liberty/WebSphere Liberty on an Azure Kubernetes Service (AKS) cluster recommendations: false description: Deploy a Java application with Open Liberty/WebSphere Liberty on an Azure Kubernetes Service (AKS) cluster-- Last updated 12/21/2022 keywords: java, jakartaee, javaee, microprofile, open-liberty, websphere-liberty, aks, kubernetes-+ # Deploy a Java application with Open Liberty or WebSphere Liberty on an Azure Kubernetes Service (AKS) cluster This article uses the Azure Marketplace offer for Open/WebSphere Liberty to acce * This article requires at least version 2.31.0 of Azure CLI. If using Azure Cloud Shell, the latest version is already installed. * If running the commands in this guide locally (instead of Azure Cloud Shell):- * Prepare a local machine with Unix-like operating system installed (for example, Ubuntu, Mariner, macOS, Windows Subsystem for Linux). + * Prepare a local machine with Unix-like operating system installed (for example, Ubuntu, Azure Linux, macOS, Windows Subsystem for Linux). * Install a Java SE implementation (for example, [Eclipse Open J9](https://www.eclipse.org/openj9/)). * Install [Maven](https://maven.apache.org/download.cgi) 3.5.0 or higher. * Install [Docker](https://docs.docker.com/get-docker/) for your OS. |
aks | Intro Kubernetes | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/aks/intro-kubernetes.md | Title: Introduction to Azure Kubernetes Service description: Learn the features and benefits of Azure Kubernetes Service to deploy and manage container-based applications in Azure. + Last updated 05/02/2023 When you deploy an AKS cluster, you specify the number and size of the nodes, an For more information on Kubernetes basics, see [Kubernetes core concepts for AKS][concepts-clusters-workloads]. [!INCLUDE [azure-lighthouse-supported-service](../../includes/azure-lighthouse-supported-service.md)]++> [!NOTE] > AKS also supports Windows Server containers. ## Access, security, and monitoring AKS supports the creation of Intel SGX-based, confidential computing node pools For more information, see [Confidential computing nodes on AKS][conf-com-node]. -### Mariner nodes +### Azure Linux nodes -Mariner is an open-source Linux distribution created by Microsoft, and itΓÇÖs now available for preview as a container host on Azure Kubernetes Service (AKS). The Mariner container host provides reliability and consistency from cloud to edge across the AKS, AKS-HCI, and Arc products. You can deploy Mariner node pools in a new cluster, add Mariner node pools to your existing Ubuntu clusters, or migrate your Ubuntu nodes to Mariner nodes. +The Azure Linux container host for AKS is an open-source Linux distribution created by Microsoft, and itΓÇÖs available as a container host on Azure Kubernetes Service (AKS). The Azure Linux container host for AKS provides reliability and consistency from cloud to edge across the AKS, AKS-HCI, and Arc products. You can deploy Azure Linux node pools in a new cluster, add Azure Linux node pools to your existing Ubuntu clusters, or migrate your Ubuntu nodes to Azure Linux nodes. -For more information, see [Use the Mariner container host on AKS](use-mariner.md) +For more information, see [Use the Azure Linux container host for AKS](use-azure-linux.md). ### Storage volume support Learn more about deploying and managing AKS. [collect-resource-logs]: monitor-aks.md#collect-resource-logs [azure-monitor-logs]: ../azure-monitor/logs/data-platform-logs.md [helm]: quickstart-helm.md-[aks-best-practices]: best-practices.md +[aks-best-practices]: best-practices.md |
aks | Kubelet Logs | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/aks/kubelet-logs.md | This article shows you how you can use `journalctl` to view *kubelet* logs on an This article assumes you have an existing AKS cluster. If you need an AKS cluster, create one using [Azure CLI][aks-quickstart-cli], [Azure PowerShell][aks-quickstart-powershell], or [Azure portal][aks-quickstart-portal]. +## Using kubectl raw ++You can quickly view any node kubelet logs by using the following command: +```bash +kubectl get --raw "/api/v1/nodes/nodename/proxy/logs/messages"|grep kubelet +``` ++ ## Create an SSH connection First, you need to create an SSH connection with the node you need to view *kubelet* logs for. To create this connection, follow the steps in [SSH into AKS cluster nodes][aks-ssh]. |
aks | Node Updates Kured | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/aks/node-updates-kured.md | Title: Handle Linux node reboots with kured description: Learn how to update Linux nodes and automatically reboot them with kured in Azure Kubernetes Service (AKS) + Last updated 04/19/2023---#Customer intent: As a cluster administrator, I want to know how to automatically apply Linux updates and reboot nodes in AKS for security and/or compliance +#Customer intent: As a cluster administrator, I want to know how to automatically apply Linux updates and reboot nodes in AKS for security and/or compliance # Apply security and kernel updates to Linux nodes in Azure Kubernetes Service (AKS) You need the Azure CLI version 2.0.59 or later installed and configured. Run `az ## Understand the AKS node update experience -In an AKS cluster, your Kubernetes nodes run as Azure virtual machines (VMs). These Linux-based VMs use an Ubuntu or Mariner image, with the OS configured to automatically check for updates every day. If security or kernel updates are available, they're automatically downloaded and installed. +In an AKS cluster, your Kubernetes nodes run as Azure virtual machines (VMs). These Linux-based VMs use an Ubuntu or Azure Linux image, with the OS configured to automatically check for updates every day. If security or kernel updates are available, they're automatically downloaded and installed.  |
aks | Private Clusters | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/aks/private-clusters.md | Private cluster is available in public regions, Azure Government, and Azure Chin ## Limitations * IP authorized ranges can't be applied to the private API server endpoint, they only apply to the public API server-* [Azure Private Link service limitations].[private-link-service] apply to private clusters. +* [Azure Private Link service limitations][private-link-service] apply to private clusters. * There's no support for Azure DevOps Microsoft-hosted Agents with private clusters. Consider using [Self-hosted Agents](/azure/devops/pipelines/agents/agents). * If you need to enable Azure Container Registry to work with a private AKS cluster, [set up a private link for the container registry in the cluster virtual network][container-registry-private-link] or set up peering between the Container Registry virtual network and the private cluster's virtual network. * There's no support for converting existing AKS clusters into private clusters. |
aks | Release Tracker | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/aks/release-tracker.md | Title: AKS release tracker description: Learn how to determine which Azure regions have the weekly AKS release deployments rolled out in real time. Previously updated : 05/24/2022 Last updated : 04/25/2023 --+ # AKS release tracker With AKS release tracker, customers can follow specific component updates presen To view the release tracker, visit the [AKS release status webpage][release-tracker-webpage]. +AKS node image and add-on releases are decoupled from the primary AKS service release. You can select the specific area tab to track the release status. + The top half of the tracker shows the latest and 3 previously available release versions for each region, and links to the corresponding release notes entry. This view is helpful when you want to track the available versions by region. :::image type="content" source="./media/release-tracker/regional-status.png" alt-text="Screenshot of the A K S release tracker's regional status table displayed in a web browser."::: The bottom half of the tracker shows the SDP process. The table has two views: o :::image type="content" source="./media/release-tracker/sdp-process.png" alt-text="Screenshot of the A K S release tracker's S D P process table displayed in a web browser."::: +On the **AKS addon release page**, you can select a specific add-on name to track its release notes and SDP process. + <!-- LINKS - external --> [aks-release]: https://github.com/Azure/AKS/releases-[release-tracker-webpage]: https://releases.aks.azure.com/webpage/https://docsupdatetracker.net/index.html +[release-tracker-webpage]: https://releases.aks.azure.com/webpage/https://docsupdatetracker.net/index.html |
aks | Use Azure Linux | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/aks/use-azure-linux.md | ++ + Title: Use the Azure Linux container host on Azure Kubernetes Service (AKS) +description: Learn how to use the Azure Linux container host on Azure Kubernetes Service (AKS) ++ Last updated : 04/19/2023+++# Use the Azure Linux container host for Azure Kubernetes Service (AKS) ++The Azure Linux container host for AKS is an open-source Linux distribution created by Microsoft, and itΓÇÖs available as a container host on Azure Kubernetes Service (AKS). The Azure Linux container host provides reliability and consistency from cloud to edge across the AKS, AKS-HCI, and Arc products. You can deploy Azure Linux node pools in a new cluster, add Azure Linux node pools to your existing Ubuntu clusters, or migrate your Ubuntu nodes to Azure Linux nodes. To learn more about Azure Linux, see the [Azure Linux documentation][azurelinux-doc]. ++## Why use Azure Linux ++The Azure Linux container host on AKS uses a native AKS image that provides one place to do all Linux development. Every package is built from source and validated, ensuring your services run on proven components. Azure Linux is lightweight, only including the necessary set of packages needed to run container workloads. It provides a reduced attack surface and eliminates patching and maintenance of unnecessary packages. At the base layer, it has a Microsoft hardened kernel tuned for Azure. Learn more about the [key capabilities of Azure Linux][azurelinux-capabilities]. ++## How to use Azure Linux on AKS ++To get started using the Azure Linux container host for AKS, see: ++* [Creating a cluster with Azure Linux][azurelinux-cluster-config] +* [Add an Azure Linux node pool to your existing cluster][azurelinux-node-pool] +* [Ubuntu to Azure Linux migration][ubuntu-to-azurelinux] ++## How to upgrade Azure Linux nodes ++We recommend keeping your clusters up to date and secured by enabling automatic upgrades for your cluster. To enable automatic upgrades, see: ++* [Automatically upgrade an Azure Kubernetes Service (AKS) cluster][auto-upgrade-aks] +* [Deploy kured in an AKS cluster][kured] ++To manually upgrade the node-image on a cluster, you can run `az aks nodepool upgrade`: ++```azurecli +az aks nodepool upgrade \ + --resource-group myResourceGroup \ + --cluster-name myAKSCluster \ + --name myNodePool \ + --node-image-only +``` ++## Regional availability ++The Azure Linux container host is available for use in the same regions as AKS. ++## Limitations ++The Azure Linux container host has the following limitations: ++* Image SKUs for SGX and FIPS aren't available. +* It doesn't meet the [Federal Information Processing Standard (FIPS) 140](https://csrc.nist.gov/publications/detail/fips/140/3/final) compliance requirements and [Center for Internet Security (CIS)](https://www.cisecurity.org/) certification. +* Azure Linux can't yet be deployed through the Azure portal. +* Qualys, Trivy, and Microsoft Defender for Containers are the only vulnerability scanning tools that support Azure Linux today. +* Azure Linux doesn't support AppArmor. Support for SELinux can be manually configured. +* Some addons, extensions, and open-source integrations may not be supported yet on Azure Linux. Azure Monitor, Grafana, Helm, Key Vault, and Container Insights are supported. ++<!-- LINKS - Internal --> +[azurelinux-doc]: https://microsoft.github.io/CBL-Mariner/docs/#cbl-mariner-linux +[azurelinux-capabilities]: https://microsoft.github.io/CBL-Mariner/docs/#key-capabilities-of-cbl-mariner-linux +[azurelinux-cluster-config]: cluster-configuration.md#azure-linux-container-host-for-aks +[azurelinux-node-pool]: use-multiple-node-pools.md#add-an-azure-linux-node-pool +[ubuntu-to-azurelinux]: use-multiple-node-pools.md#migrate-ubuntu-nodes-to-azure-linux +[auto-upgrade-aks]: auto-upgrade-cluster.md +[kured]: node-updates-kured.md |
aks | Use Mariner | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/aks/use-mariner.md | -- Title: Use the Mariner container host on Azure Kubernetes Service (AKS) -description: Learn how to use the Mariner container host on Azure Kubernetes Service (AKS) -- Previously updated : 04/19/2023---# Use the Mariner container host on Azure Kubernetes Service (AKS) --Mariner is an open-source Linux distribution created by Microsoft, and itΓÇÖs now available for preview as a container host on Azure Kubernetes Service (AKS). The Mariner container host provides reliability and consistency from cloud to edge across the AKS, AKS-HCI, and Arc products. You can deploy Mariner node pools in a new cluster, add Mariner node pools to your existing Ubuntu clusters, or migrate your Ubuntu nodes to Mariner nodes. To learn more about Mariner, see the [Mariner documentation][mariner-doc]. --## Why use Mariner --The Mariner container host on AKS uses a native AKS image that provides one place to do all Linux development. Every package is built from source and validated, ensuring your services run on proven components. Mariner is lightweight, only including the necessary set of packages needed to run container workloads. It provides a reduced attack surface and eliminates patching and maintenance of unnecessary packages. At Mariner's base layer, it has a Microsoft hardened kernel tuned for Azure. Learn more about the [key capabilities of Mariner][mariner-capabilities]. --## How to use Mariner on AKS --To get started using Mariner on AKS, see: --* [Creating a cluster with Mariner][mariner-cluster-config] -* [Add a Mariner node pool to your existing cluster][mariner-node-pool] -* [Ubuntu to Mariner migration][ubuntu-to-mariner] --## How to upgrade Mariner nodes --We recommend keeping your clusters up to date and secured by enabling automatic upgrades for your cluster. To enable automatic upgrades, see: --* [Automatically upgrade an Azure Kubernetes Service (AKS) cluster][auto-upgrade-aks] -* [Deploy kured in an AKS cluster][kured] --To manually upgrade the node-image on a cluster, you can run `az aks nodepool upgrade`: --```azurecli -az aks nodepool upgrade \ - --resource-group myResourceGroup \ - --cluster-name myAKSCluster \ - --name myNodePool \ - --node-image-only -``` --## Regional availability --Mariner is available for use in the same regions as AKS. --## Limitations --Mariner currently has the following limitations: --* Image SKUs for SGX and FIPS are not available. -* It doesn't meet the [Federal Information Processing Standard (FIPS) 140](https://csrc.nist.gov/publications/detail/fips/140/3/final) compliance requirements and [Center for Internet Security (CIS)](https://www.cisecurity.org/) certification. -* Mariner can't yet be deployed through the Azure portal. -* Qualys, Trivy, and Microsoft Defender for Containers are the only vulnerability scanning tools that support Mariner today. -* Mariner doesn't support AppArmor. Support for SELinux can be manually configured. -* Some addons, extensions, and open-source integrations may not be supported yet on Mariner. Azure Monitor, Grafana, Helm, Key Vault, and Container Insights are supported. --<!-- LINKS - Internal --> -[mariner-doc]: https://microsoft.github.io/CBL-Mariner/docs/#cbl-mariner-linux -[mariner-capabilities]: https://microsoft.github.io/CBL-Mariner/docs/#key-capabilities-of-cbl-mariner-linux -[mariner-cluster-config]: cluster-configuration.md -[mariner-node-pool]: use-multiple-node-pools.md#add-a-mariner-node-pool -[ubuntu-to-mariner]: use-multiple-node-pools.md#migrate-ubuntu-nodes-to-mariner -[auto-upgrade-aks]: auto-upgrade-cluster.md -[kured]: node-updates-kured.md |
aks | Use Multiple Node Pools | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/aks/use-multiple-node-pools.md | Title: Use multiple node pools in Azure Kubernetes Service (AKS) description: Learn how to create and manage multiple node pools for a cluster in Azure Kubernetes Service (AKS) -+ Last updated 03/11/2023 az aks nodepool add \ --node-vm-size Standard_D2pds_v5 ``` -### Add a Mariner node pool +### Add an Azure Linux node pool -Mariner is an open-source Linux distribution available as an AKS container host. It provides high reliability, security, and consistency. Mariner only includes the minimal set of packages needed for running container workloads, which improves boot times and overall performance. +The Azure Linux container host for AKS is an open-source Linux distribution available as an AKS container host. It provides high reliability, security, and consistency. It only includes the minimal set of packages needed for running container workloads, which improves boot times and overall performance. -You can add a Mariner node pool into your existing cluster using the `az aks nodepool add` command and specifying `--os-sku mariner`. +You can add an Azure Linux node pool into your existing cluster using the `az aks nodepool add` command and specifying `--os-sku AzureLinux`. ```azurecli-interactive az aks nodepool add \ --resource-group myResourceGroup \ --cluster-name myAKSCluster \- --name marinerpool \ - --os-sku mariner + --name azurelinuxpool \ + --os-sku AzureLinux ``` -### Migrate Ubuntu nodes to Mariner +### Migrate Ubuntu nodes to Azure Linux -Use the following instructions to migrate your Ubuntu nodes to Mariner nodes. +Use the following instructions to migrate your Ubuntu nodes to Azure Linux nodes. -1. Add a Mariner node pool into your existing cluster using the `az aks nodepool add` command and specifying `--os-sku mariner`. +1. Add a Azure Linux node pool into your existing cluster using the `az aks nodepool add` command and specifying `--os-sku AzureLinux`. > [!NOTE]-> When adding a new Mariner node pool, you need to add at least one as `--mode System`. Otherwise, AKS won't allow you to delete your existing Ubuntu node pool. +> When adding a new Azure Linux node pool, you need to add at least one as `--mode System`. Otherwise, AKS won't allow you to delete your existing Ubuntu node pool. 2. [Cordon the existing Ubuntu nodes][cordon-and-drain]. 3. [Drain the existing Ubuntu nodes][drain-nodes]. |
aks | Use Pod Sandboxing | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/aks/use-pod-sandboxing.md | Title: Pod Sandboxing (preview) with Azure Kubernetes Service (AKS) description: Learn about and deploy Pod Sandboxing (preview), also referred to as Kernel Isolation, on an Azure Kubernetes Service (AKS) cluster. -+ Last updated 03/07/2023 This article helps you understand this new feature, and how to implement it. - The Azure CLI version 2.44.1 or later. Run `az --version` to find the version, and run `az upgrade` to upgrade the version. If you need to install or upgrade, see [Install Azure CLI][install-azure-cli]. -- The `aks-preview` Azure CLI extension version 0.5.123 or later to select the [Mariner operating system][mariner-cluster-config] generation 2 SKU.+- The `aks-preview` Azure CLI extension version 0.5.123 or later. - Register the `KataVMIsolationPreview` feature in your Azure subscription. The following are constraints with this preview of Pod Sandboxing (preview): ## How it works -To achieve this functionality on AKS, [Kata Containers][kata-containers-overview] running on Mariner AKS Container Host (MACH) stack delivers hardware-enforced isolation. Pod Sandboxing extends the benefits of hardware isolation such as a separate kernel for each Kata pod. Hardware isolation allocates resources for each pod and doesn't share them with other Kata Containers or namespace containers running on the same host. +To achieve this functionality on AKS, [Kata Containers][kata-containers-overview] running on the Azure Linux container host for AKS stack delivers hardware-enforced isolation. Pod Sandboxing extends the benefits of hardware isolation such as a separate kernel for each Kata pod. Hardware isolation allocates resources for each pod and doesn't share them with other Kata Containers or namespace containers running on the same host. The solution architecture is based on the following components: -* [Mariner][mariner-overview] AKS Container Host +* The [Azure Linux container host for AKS][azurelinux-overview] * Microsoft Hyper-V Hypervisor * Azure-tuned Dom0 Linux Kernel * Open-source [Cloud-Hypervisor][cloud-hypervisor] Virtual Machine Monitor (VMM) When a pod uses the *kata-mshv-vm-isolation* runtimeClass, it creates a VM to se ## Deploy new cluster -Perform the following steps to deploy an AKS Mariner cluster using the Azure CLI. +Perform the following steps to deploy a Azure Linux AKS cluster using the Azure CLI. 1. Create an AKS cluster using the [az aks create][az-aks-create] command and specifying the following parameters: * **--workload-runtime**: Specify *KataMshvVmIsolation* to enable the Pod Sandboxing feature on the node pool. With this parameter, these other parameters shall satisfy the following requirements. Otherwise, the command fails and reports an issue with the corresponding parameter(s).- * **--os-sku**: *mariner*. Only the Mariner os-sku supports this feature in this preview release. + * **--os-sku**: *AzureLinux*. Only the Azure Linux os-sku supports this feature in this preview release. * **--node-vm-size**: Any Azure VM size that is a generation 2 VM and supports nested virtualization works. For example, [Dsv3][dv3-series] VMs. The following example creates a cluster named *myAKSCluster* with one node in the *myResourceGroup*: ```azurecli-interactive- az aks create --name myAKSCluster --resource-group myResourceGroup --os-sku mariner --workload-runtime KataMshvVmIsolation --node-vm-size Standard_D4s_v3 --node-count 1 + az aks create --name myAKSCluster --resource-group myResourceGroup --os-sku AzureLinux --workload-runtime KataMshvVmIsolation --node-vm-size Standard_D4s_v3 --node-count 1 2. Run the following command to get access credentials for the Kubernetes cluster. Use the [az aks get-credentials][aks-get-credentials] command and replace the values for the cluster name and the resource group name. Use the following command to enable Pod Sandboxing (preview) by creating a node * **--cluster-name**: Enter a unique name for the AKS cluster, such as *myAKSCluster*. * **--name**: Enter a unique name for your clusters node pool, such as *nodepool2*. * **--workload-runtime**: Specify *KataMshvVmIsolation* to enable the Pod Sandboxing feature on the node pool. Along with the `--workload-runtime` parameter, these other parameters shall satisfy the following requirements. Otherwise, the command fails and reports an issue with the corresponding parameter(s).- * **--os-sku**: *mariner*. Only the Mariner os-sku supports this feature in the preview release. + * **--os-sku**: *AzureLinux*. Only the Azure Linux os-sku supports this feature in the preview release. * **--node-vm-size**: Any Azure VM size that is a generation 2 VM and supports nested virtualization works. For example, [Dsv3][dv3-series] VMs. The following example adds a node pool to *myAKSCluster* with one node in *nodepool2* in the *myResourceGroup*: ```azurecli-interactive- az aks nodepool add --cluster-name myAKSCluster --resource-group myResourceGroup --name nodepool2 --os-sku mariner --workload-runtime KataMshvVmIsolation --node-vm-size Standard_D4s_v3 + az aks nodepool add --cluster-name myAKSCluster --resource-group myResourceGroup --name nodepool2 --os-sku AzureLinux --workload-runtime KataMshvVmIsolation --node-vm-size Standard_D4s_v3 ``` 2. Run the [az aks update][az-aks-update] command to enable pod sandboxing (preview) on the cluster. kubectl delete pod pod-name <!-- EXTERNAL LINKS --> [kata-containers-overview]: https://katacontainers.io/ [kubectl]: https://kubernetes.io/docs/reference/kubectl/-[azurerm-mariner]: https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/kubernetes_cluster_node_pool#os_sku +[azurerm-azurelinux]: https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/kubernetes_cluster_node_pool#os_sku [kubectl-get-pods]: https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#get [kubectl-exec]: https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#exec [container-resource-manifest]: https://kubernetes.io/docs/tasks/configure-pod-container/assign-cpu-resource/ kubectl delete pod pod-name [container-insights]: ../azure-monitor/containers/container-insights-overview.md [defender-for-containers]: ../defender-for-cloud/defender-for-containers-introduction.md [az-aks-install-cmd]: /cli/azure/aks#az-aks-install-cli-[mariner-overview]: use-mariner.md +[azurelinux-overview]: use-azure-linux.md [csi-storage-driver]: csi-storage-drivers.md [csi-secret-store driver]: csi-secrets-store-driver.md [az-aks-update]: /cli/azure/aks#az-aks-update-[mariner-cluster-config]: cluster-configuration.md#mariner-os +[azurelinux-cluster-config]: cluster-configuration.md#azure-linux-container-host-for-aks [register-the-katavmisolationpreview-feature-flag]: #register-the-katavmisolationpreview-feature-flag |
aks | Windows Faq | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/aks/windows-faq.md | Title: Windows Server node pools FAQ description: See the frequently asked questions when you run Windows Server node pools and application workloads in Azure Kubernetes Service (AKS). + Last updated 04/13/2023- #Customer intent: As a cluster operator, I want to see frequently asked questions when running Windows node pools and application workloads. Historically, Kubernetes is Linux-focused. Many examples used in the upstream [K Azure Disks and Azure Files are the supported volume types, and are accessed as NTFS volumes in the Windows Server container. +## Do Linux and Windows support generation 2 virtual machines (VMs)? ++Generation 2 VMs are supported on Linux and Windows for WS2022 only. For more information, see [Support for generation 2 VMs on Azure](../virtual-machines/generation-2.md). + ## Can I run Windows only clusters in AKS? The master nodes (the control plane) in an AKS cluster are hosted by the AKS service. You won't be exposed to the operating system of the nodes hosting the master components. All AKS clusters are created with a default first node pool, which is Linux-based. This node pool contains system services that are needed for the cluster to function. We recommend that you run at least two nodes in the first node pool to ensure the reliability of your cluster and the ability to do cluster operations. The first Linux-based node pool can't be deleted unless the AKS cluster itself is deleted. $cluster | Set-AzAksCluster > [!IMPORTANT] > Performing the `Set-AzAksCluster` operation upgrades only Windows Server node pools. Linux node pools are not affected.-> +> > When you're changing the Windows administrator password, the new password must be at least 14 characters and meet [Windows Server password requirements][windows-server-password]. |
aks | Workload Identity Overview | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/aks/workload-identity-overview.md | Title: Use an Azure AD workload identities on Azure Kubernetes Service (AKS) description: Learn about Azure Active Directory workload identity for Azure Kubernetes Service (AKS) and how to migrate your application to authenticate using this identity. + Last updated 05/01/2023- # Use Azure AD workload identity with Azure Kubernetes Service (AKS) The following table provides the **minimum** package version required for each l | Language | Library | Minimum Version | Example | ||-|--||-| .NET | [Azure.Identity](https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme) | 1.9.0 | [Link](https://github.com/Azure/azure-workload-identity/tree/main/examples/azure-identity/dotnet) | +| .NET | [Azure.Identity](/dotnet/api/overview/azure/identity-readme) | 1.9.0 | [Link](https://github.com/Azure/azure-workload-identity/tree/main/examples/azure-identity/dotnet) | | Go | [azidentity](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity) | 1.3.0 | [Link](https://github.com/Azure/azure-workload-identity/tree/main/examples/azure-identity/go) |-| Java | [azure-identity](https://learn.microsoft.com/java/api/overview/azure/identity-readme) | 1.9.0 | [Link](https://github.com/Azure/azure-workload-identity/tree/main/examples/azure-identity/java) | -| JavaScript | [@azure/identity](https://learn.microsoft.com/javascript/api/overview/azure/identity-readme) | 3.2.0 | [Link](https://github.com/Azure/azure-workload-identity/tree/main/examples/azure-identity/node) | -| Python | [azure-identity](https://learn.microsoft.com/python/api/overview/azure/identity-readme) | 1.13.0 | [Link](https://github.com/Azure/azure-workload-identity/tree/main/examples/azure-identity/python) | +| Java | [azure-identity](/java/api/overview/azure/identity-readme) | 1.9.0 | [Link](https://github.com/Azure/azure-workload-identity/tree/main/examples/azure-identity/java) | +| JavaScript | [@azure/identity](/javascript/api/overview/azure/identity-readme) | 3.2.0 | [Link](https://github.com/Azure/azure-workload-identity/tree/main/examples/azure-identity/node) | +| Python | [azure-identity](/python/api/overview/azure/identity-readme) | 1.13.0 | [Link](https://github.com/Azure/azure-workload-identity/tree/main/examples/azure-identity/python) | ## Microsoft Authentication Library (MSAL) |
api-management | Migrate Stv1 To Stv2 | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/api-management/migrate-stv1-to-stv2.md | For more information about the `stv1` and `stv2` platforms and the benefits of u > [!IMPORTANT] > * Migration is a long-running operation. Your instance will experience downtime during the last 10-15 minutes of migration. Plan your migration accordingly.-> * The VIP address(es) of your API Management will change. +> * The VIP address(es) of your API Management will change if you're using scenario 2 mentioned below (service injected in a VNET). For scenario 1 (not injected in a VNET), the VIP will temporarily change during migration for up to 15 minutes, but the original VIP of the service will be restored at the end of the migration operation. > * Migration to `stv2` is not reversible. > [!IMPORTANT] |
app-service | App Service Web Tutorial Custom Domain | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/app-service/app-service-web-tutorial-custom-domain.md | The DNS record type you need to add with your domain provider depends on the dom ## Prerequisites * [Create an App Service app](./index.yml), or use an app that you created for another tutorial. The web app's [App Service plan](overview-hosting-plans.md) must be a paid tier and not **Free (F1)**. See [Scale up an app](manage-scale-up.md#scale-up-your-pricing-tier) to update the tier.-* Make sure you can edit the DNS records for your custom domain. To edit DNS records, you need access to the DNS registry for your domain provider, such as GoDaddy. For example, to add DNS entries for `contoso.com` and `www.contoso.com`, you must be able to configure the DNS settings for the `contoso.com` root domain. Your custom domains must be in a public DNS zone; private DNS zone is only supported on Internal Load Balancer (ILB) App Service Environment (ASE). +* Make sure you can edit the DNS records for your custom domain. To edit DNS records, you need access to the DNS registry for your domain provider, such as GoDaddy. For example, to add DNS entries for `contoso.com` and `www.contoso.com`, you must be able to configure the DNS settings for the `contoso.com` root domain. Your custom domains must be in a public DNS zone; private DNS zones are not supported. * If you don't have a custom domain yet, you can [purchase an App Service domain](manage-custom-dns-buy-domain.md) instead. ## 1. Configure a custom domain |
app-service | Configure Authentication Provider Openid Connect | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/app-service/configure-authentication-provider-openid-connect.md | You can configure your app to use one or more OIDC providers. Each must be given ## <a name="register"> </a>Register your application with the identity provider -Your provider will require you to register the details of your application with it. One of these steps involves specifying a redirect URI. This redirect URI will be of the form `<app-url>/.auth/login/<provider-name>/callback`. Each identity provider should provide more instructions on how to complete these steps. +Your provider will require you to register the details of your application with it. One of these steps involves specifying a redirect URI. This redirect URI will be of the form `<app-url>/.auth/login/<provider-name>/callback`. Each identity provider should provide more instructions on how to complete these steps. `<provider-name>` will refer to the friendly name you give to the OpenID provider name in Azure. > [!NOTE] > Some providers may require additional steps for their configuration and how to use the values they provide. For example, Apple provides a private key which is not itself used as the OIDC client secret, and you instead must use it craft a JWT which is treated as the secret you provide in your app config (see the "Creating the Client Secret" section of the [Sign in with Apple documentation](https://developer.apple.com/documentation/sign_in_with_apple/generate_and_validate_tokens)) If you are unable to use a configuration metadata document, you will need to gat 1. Specify an application setting name for your client secret. Your client secret will be stored as an app setting to ensure secrets are stored in a secure fashion. You can update that setting later to use [Key Vault references](./app-service-key-vault-references.md) if you wish to manage the secret in Azure Key Vault. 1. Press the **Add** button to finish setting up the identity provider. +> [!NOTE] +> The OpenID provider name can't contain symbols like "-" because an appsetting will be created based on this and it doesn't support it. Use "_" instead. ++> [!NOTE] +> Azure requires "openid," "profile," and "email" scopes. Make sure you've configured your App Registration in your ID Provider with at least these scopes. + ## <a name="related-content"> </a>Next steps [!INCLUDE [app-service-mobile-related-content-get-started-users](../../includes/app-service-mobile-related-content-get-started-users.md)] |
app-service | Configure Authentication User Identities | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/app-service/configure-authentication-user-identities.md | public static class ClaimsPrincipalParser * other .NET code. */ - var identity = new ClaimsIdentity(principal.IdentityProvider); + var identity = new ClaimsIdentity(principal.IdentityProvider, principal.NameClaimType, principal.RoleClaimType); identity.AddClaims(principal.Claims.Select(c => new Claim(c.Type, c.Value))); return new ClaimsPrincipal(identity); For [Azure Functions](../azure-functions/functions-overview.md), `ClaimsPrincipa For .NET Core, [Microsoft.Identity.Web](https://www.nuget.org/packages/Microsoft.Identity.Web/) supports populating the current user with App Service authentication. To learn more, you can read about it on the [Microsoft.Identity.Web wiki](https://github.com/AzureAD/microsoft-identity-web/wiki/1.2.0#integration-with-azure-app-services-authentication-of-web-apps-running-with-microsoftidentityweb), or see it demonstrated in [this tutorial for a web app accessing Microsoft Graph](./scenario-secure-app-access-microsoft-graph-as-user.md?tabs=command-line#install-client-library-packages). +> [!NOTE] +> For claims mapping to work, you must enable the [Token store](overview-authentication-authorization.md#token-store). + ## Access user claims using the API If the [token store](overview-authentication-authorization.md#token-store) is enabled for your app, you can also obtain additional details on the authenticated user by calling `/.auth/me`. |
app-service | Configure Language Php | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/app-service/configure-language-php.md | As an alternative to using a `.user.ini` file, you can use [ini_set()](https://w ::: zone pivot="platform-linux" -To customize PHP_INI_USER, PHP_INI_PERDIR, and PHP_INI_ALL directives (see [php.ini directives](https://www.php.net/manual/ini.list.php)), add an *.htaccess* file to the root directory of your app. +To customize PHP_INI_USER, PHP_INI_PERDIR, and PHP_INI_ALL directives for linux web apps, such as upload_max_filesize and expose_php, use a custom "ini" file. You can create it in an [SSH session](configure-linux-open-ssh-session.md). -In the *.htaccess* file, add the directives using the `php_value <directive-name> <value>` syntax. For example: +1. Go to your KUDU site https://\<sitename\>.scm.azurewebsites.net. +2. Select Bash or SSH from the top menu. +3. In Bash/SSH, go to your "/home/site/wwwroot" directory. +4. Create a directory called "ini" (for example, mkdir ini). +5. Change the current working directory to the "ini" folder you just created. ++You need to create an "ini" file to add your settings to. In this example, we use "extensions.ini." There are no file editors such as Vi, Vim, or Nano so you'll use echo to add the settings to the file. Change the "upload_max_filesize" from 2M to 50M. Use the following command to add the setting and create an "extensions.ini" file if one doesn't already exist. ```-php_value upload_max_filesize 1000M -php_value post_max_size 2000M -php_value memory_limit 3000M -php_value max_execution_time 180 -php_value max_input_time 180 -php_value display_errors On -php_value upload_max_filesize 10M +/home/site/wwwroot/ini>echo "upload_max_filesize=50M" >> extensions.ini +/home/site/wwwroot/ini>cat extensions.ini ++upload_max_filesize=50M ++/home/site/wwwroot/ini> ``` -Redeploy your app with the changes and restart it. If you deploy it with Kudu (for example, using [Git](deploy-local-git.md)), it's automatically restarted after deployment. +Then, go to the Azure portal and add an Application Setting to scan the "ini" directory that you just created to apply the change for upload_max_filesize. + +1. Go to the [Azure portal](https://portal.azure.com) and select your App Service Linux PHP application. +2. Select Application Settings for the app. +3. Under the Application settings section, select **+ Add new setting**. +4. For the App Setting Name, enter "PHP_INI_SCAN_DIR" and for value, enter "/home/site/wwwroot/ini." +5. Select the save button. -As an alternative to using *.htaccess*, you can use [ini_set()](https://www.php.net/manual/function.ini-set.php) in your app to customize these non-PHP_INI_SYSTEM directives. +> [!NOTE] +> If you recompiled a PHP extension, such as GD, follow the steps at [Recompiling PHP Extensions at Azure App Service - Adding PHP Extensions](https://blogs.msdn.microsoft.com/azureossds/2019/01/29/azure-app-service-linux-adding-php-extensions/) ::: zone-end |
app-service | Deploy Azure Pipelines | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/app-service/deploy-azure-pipelines.md | The following example shows how to deploy to a staging slot, and then swap to a deployToSlotOrASE: true resourceGroupName: '<name of resource group>' slotName: staging+ package: '$(Build.ArtifactStagingDirectory)/**/*.zip' - task: AzureAppServiceManage@0 inputs: The following example shows how to deploy to a staging slot, and then swap to a * **appName**: the name of your existing app service. * **deployToSlotOrASE**: Boolean. Deploy to an existing deployment slot or Azure App Service Environment. * **resourceGroupName**: Name of the resource group. Required if `deployToSlotOrASE` is true. -* **slotName**: Name of the slot, defaults to `production`. Required if `deployToSlotOrASE` is true. +* **slotName**: Name of the slot, defaults to `production`. Required if `deployToSlotOrASE` is true. +* **package**: the file path to the package or a folder containing your app service contents. Wildcards are supported. * **SourceSlot**: Slot sent to production when `SwapWithProduction` is true. * **SwapWithProduction**: Boolean. Swap the traffic of source slot with production. You're now ready to create a release, which means to run the release pipeline wi ## Next steps -- Customize your [Azure DevOps pipeline](/azure/devops/pipelines/customize-pipeline).+- Customize your [Azure DevOps pipeline](/azure/devops/pipelines/customize-pipeline). |
app-service | Deploy Github Actions | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/app-service/deploy-github-actions.md | jobs: dotnet publish -c Release --property:PublishDir='${{ env.AZURE_WEBAPP_PACKAGE_PATH }}/myapp' # Deploy to Azure Web apps- - name: 'Run Azure webapp deploy action using publish profile credentials' + - name: 'Run Azure webapp deploy action using Azure Credentials' uses: azure/webapps-deploy@v2 with: app-name: ${{ env.AZURE_WEBAPP_NAME }} # Replace with your app name jobs: - name: Run MSBuild run: msbuild .\SampleWebApplication.sln - - name: 'Run Azure webapp deploy action using publish profile credentials' + - name: 'Run Azure webapp deploy action using Azure Credentials' uses: azure/webapps-deploy@v2 with: app-name: ${{ env.AZURE_WEBAPP_NAME }} # Replace with your app name |
app-service | Deploy Zip | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/app-service/deploy-zip.md | curl -X POST -u <username> -T @"<startup-file-path>" https://<app-name>.scm.azur The following example uses the cURL tool to deploy a library file for their application. Replace the placeholders `<username>`, `<lib-file-path>`, and `<app-name>`. When prompted by cURL, type in the [deployment password](deploy-configure-credentials.md). ```bash-curl -X POST -u <username> -T @"<lib-file-path>" https://<app-name>.scm.azurewebsites.net/api/publish?type=lib&path="/home/site/deployments/tools/my-lib.jar" +curl -X POST -u <username> -T @"<lib-file-path>" "https://<app-name>.scm.azurewebsites.net/api/publish?type=lib&path=/home/site/deployments/tools/my-lib.jar" ``` ### Deploy a static file curl -X POST -u <username> -T @"<lib-file-path>" https://<app-name>.scm.azureweb The following example uses the cURL tool to deploy a config file for their application. Replace the placeholders `<username>`, `<config-file-path>`, and `<app-name>`. When prompted by cURL, type in the [deployment password](deploy-configure-credentials.md). ```bash-curl -X POST -u <username> -T @"<config-file-path>" https://<app-name>.scm.azurewebsites.net/api/publish?type=static&path="/home/site/deployments/tools/my-config.json" +curl -X POST -u <username> -T @"<config-file-path>" "https://<app-name>.scm.azurewebsites.net/api/publish?type=static&path=/home/site/deployments/tools/my-config.json" ``` # [Kudu UI](#tab/kudu-ui) |
app-service | Manage Create Arc Environment | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/app-service/manage-create-arc-environment.md | If you don't have an Azure account, [sign up today](https://azure.microsoft.com/ Set the following environment variables based on your Kubernetes cluster deployment: ```bash-aksClusterGroupName="<name-resource-group-with-aks-cluster>" -groupName="<name-of-resource-group-with-the-arc-connected-cluster>" -clusterName="<name-of-arc-connected-cluster>" -geomasterLocation="TODO: Why so many different locations for different resources? Shouldn't we just say create everything in the connected cluster's resource group and location?" +AKS_CLUSTER_GROUP_NAME="<name-resource-group-with-aks-cluster>" +GROUP_NAME="<name-of-resource-group-with-the-arc-connected-cluster>" +CLUSTER_NAME="<name-of-arc-connected-cluster>" +GEOMASTER_LOCATION="TODO: Why so many different locations for different resources? Shouldn't we just say create everything in the connected cluster's resource group and location?" ``` --> ## Add Azure CLI extensions az extension add --upgrade --yes --name appservice-kube # [bash](#tab/bash) ```azurecli-interactive- aksClusterGroupName="<group-name>" # Name of resource group for the AKS cluster - aksName="${aksClusterGroupName}-aks" # Name of the AKS cluster - resourceLocation="eastus" # "eastus" or "westeurope" + AKS_CLUSTER_GROUP_NAME="<group-name>" # Name of resource group for the AKS cluster + AKS_NAME="${aksClusterGroupName}-aks" # Name of the AKS cluster + RESOURCE_LOCATION="eastus" # "eastus" or "westeurope" - az group create -g $aksClusterGroupName -l $resourceLocation - az aks create --resource-group $aksClusterGroupName --name $aksName --enable-aad --generate-ssh-keys + az group create -g $AKS_CLUSTER_GROUP_NAME -l $RESOURCE_LOCATION + az aks create --resource-group $AKS_CLUSTER_GROUP_NAME --name $AKS_NAME --enable-aad --generate-ssh-keys ``` # [PowerShell](#tab/powershell) az extension add --upgrade --yes --name appservice-kube 2. Get the [kubeconfig](https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/) file and test your connection to the cluster. By default, the kubeconfig file is saved to `~/.kube/config`. ```azurecli-interactive- az aks get-credentials --resource-group $aksClusterGroupName --name $aksName --admin + az aks get-credentials --resource-group $AKS_CLUSTER_GROUP_NAME --name $AKS_NAME --admin kubectl get ns ``` az extension add --upgrade --yes --name appservice-kube # [bash](#tab/bash) ```azurecli-interactive- groupName="<group-name>" # Name of resource group for the connected cluster + GROUP_NAME="<group-name>" # Name of resource group for the connected cluster - az group create -g $groupName -l $resourceLocation + az group create -g $GROUP_NAME -l $RESOURCE_LOCATION ``` # [PowerShell](#tab/powershell) az extension add --upgrade --yes --name appservice-kube # [bash](#tab/bash) ```azurecli-interactive- clusterName="${groupName}-cluster" # Name of the connected cluster resource + CLUSTER_NAME="${GROUP_NAME}-cluster" # Name of the connected cluster resource - az connectedk8s connect --resource-group $groupName --name $clusterName + az connectedk8s connect --resource-group $GROUP_NAME --name $CLUSTER_NAME ``` # [PowerShell](#tab/powershell) az extension add --upgrade --yes --name appservice-kube 5. Validate the connection with the following command. It should show the `provisioningState` property as `Succeeded`. If not, run the command again after a minute. ```azurecli-interactive- az connectedk8s show --resource-group $groupName --name $clusterName + az connectedk8s show --resource-group $GROUP_NAME --name $CLUSTER_NAME ``` ## Create a Log Analytics workspace While a [Log Analytic workspace](../azure-monitor/logs/quick-create-workspace.md # [bash](#tab/bash) ```azurecli-interactive- workspaceName="$groupName-workspace" # Name of the Log Analytics workspace + WORKSPACE_NAME="$GROUP_NAME-workspace" # Name of the Log Analytics workspace az monitor log-analytics workspace create \- --resource-group $groupName \ - --workspace-name $workspaceName + --resource-group $GROUP_NAME \ + --workspace-name $WORKSPACE_NAME ``` # [PowerShell](#tab/powershell) While a [Log Analytic workspace](../azure-monitor/logs/quick-create-workspace.md # [bash](#tab/bash) ```azurecli-interactive- logAnalyticsWorkspaceId=$(az monitor log-analytics workspace show \ - --resource-group $groupName \ - --workspace-name $workspaceName \ + LOG_ANALYTICS_WORKSPACE_ID=$(az monitor log-analytics workspace show \ + --resource-group $GROUP_NAME \ + --workspace-name $WORKSPACE_NAME \ --query customerId \ --output tsv)- logAnalyticsWorkspaceIdEnc=$(printf %s $logAnalyticsWorkspaceId | base64 -w0) # Needed for the next step - logAnalyticsKey=$(az monitor log-analytics workspace get-shared-keys \ - --resource-group $groupName \ - --workspace-name $workspaceName \ + LOG_ANALYTICS_WORKSPACE_ID_ENC=$(printf %s $LOG_ANALYTICS_WORKSPACE_ID | base64 -w0) # Needed for the next step + LOG_ANALYTICS_KEY=$(az monitor log-analytics workspace get-shared-keys \ + --resource-group $GROUP_NAME \ + --workspace-name $WORKSPACE_NAME \ --query primarySharedKey \ --output tsv)- logAnalyticsKeyEnc=$(printf %s $logAnalyticsKey | base64 -w0) # Needed for the next step + LOG_ANALYTICS_KEY_ENC=$(printf %s $LOG_ANALYTICS_KEY | base64 -w0) # Needed for the next step ``` # [PowerShell](#tab/powershell) While a [Log Analytic workspace](../azure-monitor/logs/quick-create-workspace.md # [bash](#tab/bash) ```bash- extensionName="appservice-ext" # Name of the App Service extension - namespace="appservice-ns" # Namespace in your cluster to install the extension and provision resources - kubeEnvironmentName="<kube-environment-name>" # Name of the App Service Kubernetes environment resource + EXTENSION_NAME="appservice-ext" # Name of the App Service extension + NAMESPACE="appservice-ns" # Namespace in your cluster to install the extension and provision resources + KUBE_ENVIRONMENT_NAME="<kube-environment-name>" # Name of the App Service Kubernetes environment resource ``` # [PowerShell](#tab/powershell) While a [Log Analytic workspace](../azure-monitor/logs/quick-create-workspace.md ```azurecli-interactive az k8s-extension create \- --resource-group $groupName \ - --name $extensionName \ + --resource-group $GROUP_NAME \ + --name $EXTENSION_NAME \ --cluster-type connectedClusters \- --cluster-name $clusterName \ + --cluster-name $CLUSTER_NAME \ --extension-type 'Microsoft.Web.Appservice' \ --release-train stable \ --auto-upgrade-minor-version true \ --scope cluster \- --release-namespace $namespace \ + --release-namespace $NAMESPACE \ --configuration-settings "Microsoft.CustomLocation.ServiceAccount=default" \- --configuration-settings "appsNamespace=${namespace}" \ - --configuration-settings "clusterName=${kubeEnvironmentName}" \ + --configuration-settings "appsNamespace=${NAMESPACE}" \ + --configuration-settings "clusterName=${KUBE_ENVIRONMENT_NAME}" \ --configuration-settings "keda.enabled=true" \ --configuration-settings "buildService.storageClassName=default" \ --configuration-settings "buildService.storageAccessMode=ReadWriteOnce" \- --configuration-settings "customConfigMap=${namespace}/kube-environment-config" \ + --configuration-settings "customConfigMap=${NAMESPACE}/kube-environment-config" \ --configuration-settings "envoy.annotations.service.beta.kubernetes.io/azure-load-balancer-resource-group=${aksClusterGroupName}" \ --configuration-settings "logProcessor.appLogs.destination=log-analytics" \- --config-protected-settings "logProcessor.appLogs.logAnalyticsConfig.customerId=${logAnalyticsWorkspaceIdEnc}" \ - --config-protected-settings "logProcessor.appLogs.logAnalyticsConfig.sharedKey=${logAnalyticsKeyEnc}" + --config-protected-settings "logProcessor.appLogs.logAnalyticsConfig.customerId=${LOG_ANALYTICS_WORKSPACE_ID_ENC}" \ + --config-protected-settings "logProcessor.appLogs.logAnalyticsConfig.sharedKey=${LOG_ANALYTICS_KEY_ENC}" ``` # [PowerShell](#tab/powershell) While a [Log Analytic workspace](../azure-monitor/logs/quick-create-workspace.md # [bash](#tab/bash) ```azurecli-interactive- extensionId=$(az k8s-extension show \ + EXTENSION_ID=$(az k8s-extension show \ --cluster-type connectedClusters \- --cluster-name $clusterName \ - --resource-group $groupName \ - --name $extensionName \ + --cluster-name $CLUSTER_NAME \ + --resource-group $GROUP_NAME \ + --name $EXTENSION_NAME \ --query id \ --output tsv) ``` While a [Log Analytic workspace](../azure-monitor/logs/quick-create-workspace.md 4. Wait for the extension to fully install before proceeding. You can have your terminal session wait until this complete by running the following command: ```azurecli-interactive- az resource wait --ids $extensionId --custom "properties.installState!='Pending'" --api-version "2020-07-01-preview" + az resource wait --ids $EXTENSION_ID --custom "properties.installState!='Pending'" --api-version "2020-07-01-preview" ``` You can use `kubectl` to see the pods that have been created in your Kubernetes cluster: ```bash-kubectl get pods -n $namespace +kubectl get pods -n $NAMESPACE ``` You can learn more about these pods and their role in the system from [Pods created by the App Service extension](overview-arc-integration.md#pods-created-by-the-app-service-extension). The [custom location](../azure-arc/kubernetes/custom-locations.md) in Azure is u # [bash](#tab/bash) ```bash- customLocationName="my-custom-location" # Name of the custom location + CUSTOM_LOCATION_NAME="my-custom-location" # Name of the custom location - connectedClusterId=$(az connectedk8s show --resource-group $groupName --name $clusterName --query id --output tsv) + CONNECTED_CLUSTER_ID=$(az connectedk8s show --resource-group $GROUP_NAME --name $CLUSTER_NAME-query id --output tsv) ``` # [PowerShell](#tab/powershell) The [custom location](../azure-arc/kubernetes/custom-locations.md) in Azure is u ```azurecli-interactive az customlocation create \- --resource-group $groupName \ - --name $customLocationName \ - --host-resource-id $connectedClusterId \ - --namespace $namespace \ - --cluster-extension-ids $extensionId + --resource-group $GROUP_NAME \ + --name $CUSTOM_LOCATION_NAME \ + --host-resource-id $CONNECTED_CLUSTER_ID \ + --namespace $NAMESPACE \ + --cluster-extension-ids $EXTENSION_ID ``` # [PowerShell](#tab/powershell) The [custom location](../azure-arc/kubernetes/custom-locations.md) in Azure is u 3. Validate that the custom location is successfully created with the following command. The output should show the `provisioningState` property as `Succeeded`. If not, run it again after a minute. ```azurecli-interactive- az customlocation show --resource-group $groupName --name $customLocationName + az customlocation show --resource-group $GROUP_NAME --name $CUSTOM_LOCATION_NAME ``` 4. Save the custom location ID for the next step. The [custom location](../azure-arc/kubernetes/custom-locations.md) in Azure is u # [bash](#tab/bash) ```azurecli-interactive- customLocationId=$(az customlocation show \ - --resource-group $groupName \ - --name $customLocationName \ + CUSTOM_LOCATION_ID=$(az customlocation show \ + --resource-group $GROUP_NAME \ + --name $CUSTOM_LOCATION_NAME \ --query id \ --output tsv) ``` Before you can start creating apps on the custom location, you need an [App Serv ```azurecli-interactive az appservice kube create \- --resource-group $groupName \ - --name $kubeEnvironmentName \ - --custom-location $customLocationId + --resource-group $GROUP_NAME \ + --name $KUBE_ENVIRONMENT_NAME \ + --custom-location $CUSTOM_LOCATION_ID ``` # [PowerShell](#tab/powershell) Before you can start creating apps on the custom location, you need an [App Serv 2. Validate that the App Service Kubernetes environment is successfully created with the following command. The output should show the `provisioningState` property as `Succeeded`. If not, run it again after a minute. ```azurecli-interactive- az appservice kube show --resource-group $groupName --name $kubeEnvironmentName + az appservice kube show --resource-group $GROUP_NAME --name $KUBE_ENVIRONMENT_NAME ``` |
app-service | Overview Disaster Recovery | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/app-service/overview-disaster-recovery.md | In this disaster recovery approach, you create regular backups of your web app t With this example architecture: -- A single web app is deployed to a singled region.+- A single web app is deployed to a single region. - The web app is regularly backed up to an Azure Storage account in the same region. - The cross-region replication of your backups depends on the data redundancy configuration in the Azure storage account. You should set your Azure Storage account as [GZRS](../storage/common/storage-redundancy.md#geo-zone-redundant-storage) if possible. GZRS offers both synchronous zone redundancy within a region and asynchronous in a secondary region. If GZRS isn't available, configure the account as [GRS](../storage/common/storage-redundancy.md#geo-redundant-storage). Both GZRS and GRS have an [RPO of about 15 minutes](../storage/common/storage-redundancy.md#redundancy-in-a-secondary-region). - To ensure that you can retrieve backups when the storage account's primary region becomes unavailable, [**enable read only access to secondary region**](../storage/common/storage-redundancy.md#read-access-to-data-in-the-secondary-region) (making the storage account **RA-GZRS** or **RA-GRS**, respectively). For more information on designing your applications to take advantage of geo-redundancy, see [Use geo-redundancy to design highly available applications](../storage/common/geo-redundant-design.md). Steps to create a passive-cold region without GRS and GZRS are summarized as fol - These disaster recovery strategies are applicable to both App Service multitenant and App Service Environments. - Within the same region, an App Service app can be deployed into [availability zones (AZ)](../reliability/availability-zones-overview.md) to help you achieve high availability for your mission-critical workloads. For more information, see [Migrate App Service to availability zone support](../reliability/migrate-app-service.md). - There are multiple ways to replicate your web apps content and configurations across Azure regions in an active-active or active-passive architecture, such as using [App service backup and restore](manage-backup.md). However, these options are point-in-time snapshots and eventually lead to web app versioning challenges across regions. To avoid these limitations, configure your CI/CD pipelines to deploy code to both the Azure regions. Consider using [Azure Pipelines](/azure/devops/pipelines/get-started/what-is-azure-pipelines) or [GitHub Actions](https://docs.github.com/actions). For more information, see [Continuous deployment to Azure App Service](deploy-continuous-deployment.md).-- Use an infrastructure-as-code (IoC) mechanism to manage your application resources in Azure. In a complex deployment across multiple regions, to manage the regions independently and to keep the configuration synchronized across regions in a reliable manner requires a predictable, testable, and repeatable process. Consider an IoC tool such as [Azure Resource Manager templates](../azure-resource-manager/management/overview.md) or [Terraform](/azure/developer/terraform/overview).+- Use an infrastructure-as-Code (IaC) mechanism to manage your application resources in Azure. In a complex deployment across multiple regions, to manage the regions independently and to keep the configuration synchronized across regions in a reliable manner requires a predictable, testable, and repeatable process. Consider an IaC tool such as [Azure Resource Manager templates](../azure-resource-manager/management/overview.md) or [Terraform](/azure/developer/terraform/overview). - Your application most likely depends on other data services in Azure, such as Azure SQL Database and Azure Storage accounts. You should develop disaster recovery strategies for each of these dependent Azure Services as well. For SQL Database, see [Active geo-replication for Azure SQL Database](/azure/azure-sql/database/active-geo-replication-overview). For Azure Storage, see [Azure Storage redundancy](../storage/common/storage-redundancy.md). - Aside from Azure Front Door, which is proposed in this article, Azure provides other load balancing options, such as Azure Traffic Manager. For a comparison of the various options, see [Load-balancing options - Azure Architecture Center](/azure/architecture/guide/technology-choices/load-balancing-overview). - It's also recommended to set up monitoring and alerts for your web apps to for timely notifications during a disaster. For more information, see [Application Insights availability tests](../azure-monitor/app/availability-overview.md). |
app-service | Reference App Settings | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/app-service/reference-app-settings.md | The following environment variables are related to [health checks](monitor-insta | Setting name | Description | |-|-| | `WEBSITE_HEALTHCHECK_MAXPINGFAILURES` | The maximum number of failed pings before removing the instance. Set to a value between `2` and `100`. When you're scaling up or out, App Service pings the Health check path to ensure new instances are ready. For more information, see [Health check](monitor-instances-health-check.md).|-| `WEBSITE_HEALTHCHECK_MAXUNHEALTHYWORKERPERCENT` | To avoid overwhelming healthy instances, no more than half of the instances will be excluded. For example, if an App Service Plan is scaled to four instances and three are unhealthy, at most two will be excluded. The other two instances (one healthy and one unhealthy) will continue to receive requests. In the worst-case scenario where all instances are unhealthy, none will be excluded. To override this behavior, set to a value between `0` and `100`. A higher value means more unhealthy instances will be removed. The default is `50` (50%). | +| `WEBSITE_HEALTHCHECK_MAXUNHEALTHYWORKERPERCENT` | To avoid overwhelming healthy instances, no more than half of the instances will be excluded. For example, if an App Service Plan is scaled to four instances and three are unhealthy, at most two will be excluded. The other two instances (one healthy and one unhealthy) will continue to receive requests. In the worst-case scenario where all instances are unhealthy, none will be excluded. To override this behavior, set to a value between `1` and `100`. A higher value means more unhealthy instances will be removed. The default is `50` (50%). | ## Push notifications |
application-gateway | Application Gateway Backend Health Troubleshooting | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/application-gateway/application-gateway-backend-health-troubleshooting.md | The status retrieved by any of these methods can be any one of the following sta If the backend health status for a server is healthy, it means that Application Gateway will forward the requests to that server. But if the backend health for all the servers in a backend pool is unhealthy or unknown, you might encounter problems when you try to access applications. This article describes the symptoms, cause, and resolution for each of the errors shown. +> [!NOTE] +> If your user doesn't have permission to see backend health statuses, `No results.` will be shown. + ## Backend health status: Unhealthy If the backend health status is **Unhealthy**, the portal view will resemble the following screenshot: |
application-gateway | Application Gateway Metrics | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/application-gateway/application-gateway-metrics.md | Application Gateway provides several builtΓÇæin timing metrics related to the re - **Backend connect time** - Time spent establishing a connection with the backend application. + *Aggregation type:Avg/Max* - This includes the network latency as well as the time taken by the backend serverΓÇÖs TCP stack to establish new connections. For TLS, it also includes the time spent on handshake. + Time spent establishing a connection with the backend application. ++ This includes the network latency as well as the time taken by the backend serverΓÇÖs TCP stack to establish new connections. For TLS, it also includes the time spent on handshake. - **Backend first byte response time** - Time interval between start of establishing a connection to backend server and receiving the first byte of the response header. + *Aggregation type:Avg/Max* ++ Time interval between start of establishing a connection to backend server and receiving the first byte of the response header. - This approximates the sum of *Backend connect time*, time taken by the request to reach the backend from Application Gateway, time taken by backend application to respond (the time the server took to generate content, potentially fetch database queries), and the time taken by first byte - of the response to reach the Application Gateway from the backend. + This approximates the sum of *Backend connect time*, time taken by the request to reach the backend from Application Gateway, time taken by backend application to respond (the time the server took to generate content, potentially fetch database queries), and the time taken by first byte of the response to reach the Application Gateway from the backend. - **Backend last byte response time** - Time interval between start of establishing a connection to backend server and receiving the last byte of the response body. + *Aggregation type:Avg/Max* ++ Time interval between start of establishing a connection to backend server and receiving the last byte of the response body. - This approximates the sum of *Backend first byte response time* and data transfer time (this number may vary greatly depending on the size of objects requested and the latency of the server network). + This approximates the sum of *Backend first byte response time* and data transfer time (this number may vary greatly depending on the size of objects requested and the latency of the server network). - **Application gateway total time** - Average time that it takes for a request to be received, processed and its response to be sent. + *Aggregation type:Avg/Max* - This is the interval from the time when Application Gateway receives the first byte of the HTTP request to the time when the last response byte has been sent to the client. This includes the processing time taken by Application Gateway, the *Backend last byte response time*, and the time taken by Application Gateway to send all the response. + This metric captures either the Average/Max time taken for a request to be received, processed and its response to be sent. -- **Client RTT**+ This is the interval from the time when Application Gateway receives the first byte of the HTTP request to the time when the last response byte has been sent to the client. This includes the processing time taken by Application Gateway, the *Backend last byte response time*, and the time taken by Application Gateway to send all the response. - Average round trip time between clients and Application Gateway. +- **Client RTT** + *Aggregation type:Avg/Max* + This metric captures the Average/Max round trip time between clients and Application Gateway. These metrics can be used to determine whether the observed slowdown is due to the client network, Application Gateway performance, the backend network and backend server TCP stack saturation, backend application performance, or large file size. |
automation | Extension Based Hybrid Runbook Worker Install | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/automation/extension-based-hybrid-runbook-worker-install.md | $settings = @{ **Azure VMs** ```powershell-Set-AzVMExtension -ResourceGroupName <VMResourceGroupName> -Location <VMLocation> -VMName <VMName> -Name "HybridWorkerExtension" -Publisher "Microsoft.Azure.Automation.HybridWorker" -ExtensionType HybridWorkerForLinux TypeHandlerVersion 1.1 -Settings $settings -EnableAutomaticUpgrade $true +Set-AzVMExtension -ResourceGroupName <VMResourceGroupName> -Location <VMLocation> -VMName <VMName> -Name "HybridWorkerExtension" -Publisher "Microsoft.Azure.Automation.HybridWorker" -ExtensionType HybridWorkerForLinux -TypeHandlerVersion 1.1 -Settings $settings -EnableAutomaticUpgrade $true ``` **Azure Arc-enabled VMs** |
automation | Migrate Run As Accounts Managed Identity | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/automation/migrate-run-as-accounts-managed-identity.md | To migrate from an Automation Run As account or Classic Run As account to a mana We recommend that you test the managed identity to verify if the runbook works as expected by creating a copy of your production runbook. Update your test runbook code to authenticate by using the managed identity. This method ensures that you don't override `AzureRunAsConnection` in your production runbook and break the existing Automation instance. After you're sure that the runbook code runs as expected via the managed identity, update your production runbook to use the managed identity. - For managed identity support, use the `Connect-AzAccount` cmdlet. To learn more about this cmdlet, see [Connect-AzAccount](/powershell/module/az.accounts/Connect-AzAccount?branch=main&view=azps-8.3.0) in the PowerShell reference. + For managed identity support, use the `Connect-AzAccount` cmdlet. To learn more about this cmdlet, see [Connect-AzAccount](/powershell/module/az.accounts/Connect-AzAccount?branch=main&view=azps-8.3.0&preserve-view=true) in the PowerShell reference. - If you're using `Az` modules, update to the latest version by following the steps in the [Update Azure PowerShell modules](./automation-update-azure-modules.md?branch=main#update-az-modules) article. - If you're using AzureRM modules, update `AzureRM.Profile` to the latest version and replace it by using the `Add-AzureRMAccount` cmdlet with `Connect-AzureRMAccount ΓÇôIdentity`. try { "Logging in to Azure..." - Connect-AzAccountΓÇ»-IdentityΓÇ»-AccountIdΓÇ»<Client Id of myUserAssignedIdentity> + Connect-AzAccount -Identity -AccountId <Client Id of myUserAssignedIdentity> } catch { Write-Error -Message $_.Exception For example, in the runbook **Start Azure V2 VMs** in the runbook gallery, you m For more information, see the sample runbook name **AzureAutomationTutorialWithIdentityGraphical** that's created with the Automation account. > [!NOTE]-> AzureRM PowerShell modules are retiring on 29 February 2024. If you are using AzureRM PowerShell modules in Graphical runbooks, you must upgrade them to use Az PowerShell modules. [Learn more](https://learn.microsoft.com/powershell/azure/migrate-from-azurerm-to-az?view=azps-9.4.0). +> AzureRM PowerShell modules are retiring on 29 February 2024. If you are using AzureRM PowerShell modules in Graphical runbooks, you must upgrade them to use Az PowerShell modules. [Learn more](/powershell/azure/migrate-from-azurerm-to-az?view=azps-9.4.0&preserve-view=true). ## Next steps |
automation | Source Control Integration | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/automation/source-control-integration.md | The following subsections illustrate PowerShell creation of the source control c #### Create source control connection for GitHub ```powershell-interactive-New-AzAutomationSourceControl -Name SCGitHub -RepoUrl https://github.com/<accountname>/<reponame>.git -SourceType GitHub -FolderPath "/MyRunbooks" -Branch master -AccessToken <secureStringofPAT> -ResourceGroupName <ResourceGroupName> -AutomationAccountName <AutomationAccountName> +New-AzAutomationSourceControl -Name SCGitHub -RepoUrl https://github.com/<accountname>/<reponame>.git -SourceType GitHub -FolderPath "/MyRunbooks" -Branch main -AccessToken <secureStringofPAT> -ResourceGroupName <ResourceGroupName> -AutomationAccountName <AutomationAccountName> ``` #### Create source control connection for Azure DevOps (Git) New-AzAutomationSourceControl -Name SCGitHub -RepoUrl https://github.com/<accoun > Azure DevOps (Git) uses a URL that accesses **dev.azure.com** instead of **visualstudio.com**, used in earlier formats. The older URL format `https://<accountname>.visualstudio.com/<projectname>/_git/<repositoryname>` is deprecated but still supported. The new format is preferred. ```powershell-interactive-New-AzAutomationSourceControl -Name SCReposGit -RepoUrl https://dev.azure.com/<accountname>/<adoprojectname>/_git/<repositoryname> -SourceType VsoGit -AccessToken <secureStringofPAT> -Branch master -ResourceGroupName <ResourceGroupName> -AutomationAccountName <AutomationAccountName> -FolderPath "/Runbooks" +New-AzAutomationSourceControl -Name SCReposGit -RepoUrl https://dev.azure.com/<accountname>/<adoprojectname>/_git/<repositoryname> -SourceType VsoGit -AccessToken <secureStringofPAT> -Branch main -ResourceGroupName <ResourceGroupName> -AutomationAccountName <AutomationAccountName> -FolderPath "/Runbooks" ``` #### Create source control connection for Azure DevOps (TFVC) |
azure-arc | Release Notes | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/azure-arc/data/release-notes.md | New for this release: - [Rotate Azure Arc-enabled SQL Managed Instance service-managed credentials (preview)](rotate-sql-managed-instance-credentials.md) - Azure Arc-enabled PostgreSQL - Require client connections to use SSL- - Extended Azure Arc-enabled SQL Managed Instance authentication control plane to PostgresSQL + - Extended Azure Arc-enabled SQL Managed Instance authentication control plane to PostgreSQL ## February 14, 2023 |
azure-functions | Create First Function Arc Cli | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/azure-functions/create-first-function-arc-cli.md | Title: 'Quickstart: Create a function app on Azure Arc' description: Get started with Azure Functions on Azure Arc by deploying your first function app. Last updated 09/02/2022-+ ms.devlang: azurecli In this quickstart, you create an Azure Functions project and deploy it to a fun > > Publishing PowerShell function projects to Azure Arc-enabled Kubernetes clusters isn't currently supported. If you need to deploy PowerShell functions to Azure Arc-enabled Kubernetes clusters, [create your function app in a container](create-first-function-arc-custom-container.md). +If you need to customize the container in which your function app runs, instead see [Create your first containerized functions on Azure Arc (preview)](create-first-function-arc-custom-container.md). + ## Prerequisites On your local computer: |
azure-functions | Create First Function Arc Custom Container | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/azure-functions/create-first-function-arc-custom-container.md | Title: 'Quickstart: Create a function app on Azure Arc in a custom container' + Title: Create your first containerized Azure Functions on Azure Arc description: Get started with Azure Functions on Azure Arc by deploying your first function app in a custom Linux container. Previously updated : 05/11/2021- Last updated : 05/07/2023+ ms.devlang: azurecli+zone_pivot_groups: programming-languages-set-functions -# Create your first function on Azure Arc using a custom container (preview) +# Create your first containerized Azure Functions on Azure Arc (preview) -In this quickstart, you create an Azure Functions project running in a custom container and deploy it to an [Azure Arc-enabled Kubernetes cluster](../azure-arc/kubernetes/overview.md) from your Docker Hub account. To learn more, see [App Service, Functions, and Logic Apps on Azure Arc](../app-service/overview-arc-integration.md). This scenario only supports function apps running on Linux. +In this article, you create a function app running in a Linux container and deploy it to an [Azure Arc-enabled Kubernetes cluster](../azure-arc/kubernetes/overview.md) from a container registry. When you create your own container, you can customize the execution environment for your function app. To learn more, see [App Service, Functions, and Logic Apps on Azure Arc](../app-service/overview-arc-integration.md). > [!NOTE]-> Support for running functions on an Azure Arc-enabled Kubernetes cluster is currently in preview. +> Support for deploying a custom container to an Azure Arc-enabled Kubernetes cluster is currently in preview. -## Prerequisites +You can also publish your functions to an Azure Arc-enabled Kubernetes cluster without first creating a container. To learn more, see [Create your first function on Azure Arc (preview)](create-first-function-arc-cli.md) -On your local computer: --# [C\#](#tab/csharp) --+ [.NET 6.0 SDK](https://dotnet.microsoft.com/download) -+ [Azure Functions Core Tools version 4.x](functions-run-local.md?tabs=v4%2Ccsharp#install-the-azure-functions-core-tools) -+ [Azure CLI](/cli/azure/install-azure-cli) version 2.4 or later -+ [Docker](https://docs.docker.com/install/) -+ [Docker ID](https://hub.docker.com/signup) --# [JavaScript](#tab/nodejs) --+ [Node.js](https://nodejs.org/) version 12 (Node.js version 10 is also supported) -+ [Azure Functions Core Tools version 4.x](functions-run-local.md?tabs=v4%2Cnode#install-the-azure-functions-core-tools) -+ [Azure CLI](/cli/azure/install-azure-cli) version 2.4 or later -+ [Docker](https://docs.docker.com/install/) -+ [Docker ID](https://hub.docker.com/signup) --# [Python](#tab/python) --+ [Python versions that are supported by Azure Functions](supported-languages.md#languages-by-runtime-version) -+ [Azure Functions Core Tools version 4.x](functions-run-local.md?tabs=v4%2Cpython#install-the-azure-functions-core-tools) -+ [Azure CLI](/cli/azure/install-azure-cli) version 2.4 or later -+ [Docker](https://docs.docker.com/install/) -+ [Docker ID](https://hub.docker.com/signup) --# [PowerShell](#tab/powershell) --+ [PowerShell 7](/powershell/scripting/install/installing-powershell-core-on-windows) -+ [Azure Functions Core Tools version 4.x](functions-run-local.md?tabs=v4%2Cpowershell#install-the-azure-functions-core-tools) -+ [Azure CLI](/cli/azure/install-azure-cli) version 2.4 or later -+ [Docker](https://docs.docker.com/install/) -+ [Docker ID](https://hub.docker.com/signup) -+ PowerShell 7 requires recent versions of two Azure CLI extensions. Make sure you install the correct versions of the following extensions as you complete this quickstart article: - + `connectedk8s` version 1.2.5, or a later version - + `appservice-kube` version 0.1.3 or a later version -- [!INCLUDE [functions-arc-create-environment](../../includes/functions-arc-create-environment.md)] [!INCLUDE [app-service-arc-cli-install-extensions](../../includes/app-service-arc-cli-install-extensions.md)] -## Create the local function project --In Azure Functions, a function project is the context for one or more individual functions that each responds to a specific trigger. All functions in a project share the same local and hosting configurations. In this section, you create a function project that contains a single function. --1. Run the `func init` command, as follows, to create a functions project in a folder named *LocalFunctionProj* with the specified runtime: -- # [C\#](#tab/csharp) -- ```console - func init LocalFunctionProj --dotnet --docker - ``` - # [JavaScript](#tab/nodejs) -- ```console - func init LocalFunctionProj --javascript --docker - ``` -- # [Python](#tab/python) -- Python requires a virtual environment, the commands for which differ between bash and a Windows command line. - - + Bash: -- ```bash - python -m venv .venv - source .venv/bin/activate - ``` - - + Command line: -- ```cmd - py -m venv .venv - .venv\scripts\activate - ``` -- Now, you create the project inside the virtual environment. - - ```console - func init LocalFunctionProj --python --docker - ``` - # [PowerShell](#tab/powershell) --- ```console - func init LocalFunctionProj --powershell --docker - ``` -- -- The `--docker` option generates a `Dockerfile` for the project, which defines a suitable custom container for use with Azure Functions and the selected runtime. --1. Navigate into the project folder: -- ```console - cd LocalFunctionProj - ``` -- This folder contains the `Dockerfile` and other files for the project, including configurations files named [local.settings.json](functions-develop-local.md#local-settings-file) and [host.json](functions-host-json.md). By default, the *local.settings.json* file is excluded from source control in the *.gitignore* file. This exclusion is because the file can contain secrets that are downloaded from Azure. --1. Open the generated `Dockerfile` and locate the `3.0` tag for the base image. If there's a `3.0` tag, replace it with a `3.0.15885` tag. For example, in a JavaScript application, the Docker file should be modified to have `FROM mcr.microsoft.com/azure-functions/node:3.0.15885`. This version of the base image supports deployment to an Azure Arc-enabled Kubernetes cluster. --1. Add a function to your project by using the following command, where the `--name` argument is the unique name of your function (HttpExample) and the `--template` argument specifies the function's trigger (HTTP). -- ```console - func new --name HttpExample --template "HTTP trigger" --authlevel "anonymous" - ``` --## Build the container image and test locally --The Dockerfile in the project root describes the minimum required environment to run the function app in a container. The complete list of supported base images for Azure Functions can be found in the [Azure Functions base image page](https://hub.docker.com/_/microsoft-azure-functions-base). --1. In the root project folder, run the [docker build](https://docs.docker.com/engine/reference/commandline/build/) command, and provide a name, `azurefunctionsimage`, and tag, `v1.0.0`. -- The following command builds the Docker image for the container. -- ```console - docker build --tag <DOCKER_ID>/azurefunctionsimage:v1.0.0 . - ``` -- In this example, replace `<DOCKER_ID>` with your Docker Hub account ID. When the command completes, you can run the new container locally. - -1. To test the build, run the image in a local container using the [docker run](https://docs.docker.com/engine/reference/commandline/run/) command, with the adding the ports argument, `-p 8080:80`. -- ```console - docker run -p 8080:80 -it <docker_id>/azurefunctionsimage:v1.0.0 - ``` -- Again, replace `<DOCKER_ID` with your Docker ID and adding the ports argument, `-p 8080:80` --1. After the image is running in a local container, browse to `http://localhost:8080/api/HttpExample?name=Functions`, which should display the same "hello" message as before. Because the HTTP triggered function uses anonymous authorization, you can still call the function even though it's running in the container. Function access key settings are enforced when running locally in a container. If you have problems calling the function, make sure that [access to the function](functions-bindings-http-webhook-trigger.md#authorization-keys) is set to anonymous. --After you've verified the function app in the container, stop docker with **Ctrl**+**C**. --## Push the image to Docker Hub --Docker Hub is a container registry that hosts images and provides image and container services. To share your image, which includes deploying to Azure, you must push it to a registry. --1. If you haven't already signed in to Docker, do so with the [docker login](https://docs.docker.com/engine/reference/commandline/login/) command, replacing `<docker_id>` with your Docker ID. This command prompts you for your username and password. A "Login Succeeded" message confirms that you're signed in. -- ```console - docker login - ``` - -1. After you've signed in, push the image to Docker Hub by using the [docker push](https://docs.docker.com/engine/reference/commandline/push/) command, again replacing `<docker_id>` with your Docker ID. -- ```console - docker push <docker_id>/azurefunctionsimage:v1.0.0 - ``` --1. Depending on your network speed, pushing the image the first time might take a few minutes (pushing subsequent changes is much faster). While you're waiting, you can proceed to the next section and create Azure resources in another terminal. -- ## Create Azure resources Before you can deploy your container to your new App Service Kubernetes environment, you need to create two more resources: In the previous example, replace `<STORAGE_NAME>` with a name that is appropriat Run the [az functionapp create](/cli/azure/functionapp#az-functionapp-create) command to create a new function app in the environment. -# [C\#](#tab/csharp) -```azurecli -az functionapp create --resource-group MyResourceGroup --name <APP_NAME> --custom-location <CUSTOM_LOCATION_ID> --storage-account <STORAGE_NAME> --functions-version 4 --runtime dotnet --deployment-container-image-name <DOCKER_ID>/azurefunctionsimage:v1.0.0 -``` --# [JavaScript](#tab/nodejs) -```azurecli -az functionapp create --resource-group MyResourceGroup --name <APP_NAME> --custom-location <CUSTOM_LOCATION_ID> --storage-account <STORAGE_NAME> --functions-version 4 --runtime node --runtime-version 12 --deployment-container-image-name <DOCKER_ID>/azurefunctionsimage:v1.0.0 -``` --# [Python](#tab/python) +# [Azure Container Registry](#tab/acr) ```azurecli-az functionapp create --resource-group MyResourceGroup --name <APP_NAME> --custom-location <CUSTOM_LOCATION_ID> --storage-account <STORAGE_NAME> --functions-version 4 --runtime python --runtime-version 3.8 --deployment-container-image-name <DOCKER_ID>/azurefunctionsimage:v1.0.0 +az functionapp create --name <APP_NAME> --custom-location <CUSTOM_LOCATION_ID> --storage-account <STORAGE_NAME> --resource-group AzureFunctionsContainers-rg --image <LOGIN_SERVER>/azurefunctionsimage:v1.0.0 --registry-username <USERNAME> --registry-password <SECURE_PASSWORD> ```-# [PowerShell](#tab/powershell) +# [Docker Hub](#tab/docker) ```azurecli-az functionapp create --resource-group myResourceGroup --name <APP_NAME> --custom-location <CUSTOM_LOCATION_ID> --storage-account <STORAGE_NAME> --functions-version 4 --runtime powershell --runtime-version 7.0 +az functionapp create --name <APP_NAME> --custom-location <CUSTOM_LOCATION_ID> --storage-account <STORAGE_NAME> --resource-group AzureFunctionsContainers-rg --image <DOCKER_ID>/azurefunctionsimage:v1.0.0 ```- -In this example, replace `<CUSTOM_LOCATION_ID>` with the ID of the custom location you determined for the App Service Kubernetes environment. Also, replace `<STORAGE_NAME>` with the name of the account you used in the previous step, `<APP_NAME>` with a globally unique name appropriate to you, and `<DOCKER_ID>` with your Docker Hub ID. --The *deployment-container-image-name* parameter specifies the image to use for the function app. You can use the [az functionapp config container show](/cli/azure/functionapp/config/container#az-functionapp-config-container-show) command to view information about the image used for deployment. You can also use the [az functionapp config container set](/cli/azure/functionapp/config/container#az-functionapp-config-container-set) command to deploy from a different image. --When you first create the function app, it pulls the initial image from your Docker Hub. You can also [Enable continuous deployment to Azure](functions-create-function-linux-custom-image.md#enable-continuous-deployment-to-azure) from Docker Hub. +In this example, replace `<CUSTOM_LOCATION_ID>` with the ID of the custom location you determined for the App Service Kubernetes environment. Also, replace `<STORAGE_NAME>` with the name of the account you used in the previous step, `<APP_NAME>` with a globally unique name, and `<DOCKER_ID>` or `<LOGIN_SERVER>` with your Docker Hub account ID or Container Registry server, respectively. When you're deploying from a custom container registry, the image name indicates the URL of the registry. -To learn how to enable SSH in the image, see [Enable SSH connections](functions-create-function-linux-custom-image.md#enable-ssh-connections). +When you first create the function app, it pulls the initial image from your Docker Hub. +<! Need to verify if CI/CD is supported: +You can also [Enable continuous deployment](./functions-how-to-custom-container.md#enable-continuous-deployment-to-azure) to Azure from Docker Hub. --> ### Set required app settings This code must be run either in Cloud Shell or in Bash on your local computer. R [!INCLUDE [functions-run-remote-azure-cli](../../includes/functions-run-remote-azure-cli.md)] -## Next steps --Now that you have your function app running in a container an Azure Arc-enabled App Service Kubernetes environment, you can connect it to Azure Storage by adding a Queue Storage output binding. +## Clean up resources -# [C\#](#tab/csharp) --> [!div class="nextstepaction"] -> [Connect to an Azure Storage queue](functions-add-output-binding-storage-queue-cli.md?pivots=programming-language-csharp) +If you want to continue working with Azure Function using the resources you created in this article, you can leave all those resources in place. -# [JavaScript](#tab/nodejs) +When you are done working with this function app deployment, delete the `AzureFunctionsContainers-rg` resource group to clean up all the resources in that group: -> [!div class="nextstepaction"] -> [Connect to an Azure Storage queue](functions-add-output-binding-storage-queue-cli.md?pivots=programming-language-javascript) --# [Python](#tab/python) +```azurecli +az group delete --name AzureFunctionsContainers-rg +``` -> [!div class="nextstepaction"] -> [Connect to an Azure Storage queue](functions-add-output-binding-storage-queue-cli.md?pivots=programming-language-python) +This only removes the resources created in this article. The underlying Azure Arc environment remains in place. -# [PowerShell](#tab/powershell) +## Next steps > [!div class="nextstepaction"]-> [Connect to an Azure Storage queue](functions-add-output-binding-storage-queue-cli.md?pivots=programming-language-powershell) --+> [Working with custom containers and Azure Functions](./functions-how-to-custom-container.md) |
azure-functions | Functions Bindings Azure Data Explorer Input | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/azure-functions/functions-bindings-azure-data-explorer-input.md | + + Title: Azure Data Explorer input bindings for Azure Functions (preview) +description: Understand usage of Azure Data Explorer input bindings for Azure Functions (Query data from Azure Data Explorer) +++ Last updated : 05/04/2023+++zone_pivot_groups: programming-languages-set-functions-data-explorer +++# Azure Data Explorer input bindings for Azure Functions (preview) ++The Azure Data Explorer input binding retrieves data from a database. ++## Examples ++++# [In-process](#tab/in-process) ++More samples for the Azure Data Explorer input binding are available in the [GitHub repository](https://github.com/Azure/Webjobs.Extensions.Kusto/blob/main/samples/samples-csharp). ++This section contains the following examples: ++* [HTTP trigger, get rows by ID from query string](#http-trigger-look-up-id-from-query-string-c) +* [HTTP trigger, get multiple rows from route data](#http-trigger-get-multiple-items-from-route-data-c) ++The examples refer to `Product` class and a corresponding database table: ++```cs +public class Product +{ + [JsonProperty(nameof(ProductID))] + public long ProductID { get; set; } ++ [JsonProperty(nameof(Name))] + public string Name { get; set; } ++ [JsonProperty(nameof(Cost))] + public double Cost { get; set; } +} +``` ++```kusto +.create-merge table Products (ProductID:long, Name:string, Cost:double) +``` ++<a id="http-trigger-look-up-id-from-query-string-c"></a> ++### HTTP trigger, get row by ID from query string ++The following example shows a [C# function](functions-dotnet-class-library.md) that retrieves a list of products given a productId. The function is triggered by an HTTP request that uses a parameter for the ID. That ID is used to retrieve a list of `Product` that matches the query. ++> [!NOTE] +> The HTTP query string parameter is case-sensitive. +> ++```cs +using System.Collections.Generic; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Azure.WebJobs.Extensions.Http; +using Microsoft.Azure.WebJobs.Extensions.Kusto.Samples.Common; +using Microsoft.Azure.WebJobs.Kusto; ++namespace Microsoft.Azure.WebJobs.Extensions.Kusto.Samples.InputBindingSamples +{ + public static class GetProducts + { + [FunctionName("GetProductsList")] + public static async Task<IActionResult> RunAsync( + [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "getproducts")] + HttpRequest req, + [Kusto(Database:"productsdb" , + KqlCommand = "declare query_parameters (productId:long);Products | where ProductID == productId" , + KqlParameters = "@productId={Query.productId}", // get the value of the query parameter "productId" + Connection = "KustoConnectionString")] + IAsyncEnumerable<Product> products) + { + IAsyncEnumerator<Product> enumerator = products.GetAsyncEnumerator(); + var productList = new List<Product>(); + while (await enumerator.MoveNextAsync()) + { + productList.Add(enumerator.Current); + } + await enumerator.DisposeAsync(); + return new OkObjectResult(productList); + } + } +} +``` ++<a id="http-trigger-get-multiple-items-from-route-data-c"></a> ++### HTTP trigger, get multiple rows from route parameter ++The following example shows a [C# function](functions-dotnet-class-library.md) that retrieves documents returned by the query. The function is triggered by an HTTP request that uses route data to specify the value of a KQL function parameter. GetProductsByName is a simple function that retrieves a set of products that match a product name ++```kusto +.create function ifnotexists GetProductsByName(name:string) +{ + Products | where Name == name +} +``` ++```cs +using System.Collections.Generic; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Azure.WebJobs; +using Microsoft.Azure.WebJobs.Extensions.Http; ++namespace Microsoft.Azure.WebJobs.Extensions.Kusto.Samples.InputBindingSamples +{ + public static class GetProductsFunction + { + [FunctionName("GetProductsFunction")] + public static IActionResult Run( + [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "getproductsfn/{name}")] + HttpRequest req, + [Kusto(Database:"productsdb" , + KqlCommand = "declare query_parameters (name:string);GetProductsByName(name)" , + KqlParameters = "@name={name}", + Connection = "KustoConnectionString")] + IEnumerable<Product> products) + { + return new OkObjectResult(products); + } + } +} +``` ++# [Isolated process](#tab/isolated-process) ++More samples for the Azure Data Explorer input binding (out of process) are available in the [GitHub repository](https://github.com/Azure/Webjobs.Extensions.Kusto/tree/main/samples/samples-outofproc). ++This section contains the following examples: ++* [HTTP trigger, get row by ID from query string](#http-trigger-look-up-id-from-query-string-c-oop) +* [HTTP trigger, get multiple rows from route data](#http-trigger-get-multiple-items-from-route-data-c-oop) ++The examples refer to a `Product` class and the Products table, both of which are defined in the previous sections. ++<a id="http-trigger-look-up-id-from-query-string-c-oop"></a> ++### HTTP trigger, get row by ID from query string ++The following example shows a [C# function](functions-dotnet-class-library.md) that retrieves a single record. The function is triggered by an HTTP request that uses a query string to specify the ID. That ID is used to retrieve a `Product` record with the specified query. ++> [!NOTE] +> The HTTP query string parameter is case-sensitive. +> ++```cs +using System.Text.Json.Nodes; +using Microsoft.Azure.Functions.Worker; +using Microsoft.Azure.Functions.Worker.Extensions.Kusto; +using Microsoft.Azure.Functions.Worker.Http; +using Microsoft.Azure.WebJobs.Extensions.Kusto.SamplesOutOfProc.OutputBindingSamples.Common; ++namespace Microsoft.Azure.WebJobs.Extensions.Kusto.SamplesOutOfProc.InputBindingSamples +{ + public static class GetProductsQuery + { + [Function("GetProductsQuery")] + public static JsonArray Run( + [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "getproductsquery")] HttpRequestData req, + [KustoInput(Database: "productsdb", + KqlCommand = "declare query_parameters (productId:long);Products | where ProductID == productId", + KqlParameters = "@productId={Query.productId}",Connection = "KustoConnectionString")] JsonArray products) + { + return products; + } + } +} +``` ++<a id="http-trigger-get-multiple-items-from-route-data-c-oop"></a> ++### HTTP trigger, get multiple rows from route parameter ++The following example shows a [C# function](functions-dotnet-class-library.md) that retrieves records returned by the query (based on the name of product in this case). The function is triggered by an HTTP request that uses route data to specify the value of a query parameter. That parameter is used to filter the `Product` records in the specified query. ++```cs +using Microsoft.Azure.Functions.Worker; +using Microsoft.Azure.Functions.Worker.Extensions.Kusto; +using Microsoft.Azure.Functions.Worker.Http; +using Microsoft.Azure.WebJobs.Extensions.Kusto.SamplesOutOfProc.OutputBindingSamples.Common; ++namespace Microsoft.Azure.WebJobs.Extensions.Kusto.SamplesOutOfProc.InputBindingSamples +{ + public static class GetProductsFunction + { + [Function("GetProductsFunction")] + public static IEnumerable<Product> Run( + [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "getproductsfn/{name}")] HttpRequestData req, + [KustoInput(Database: "productsdb", + KqlCommand = "declare query_parameters (name:string);GetProductsByName(name)", + KqlParameters = "@name={name}",Connection = "KustoConnectionString")] IEnumerable<Product> products) + { + return products; + } + } +} +``` ++<!-- Uncomment to support C# script examples. +# [C# Script](#tab/csharp-script) ++--> +++++More samples for the java Azure Data Explorer input binding are available in the [GitHub repository](https://github.com/Azure/Webjobs.Extensions.Kusto/tree/main/samples/samples-java). ++This section contains the following examples: ++* [HTTP trigger, get multiple rows](#http-trigger-get-multiple-items-java) +* [HTTP trigger, get row by ID from query string](#http-trigger-look-up-id-from-query-string-java) ++The examples refer to a `Product` class (in a separate file `Product.java`) and a corresponding database table: ++```java +package com.microsoft.azure.kusto.common; ++import com.fasterxml.jackson.annotation.JsonProperty; ++public class Product { + @JsonProperty("ProductID") + public long ProductID; + @JsonProperty("Name") + public String Name; + @JsonProperty("Cost") + public double Cost; ++ public Product() { + } ++ public Product(long ProductID, String name, double Cost) { + this.ProductID = ProductID; + this.Name = name; + this.Cost = Cost; + } +} ++``` ++<a id="http-trigger-get-multiple-items-java"></a> ++### HTTP trigger, get multiple rows ++The example uses a route parameter to specify the name of the ID of the products. All matching products are retrieved from the products table. ++```java +package com.microsoft.azure.kusto.inputbindings; ++import com.microsoft.azure.functions.HttpMethod; +import com.microsoft.azure.functions.HttpRequestMessage; +import com.microsoft.azure.functions.HttpResponseMessage; +import com.microsoft.azure.functions.HttpStatus; +import com.microsoft.azure.functions.annotation.AuthorizationLevel; +import com.microsoft.azure.functions.annotation.FunctionName; +import com.microsoft.azure.functions.annotation.HttpTrigger; +import com.microsoft.azure.functions.kusto.annotation.KustoInput; +import com.microsoft.azure.kusto.common.Product; +++import java.util.Optional; ++public class GetProducts { + @FunctionName("GetProducts") + public HttpResponseMessage run( + @HttpTrigger(name = "req", methods = { + HttpMethod.GET}, authLevel = AuthorizationLevel.ANONYMOUS, route = "getproducts/{productId}") HttpRequestMessage<Optional<String>> request, + @KustoInput(name = "getjproducts", kqlCommand = "declare query_parameters (productId:long);Products | where ProductID == productId", + kqlParameters = "@productId={productId}", database = "productsdb", connection = "KustoConnectionString") Product[] products) { + return request.createResponseBuilder(HttpStatus.OK).header("Content-Type", "application/json").body(products) + .build(); + } +} +``` ++<a id="http-trigger-look-up-id-from-query-string-java"></a> ++### HTTP trigger, get row by ID from query string ++The following example shows a query the products table by the product name. The function is triggered by an HTTP request that uses a query string to specify the value of a query parameter. That parameter is used to filter the `Product` records in the specified query. ++```java +package com.microsoft.azure.kusto.inputbindings; ++import com.microsoft.azure.functions.HttpMethod; +import com.microsoft.azure.functions.HttpRequestMessage; +import com.microsoft.azure.functions.HttpResponseMessage; +import com.microsoft.azure.functions.HttpStatus; +import com.microsoft.azure.functions.annotation.AuthorizationLevel; +import com.microsoft.azure.functions.annotation.FunctionName; +import com.microsoft.azure.functions.annotation.HttpTrigger; +import com.microsoft.azure.functions.kusto.annotation.KustoInput; +import com.microsoft.azure.kusto.common.Product; ++import java.util.Optional; ++public class GetProductsQueryString { + @FunctionName("GetProductsQueryString") + public HttpResponseMessage run(@HttpTrigger(name = "req", methods = { + HttpMethod.GET}, authLevel = AuthorizationLevel.ANONYMOUS, route = "getproducts") HttpRequestMessage<Optional<String>> request, + @KustoInput(name = "getjproductsquery", kqlCommand = "declare query_parameters (name:string);GetProductsByName(name)", + kqlParameters = "@name={Query.name}", database = "productsdb", connection = "KustoConnectionString") Product[] products) { + return request.createResponseBuilder(HttpStatus.OK).header("Content-Type", "application/json").body(products) + .build(); + } +} +``` ++++More samples for the Azure Data Explorer input binding are available in the [GitHub repository](https://github.com/Azure/Webjobs.Extensions.Kusto/tree/main/samples/samples-node). ++This section contains the following examples: ++* [HTTP trigger, get multiple rows](#http-trigger-get-multiple-items-javascript) +* [HTTP trigger, get row by ID from query string](#http-trigger-look-up-id-from-query-string-javascript) ++The examples refer to a database table: ++<a id="http-trigger-get-multiple-items-javascript"></a> ++### HTTP trigger, get multiple rows ++The following example shows an Azure Data Explorer input binding in a function.json file and a JavaScript function that reads from a query and returns the results in the HTTP response. ++The following is binding data in the function.json file: ++```json +{ + "bindings": [ + { + "authLevel": "function", + "name": "req", + "direction": "in", + "type": "httpTrigger", + "methods": [ + "get" + ], + "route": "getproducts/{productId}" + }, + { + "name": "$return", + "type": "http", + "direction": "out" + }, + { + "name": "productget", + "type": "kusto", + "database": "productsdb", + "direction": "in", + "kqlCommand": "declare query_parameters (productId:long);Products | where ProductID == productId", + "kqlParameters": "@productId={productId}", + "connection": "KustoConnectionString" + } + ], + "disabled": false +} +``` ++The [configuration](#configuration) section explains these properties. ++The following is sample JavaScript code: ++```javascript +module.exports = async function (context, req, productget) { + return { + status: 200, + body: productget + }; +} +``` ++<a id="http-trigger-look-up-id-from-query-string-javascript"></a> ++### HTTP trigger, get row by name from query string ++The following example shows a query the products table by the product name. The function is triggered by an HTTP request that uses a query string to specify the value of a query parameter. That parameter is used to filter the `Product` records in the specified query. ++The following is binding data in the function.json file: ++```json +{ + "bindings": [ + { + "authLevel": "function", + "name": "req", + "direction": "in", + "type": "httpTrigger", + "methods": [ + "get" + ], + "route": "getproductsfn" + }, + { + "name": "$return", + "type": "http", + "direction": "out" + }, + { + "name": "productfnget", + "type": "kusto", + "database": "productsdb", + "direction": "in", + "kqlCommand": "declare query_parameters (name:string);GetProductsByName(name)", + "kqlParameters": "@name={Query.name}", + "connection": "KustoConnectionString" + } + ], + "disabled": false +} +``` ++The [configuration](#configuration) section explains these properties. ++The following is sample JavaScript code: ++```javascript +module.exports = async function (context, req, producproductfngettget) { + return { + status: 200, + body: productfnget + }; +} +``` ++++More samples for the Azure Data Explorer input binding are available in the [GitHub repository](https://github.com/Azure/Webjobs.Extensions.Kusto/tree/main/samples/samples-python). ++This section contains the following examples: ++* [HTTP trigger, get multiple rows](#http-trigger-get-multiple-items-python) +* [HTTP trigger, get records using a KQL Function](#http-trigger-look-up-id-from-query-string-python) ++<a id="http-trigger-get-multiple-items-python"></a> ++### HTTP trigger, get multiple rows ++The following example shows an Azure Data Explorer input binding in a function.json file and a Python function that reads from a query and returns the results in the HTTP response. ++The following is binding data in the function.json file: ++```json +{ + "scriptFile": "__init__.py", + "bindings": [ + { + "authLevel": "Anonymous", + "type": "httpTrigger", + "direction": "in", + "name": "req", + "methods": [ + "get" + ], + "route": "getproducts/{productId}" + }, + { + "type": "http", + "direction": "out", + "name": "$return" + }, + { + "name": "productsdb", + "type": "kusto", + "database": "sdktestsdb", + "direction": "in", + "kqlCommand": "declare query_parameters (productId:long);Products | where ProductID == productId", + "kqlParameters": "@productId={Query.productId}", + "connection": "KustoConnectionString" + } + ] +} +``` ++The [configuration](#configuration) section explains these properties. ++The following is sample Python code: ++```python +import azure.functions as func +from Common.product import Product +++def main(req: func.HttpRequest, products: str) -> func.HttpResponse: + return func.HttpResponse( + products, + status_code=200, + mimetype="application/json" + ) +``` ++<a id="http-trigger-look-up-id-from-query-string-python"></a> ++### HTTP trigger, get row by ID from query string ++The following example shows a query the products table by the product name. The function is triggered by an HTTP request that uses a query string to specify the value of a query parameter. That parameter is used to filter the `Product` records in the specified query. ++The following is binding data in the function.json file: ++```json +{ + "bindings": [ + { + "authLevel": "function", + "name": "req", + "direction": "in", + "type": "httpTrigger", + "methods": [ + "get" + ], + "route": "getproductsfn" + }, + { + "name": "$return", + "type": "http", + "direction": "out" + }, + { + "name": "productfnget", + "type": "kusto", + "database": "productsdb", + "direction": "in", + "kqlCommand": "declare query_parameters (name:string);GetProductsByName(name)", + "kqlParameters": "@name={Query.name}", + "connection": "KustoConnectionString" + } + ], + "disabled": false +} +``` ++The [configuration](#configuration) section explains these properties. ++The following is sample Python code: ++```python +import azure.functions as func ++def main(req: func.HttpRequest, products: str) -> func.HttpResponse: + return func.HttpResponse( + products, + status_code=200, + mimetype="application/json" + ) +``` ++++## Attributes ++The [C# library](functions-dotnet-class-library.md) uses the [KustoAttribute](https://github.com/Azure/Webjobs.Extensions.Kusto/blob/main/src/KustoAttribute.cs) attribute to declare the Azure Data Explorer bindings on the function, which has the following properties: ++| Attribute property |Description| +||| +| **Database** | Required. The database against which the query has to be executed. | +| **Connection** | Required. The _**name**_ of the variable that holds the connection string, resolved through environment variables or through function app settings. Defaults to look up on the variable _**KustoConnectionString**_, at runtime this variable is looked up against the environment. Documentation on connection string can be found at [Kusto connection strings](/azure/data-explorer/kusto/api/connection-strings/kusto) for example:`"KustoConnectionString": "Data Source=https://_**cluster**_.kusto.windows.net;Database=_**Database**_;Fed=True;AppClientId=_**AppId**_;AppKey=_**AppKey**_;Authority Id=_**TenantId**_` | +| **KqlCommand** | Required. The KqlQuery that has to be executed. Can be a KQL query or a KQL Function call| +| **KqlParameters** | Optional. Parameters that act as predicate variables for the KqlCommand. For example "@name={name},@Id={id}" where the parameters {name} and {id} is substituted at runtime with actual values acting as predicates. Neither the parameter name nor the parameter value can contain a comma (`,`) or an equals sign (`=`). | +| **ManagedServiceIdentity** | Optional. A managed identity can be used to connect to Azure Data Explorer. To use a System managed identity, use "system", any other identity names are interpreted as user managed identity | ++++## Annotations ++In the [Java functions runtime library](/java/api/overview/azure/functions/runtime), uses the [`@KustoInput`](https://github.com/Azure/Webjobs.Extensions.Kusto/blob/main/java-library/src/main/java/com/microsoft/azure/functions/kusto/annotation/KustoInput.java) annotation (`com.microsoft.azure.functions.kusto.annotation.KustoInput`): ++| Element |Description| +||| +| **name** | Required. The name of the variable that represents the query results in function code. | +| **database** | Required. The database against which the query has to be executed. | +| **connection** | Required. The _**name**_ of the variable that holds the connection string, resolved through environment variables or through function app settings. Defaults to look up on the variable _**KustoConnectionString**_, at runtime this variable is looked up against the environment. Documentation on connection string can be found at [Kusto connection strings](/azure/data-explorer/kusto/api/connection-strings/kusto) for example:`"KustoConnectionString": "Data Source=https://_**cluster**_.kusto.windows.net;Database=_**Database**_;Fed=True;AppClientId=_**AppId**_;AppKey=_**AppKey**_;Authority Id=_**TenantId**_` | +| **kqlCommand** | Required. The KqlQuery that has to be executed. Can be a KQL query or a KQL Function call| +|**kqlParameters** | Optional. Parameters that act as \predicate variables for the KqlCommand. For example "@name={name},@Id={id}" where the parameters {name} and {id} is substituted at runtime with actual values acting as predicates. Neither the parameter name nor the parameter value can contain a comma (`,`) or an equals sign (`=`). | +| **managedServiceIdentity** | A managed identity can be used to connect to Azure Data Explorer. To use a System managed identity, use "system", any other identity names are interpreted as user managed identity| ++++## Configuration ++The following table explains the binding configuration properties that you set in the function.json file. ++|function.json property | Description| +||-| +|**type** | Required. Must be set to `kusto`. | +|**direction** | Required. Must be set to `in`. | +|**name** | Required. The name of the variable that represents the query results in function code. | +| **database** | Required. The database against which the query has to be executed. | +| **connection** | Required. The _**name**_ of the variable that holds the connection string, resolved through environment variables or through function app settings. Defaults to look up on the variable _**KustoConnectionString**_, at runtime this variable is looked up against the environment. Documentation on connection string can be found at [Kusto connection strings](/azure/data-explorer/kusto/api/connection-strings/kusto) for example:`"KustoConnectionString": "Data Source=https://_**cluster**_.kusto.windows.net;Database=_**Database**_;Fed=True;AppClientId=_**AppId**_;AppKey=_**AppKey**_;Authority Id=_**TenantId**_` | +| **kqlCommand** | Required. The KqlQuery that has to be executed. Can be a KQL query or a KQL Function call| +|**kqlParameters** | Optional. Parameters that act as predicate variables for the KqlCommand. For example "@name={name},@Id={id}" where the parameters {name} and {id} is substituted at runtime with actual values acting as predicates. Neither the parameter name nor the parameter value can contain a comma (`,`) or an equals sign (`=`). | +| **managedServiceIdentity** | A managed identity can be used to connect to Azure Data Explorer. To use a System managed identity, use "system", any other identity names are interpreted as user managed identity| +++## Usage +++The attribute's constructor takes the **Database** and the attributes **KQLCommand**, KQLParameters, and the Connection setting name. The **KQLCommand** can be a KQL statement or a KQL function. The connection string setting name corresponds to the application setting (in `local.settings.json` for local development) that contains the [Kusto connection strings](/azure/data-explorer/kusto/api/connection-strings/kusto) for example: `"KustoConnectionString": "Data Source=https://_**cluster**_.kusto.windows.net;Database=_**Database**_;Fed=True;AppClientId=_**AppId**_;AppKey=_**AppKey**_;Authority Id=_**TenantId**_`. Queries executed by the input binding are parameterized and the values provided in the KQLParameters are used at runtime. +++## Next steps ++* [Save data to a table (Output binding)](functions-bindings-azure-data-explorer-output.md) |
azure-functions | Functions Bindings Azure Data Explorer Output | https://github.com/MicrosoftDocs/azure-docs/commits/main/articles/azure-functions/functions-bindings-azure-data-explorer-output.md | + + Title: Azure Data Explorer output bindings for Azure Functions (preview) +description: Understand usage of Azure Data Explorer output bindings for Azure Functions (Ingest data to Azure Data Explorer) +++ Last updated : 05/04/2023+++zone_pivot_groups: programming-languages-set-functions-data-explorer +++# Azure Data Explorer output bindings for Azure Functions (preview) ++When a function runs, the Azure Data Explorer output binding ingests data to Azure Data Explorer. ++For information on setup and configuration details, see the [overview](functions-bindings-azure-data-explorer.md). ++## Examples ++++# [In-process](#tab/in-process) ++More samples for the Azure Data Explorer output binding are available in the [GitHub repository](https://github.com/Azure/Webjobs.Extensions.Kusto/tree/main/samples/samples-csharp). ++This section contains the following examples: ++* [HTTP trigger, write one record](#http-trigger-write-one-record-c) +* [HTTP trigger, write to two tables](#http-trigger-write-to-two-tables-c) +* [HTTP trigger, write records using IAsyncCollector](#http-trigger-write-records-using-iasynccollector-c) ++The examples refer to `Product` class and a corresponding database table: ++```cs +public class Product +{ + [JsonProperty(nameof(ProductID))] + public long ProductID { get; set; } ++ [JsonProperty(nameof(Name))] + public string Name { get; set; } ++ [JsonProperty(nameof(Cost))] + public double Cost { get; set; } +} +``` ++```kusto +.create-merge table Products (ProductID:long, Name:string, Cost:double) +``` ++<a id="http-trigger-write-one-record-c"></a> ++### HTTP trigger, write one record ++The following example shows a [C# function](functions-dotnet-class-library.md) that adds a record to a database, using data provided in an HTTP POST request as a JSON body. ++```cs +using System.Globalization; +using System.IO; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Azure.WebJobs.Extensions.Http; +using Microsoft.Azure.WebJobs.Extensions.Kusto.Samples.Common; +using Microsoft.Azure.WebJobs.Kusto; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; ++namespace Microsoft.Azure.WebJobs.Extensions.Kusto.Samples.OutputBindingSamples +{ + public static class AddProduct + { + [FunctionName("AddProductUni")] + public static IActionResult Run( + [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "addproductuni")] + HttpRequest req, ILogger log, + [Kusto(Database:"productsdb" , + TableName ="Products" , + Connection = "KustoConnectionString")] out Product product) + { + log.LogInformation($"AddProduct function started"); + string body = new StreamReader(req.Body).ReadToEnd(); + product = JsonConvert.DeserializeObject<Product>(body); + return new CreatedResult($"/api/addproductuni", product); + } + } +} +``` ++<a id="http-trigger-write-to-two-tables-c"></a> ++### HTTP trigger, write to two tables ++The following example shows a [C# function](functions-dotnet-class-library.md) that adds records to a database in two different tables (`Products` and `ProductsChangeLog`), using data provided in an HTTP POST request as a JSON body and multiple output bindings. ++```kusto +.create-merge table ProductsChangeLog (ProductID:long, CreatedAt:datetime) +``` ++```cs +using System; +using Newtonsoft.Json; ++namespace Microsoft.Azure.WebJobs.Extensions.Kusto.Samples.Common +{ + public class ProductsChangeLog + { + [JsonProperty(nameof(ProductID))] + public long ProductID { get; set; } ++ [JsonProperty(nameof(CreatedAt))] + public DateTime CreatedAt { get; set; } ++ } +} +``` ++```cs +using System; +using System.IO; +using Kusto.Cloud.Platform.Utils; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Azure.WebJobs.Extensions.Http; +using Microsoft.Azure.WebJobs.Extensions.Kusto.Samples.Common; +using Microsoft.Azure.WebJobs.Kusto; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; ++namespace Microsoft.Azure.WebJobs.Extensions.Kusto.Samples.OutputBindingSamples +{ + public static class AddMultiTable + { + [FunctionName("AddMultiTable")] + public static IActionResult Run( + [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "addmulti")] + HttpRequest req, ILogger log, + [Kusto(Database:"productsdb" , + TableName ="Products" , + Connection = "KustoConnectionString")] IAsyncCollector<Product> productsCollector, + [Kusto(Database:"productsdb" , + TableName =S"ProductsChangeLog" , + Connection = "KustoConnectionString")] IAsyncCollector<ProductsChangeLog> changeCollector) + { + log.LogInformation($"AddProducts function started"); + string body = new StreamReader(req.Body).ReadToEnd(); + Product[] products = JsonConvert.DeserializeObject<Product[]>(body); + products.ForEach(p => + { + productsCollector.AddAsync(p); + changeCollector.AddAsync(new ProductsChangeLog { CreatedAt = DateTime.UtcNow, ProductID = p.ProductID }); + }); + productsCollector.FlushAsync(); + changeCollector.FlushAsync(); + return products != null ? new ObjectResult(products) { StatusCode = StatusCodes.Status201Created } : new BadRequestObjectResult("Please pass a well formed JSON Product array in the body"); + } + } +} +``` ++<a id="http-trigger-write-records-using-iasynccollector-c"></a> ++### HTTP trigger, write records using IAsyncCollector ++The following example shows a [C# function](functions-dotnet-class-library.md) that ingests a set of records to a table, using data provided in an HTTP POST body JSON array. ++```cs +using System.IO; +using Kusto.Cloud.Platform.Utils; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Azure.WebJobs.Extensions.Http; +using Microsoft.Azure.WebJobs.Extensions.Kusto.Samples.Common; +using Microsoft.Azure.WebJobs.Kusto; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; ++namespace Microsoft.Azure.WebJobs.Extensions.Kusto.Samples.OutputBindingSamples +{ + public static class AddProductsAsyncCollector + { + [FunctionName("AddProductsAsyncCollector")] + public static IActionResult Run( + [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "addproductsasynccollector")] + HttpRequest req, ILogger log, + [Kusto(Database:"productsdb" , + TableName ="Products" , + Connection = "KustoConnectionString")] IAsyncCollector<Product> collector) + { + log.LogInformation($"AddProductsAsyncCollector function started"); + string body = new StreamReader(req.Body).ReadToEnd(); + Product[] products = JsonConvert.DeserializeObject<Product[]>(body); + products.ForEach(p => + { + collector.AddAsync(p); + }); + collector.FlushAsync(); + return products != null ? new ObjectResult(products) { StatusCode = StatusCodes.Status201Created } : new BadRequestObjectResult("Please pass a well formed JSON Product array in the body"); + } + } +} +``` ++# [Isolated process](#tab/isolated-process) ++More samples for the Azure Data Explorer output binding are available in the [GitHub repository](https://github.com/Azure/Webjobs.Extensions.Kusto/tree/main/samples/samples-outofproc). ++This section contains the following examples: ++* [HTTP trigger, write one record](#http-trigger-write-one-record-c-oop) +* [HTTP trigger, write records with mapping](#http-trigger-write-records-with-mapping-oop) ++The examples refer to `Product` class and a corresponding database table: ++```cs +public class Product +{ + [JsonProperty(nameof(ProductID))] + public long ProductID { get; set; } ++ [JsonProperty(nameof(Name))] + public string Name { get; set; } ++ [JsonProperty(nameof(Cost))] + public double Cost { get; set; } +} +``` ++```kusto +.create-merge table Products (ProductID:long, Name:string, Cost:double) +``` ++<a id="http-trigger-write-one-record-c-oop"></a> ++### HTTP trigger, write one record ++The following example shows a [C# function](functions-dotnet-class-library.md) that adds a record to a database, using data provided in an HTTP POST request as a JSON body. ++```cs +using Microsoft.Azure.Functions.Worker; +using Microsoft.Azure.Functions.Worker.Extensions.Kusto; +using Microsoft.Azure.Functions.Worker.Http; +using Microsoft.Azure.WebJobs.Extensions.Kusto.SamplesOutOfProc.OutputBindingSamples.Common; ++namespace Microsoft.Azure.WebJobs.Extensions.Kusto.SamplesOutOfProc.OutputBindingSamples +{ + public static class AddProduct + { + [Function("AddProduct")] + [KustoOutput(Database: "productsdb", Connection = "KustoConnectionString", TableName = "Products")] + public static async Task<Product> Run( + [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "addproductuni")] + HttpRequestData req) + { + Product? prod = await req.ReadFromJsonAsync<Product>(); + return prod ?? new Product { }; + } + } +} ++``` ++<a id="http-trigger-write-records-with-mapping-oop"></a> ++### HTTP trigger, write records with mapping ++The following example shows a [C# function](functions-dotnet-class-library.md) that adds a collection of records to a database, using a mapping that transforms a `Product` to `Item`. ++To transform data from `Product` to `Item`, the function uses a mapping reference ++```kusto +.create-merge table Item (ItemID:long, ItemName:string, ItemCost:float) +++-- Create a mapping that transforms an Item to a Product ++.create-or-alter table Product ingestion json mapping "item_to_product_json" '[{"column":"ProductID","path":"$.ItemID"},{"column":"Name","path":"$.ItemName"},{"column":"Cost","path":"$.ItemCost"}]' +``` ++```cs +namespace Microsoft.Azure.WebJobs.Extensions.Kusto.SamplesOutOfProc.OutputBindingSamples.Common +{ + public class Item + { + public long ItemID { get; set; } ++ public string? ItemName { get; set; } ++ public double ItemCost { get; set; } + } +} +``` ++```cs +using Microsoft.Azure.Functions.Worker; +using Microsoft.Azure.Functions.Worker.Extensions.Kusto; +using Microsoft.Azure.Functions.Worker.Http; +using Microsoft.Azure.WebJobs.Extensions.Kusto.SamplesOutOfProc.OutputBindingSamples.Common; ++namespace Microsoft.Azure.WebJobs.Extensions.Kusto.SamplesOutOfProc.OutputBindingSamples +{ + public static class AddProductsWithMapping + { + [Function("AddProductsWithMapping")] + [KustoOutput(Database: "productsdb", Connection = "KustoConnectionString", TableName = "Products", MappingRef = "item_to_product_json")] + public static async Task<Item> Run( + [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "addproductswithmapping")] + HttpRequestData req) + { + Item? item = await req.ReadFromJsonAsync<Item>(); + return item ?? new Item { }; + } + } +} +``` ++++More samples for the java Azure Data Explorer input binding are available in the [GitHub repository](https://github.com/Azure/Webjobs.Extensions.Kusto/tree/main/samples/samples-java). ++This section contains the following examples: ++* [HTTP trigger, write a record to a table](#http-trigger-write-record-to-table-java) +* [HTTP trigger, write to two tables](#http-trigger-write-to-two-tables-java) ++The examples refer to a `Products` class (in a separate file `Product.java`) and a corresponding database table `Products` (defined earlier): ++```java +package com.microsoft.azure.kusto.common; ++import com.fasterxml.jackson.annotation.JsonProperty; ++public class Product { + @JsonProperty("ProductID") + public long ProductID; + @JsonProperty("Name") + public String Name; + @JsonProperty("Cost") + public double Cost; ++ public Product() { + } ++ public Product(long Pro |