An Interest In:
Web News this Week
- April 12, 2024
- April 11, 2024
- April 10, 2024
- April 9, 2024
- April 8, 2024
- April 7, 2024
- April 6, 2024
April 18, 2022 01:36 pm GMT
Original Link: https://dev.to/koheikawata/azure-api-management-authentication-part2-pd9
Azure API Management authentication - Part.2
Summary
Following the article Part.1, I would share how Azure API Management authentication works. The sample code includes three types of authentication APIs - Azure AD, Basic Auth, Client Certificate and two patterns of API Management Gateway validation. In Part.2, I would talk about the Gateway Validation pattern.
TOC
- Architecture
- Gateway validation
- Configuraiton - Azure AD token validation
- Configuraiton - Basic auth validation
- Configuration - Client certificate validation
- Sample request
Architecture
As mentioned in Part.1, the APIs that have different types of authentication are behind API Management.
Gateway validation
- API Management Gateway validates each type of credential, Azure AD token, Basic Authentication username and password, and Client certificate.
- For Azure AD and Basic Authentication, the credentials attached on the request header are passed through the gateway to the backend.
- For Client Certificate Authentication, it is difficult to pass through to the backend. Once a client certificate is validated at the API Management Gateway, another client certificate is retrieved from Azure Key Vault and attached to the backend request.
Configuraiton - Azure AD token validation
- It uses
<validate-jwt>
and sees if the header includes the right claims. - It checks
aud
andappid
claims.
Policy example
Named values | Comments |
---|---|
aadTenantId | Azure AD tenant ID |
backendAppId | Azure AD application ID of client app |
clientAppId | Azure AD applicaiton ID of backend app |
<policies> <inbound> <base /> <validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized. Access token is missing or invalid."> <openid-config url="https://login.microsoftonline.com/{{aadTenantId}}/.well-known/openid-configuration" /> <audiences> <audience>api://{{backendAppId}}</audience> </audiences> <required-claims> <claim name="appid" match="all"> <value>{{clientAppId}}</value> </claim> </required-claims> </validate-jwt> </inbound> <backend> <base /> </backend> <outbound> <base /> </outbound> <on-error> <base /> </on-error></policies>
- In Bicep deployment, the Policy depends on Named Values. It uses
dependsOn
to specify the deployment order.
resource ApiManagementPolicyAzureAd 'Microsoft.ApiManagement/service/apis/policies@2021-08-01' = { name: '${ApiManagementApiAzureAd.name}/policy' dependsOn: [ ApiManagementNamedValueClientAppId ApiManagementNamedValueBackendAppId ApiManagementNamedValueAadTenantId ] properties: { value: '<policies>\r
<inbound>\r
<base />\r
<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized. Access token is missing or invalid.">\r
<openid-config url="${environment().authentication.loginEndpoint}{{${apim_nv_aadtenantid}}}/.well-known/openid-configuration" />\r
<audiences>\r
<audience>api://{{${apim_nv_backendappid}}}</audience>\r
</audiences>\r
<required-claims>\r
<claim name="appid" match="all">\r
<value>{{${apim_nv_clientappid}}}</value>\r
</claim>\r
</required-claims>\r
</validate-jwt>\r
</inbound>\r
<backend>\r
<base />\r
</backend>\r
<outbound>\r
<base />\r
</outbound>\r
<on-error>\r
<base />\r
</on-error>\r
</policies>' format: 'xml' }}resource ApiManagementNamedValueClientAppId 'Microsoft.ApiManagement/service/namedValues@2021-08-01' = { name: '${ApiManagement.name}/${apim_nv_clientappid}' properties: { displayName: apim_nv_clientappid value: aad_appid_client }}resource ApiManagementNamedValueBackendAppId 'Microsoft.ApiManagement/service/namedValues@2021-08-01' = { name: '${ApiManagement.name}/${apim_nv_backendappid}' properties: { displayName: apim_nv_backendappid value: aad_appid_backend }}resource ApiManagementNamedValueAadTenantId 'Microsoft.ApiManagement/service/namedValues@2021-08-01' = { name: '${ApiManagement.name}/${apim_nv_aadtenantid}' properties: { displayName: apim_nv_aadtenantid value: aad_tenantid }}
Configuraiton - Basic auth validation
- API Management Gateway validates if an username and password on the request header is identical with those which registered as Named Values in API Management. The password is stored in Azure Key Vault and API Management refers to it.
Policy example
Named values | Comments |
---|---|
basicAuthUserName | Username for Basic Authentication |
basicAuthPass | Password for Basic Authentication |
<policies> <inbound> <base /> <set-variable name="user-pass" value="{{basicAuthUserName}}:{{basicAuthPass}}" /> <check-header name="Authorization" failed-check-httpcode="401" failed-check-error-message="Not authorized" ignore-case="false"> <value>@("Basic " + System.Convert.ToBase64String(Encoding.UTF8.GetBytes((string)context.Variables["user-pass"])))</value> </check-header> </inbound> <backend> <base /> </backend> <outbound> <base /> </outbound> <on-error> <base /> </on-error></policies>
- In Bicep deployment, the Policy depends on the Named Values registered in API Management. It uses
dependsOn
to specify the deployment order.
resource ApiManagementPolicyBasic 'Microsoft.ApiManagement/service/apis/policies@2021-08-01' = { name: '${ApiManagementApiBasic.name}/policy' dependsOn: [ ApiManagementNamedValueBasicAuthName ApiManagementNamedValueBasicAuthPass ] properties: { value: '<policies>\r
<inbound>\r
<base />\r
<set-variable name="user-pass" value="{{${apim_nv_basicauthuser}}}:{{${apim_nv_basicauthpass}}}" />\r
<check-header name="Authorization" failed-check-httpcode="401" failed-check-error-message="Not authorized" ignore-case="false">\r
<value>@("Basic " + System.Convert.ToBase64String(Encoding.UTF8.GetBytes((string)context.Variables["user-pass"])))</value>\r
</check-header>\r
</inbound>\r
<backend>\r
<base />\r
</backend>\r
<outbound>\r
<base />\r
</outbound>\r
<on-error>\r
<base />\r
</on-error>\r
</policies>' format: 'xml' }}resource ApiManagementNamedValueBasicAuthName 'Microsoft.ApiManagement/service/namedValues@2021-08-01' = { name: '${ApiManagement.name}/${apim_nv_basicauthuser}' properties: { displayName: apim_nv_basicauthuser value: basic_auth_user }}resource ApiManagementNamedValueBasicAuthPass 'Microsoft.ApiManagement/service/namedValues@2021-08-01' = { name: '${ApiManagement.name}/${apim_nv_basicauthpass}' dependsOn: [ KeyVaultAccessPolicies ] properties: { displayName: apim_nv_basicauthpass keyVault: { secretIdentifier: 'https://${kv_name}${environment().suffixes.keyvaultDns}/secrets/${kvsecret_name_basic_pass}' } secret: true }}
Configuration - Client certificate validation
- It requires to configure
negotiateClientCertificate: true
so API Management accepts a client certificate during TLS handshake. Without it, the Policy does not work for client certificate authentication. negotiateClientCertificate: true
should be configured for other request patterns without a client certificate because it wokrs well too. If you turn true/false back and forth, it takes an half hour or more to change the API Management configuration.- It uses
<validate-client-certificate>
policy and validates the thumbprint stored in Azure Key Vault. validate-trust
should turn tofalse
for a self-signed certificate to work.<authentication-certificate certificate-id="apicert" />
is needed to send a backend request with a certificate.
properties: { hostnameConfigurations: [ { type: 'Proxy' hostName: '${apim_name}.azure-api.net' negotiateClientCertificate: true } ]}
Policy example
Named values | Comments |
---|---|
certificateThumbprint | Thumbprint of Certificate uploaded |
<policies> <inbound> <base /> <validate-client-certificate validate-revocation="true" validate-trust="false" validate-not-before="true" validate-not-after="true" ignore-error="false"> <identities> <identity thumbprint="{{certificateThumbprint}}" /> </identities> </validate-client-certificate> <authentication-certificate certificate-id="apicert" /> </inbound> <backend> <base /> </backend> <outbound> <base /> </outbound> <on-error> <base /> </on-error></policies>
- Another policy pattern works too like below
<choose> <when condition="@(context.Request.Certificate == null || context.Request.Certificate.Thumbprint != "{Thumbprint uploaded in Key Vault}")"> <return-response> <set-status code="403" reason="Invalid client certificate" /> </return-response> </when></choose>
- In bicep deployment, the Policy depends on the Certificate registered in API Management. Use dependsOn to specify the deployment order.
- The policy points to apim_certificate_id which is Certificate ID in API Management.
- In bicep deployment, the API Management needs an AccessPolicies of the Key Vault. And the deployment order should be Key Vault Access Policy, Certificate, and Policy.
resource ApiManagementPolicyCert 'Microsoft.ApiManagement/service/apis/policies@2021-08-01' = { name: '${ApiManagementApiCert.name}/policy' dependsOn: [ ApiManagementNamedValueThumbprint ApiManagementCertificate ] properties: { value: '<policies>\r
<inbound>\r
<base />\r
<validate-client-certificate validate-revocation="true" validate-trust="false" validate-not-before="true" validate-not-after="true" ignore-error="false">\r
<identities>\r
<identity thumbprint="{{${apim_nv_thumbprint}}}" />\r
</identities>\r
</validate-client-certificate>\r
<authentication-certificate certificate-id="${apim_certificate_id}" />\r
</inbound>\r
<backend>\r
<base />\r
</backend>\r
<outbound>\r
<base />\r
</outbound>\r
<on-error>\r
<base />\r
</on-error>\r
</policies>' format: 'xml' }}resource ApiManagementNamedValueThumbprint 'Microsoft.ApiManagement/service/namedValues@2021-08-01' = { name: '${ApiManagement.name}/${apim_nv_thumbprint}' dependsOn: [ KeyVaultAccessPolicies ] properties: { displayName: apim_nv_thumbprint keyVault: { secretIdentifier: 'https://${kv_name}${environment().suffixes.keyvaultDns}/secrets/${kvsecret_name_cert_thumbprint}' } secret: true }}resource ApiManagementCertificate 'Microsoft.ApiManagement/service/certificates@2021-08-01' = { name: '${ApiManagement.name}/${apim_certificate_id}' dependsOn: [ KeyVaultAccessPolicies ] properties: { keyVault: { secretIdentifier: 'https://${kv_name}${environment().suffixes.keyvaultDns}/secrets/${kvcert_name_api}' } }}
Sample request
Powershell for AzureAdAuthAPI
$clientSecret = "{Azure AD client app secret}"$authorizeUri = "https://login.microsoftonline.com/{Azure AD tenant ID}/oauth2/v2.0/token"$body = 'grant_type=client_credentials' + `'&client_id={Azure AD client app ID}' + `'&client_secret=' + $clientSecret + `'&scope=api://{Azure AD backend app ID}/.default'$token = (Invoke-RestMethod -Method Post -Uri $authorizeUri -Body $body).access_token$Uri = "https://{API Management name}.azure-api.net/AzureAdAuth/Weatherforecast/RequireAuth"$headers = @{ "Authorization" = 'Bearer ' + $token}Invoke-RestMethod -Uri $Uri -Method Get -Headers $headers
Powershell for BasicAuthAPI
$basicAuthUsername = "{Basic Authenticaiton user}"$basicAuthSecret = "{Basic Authenticaiton password}"$bytes = [System.Text.Encoding]::ASCII.GetBytes($basicAuthUsername + ':' + $basicAuthSecret)$authHeader = [Convert]::ToBase64String($bytes)$Uri = "https://{API Management name}.azure-api.net/BasicAuth/Weatherforecast/RequireAuth"$headers = @{ "Authorization" = 'Basic ' + $authHeader}Invoke-RestMethod -Uri $Uri -Method Get -Headers $headers
Powershell for CertificateAuthAPI
$parameters = @{ Method = "GET" Uri = "https://{API Management name}.azure-api.net/CertificateAuth/Weatherforecast/RequireAuth" Certificate = (Get-PfxCertificate "{PFX file path}")}Invoke-RestMethod @parameters
Original Link: https://dev.to/koheikawata/azure-api-management-authentication-part2-pd9
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To