Azure托管应用调用内网WCF服务及AD身份认证配置问询
Alright, let's break down your problem into two key parts: first, enabling your Azure-hosted app to access on-premises WCF services, and second, configuring WCF security to pass Azure AD credentials through and validate against your local Active Directory. Here's a step-by-step breakdown:
You have three reliable options to bridge the gap between Azure and your internal network:
Site-to-Site VPN with Azure VPN Gateway
This creates a secure, persistent tunnel between your Azure virtual network and your corporate on-prem network. Once set up, your Azure app can reach WCF services using their internal private IPs or domain names just like any on-prem machine.
Steps: Create an Azure VPN Gateway, configure your on-prem VPN device to connect to it, and ensure routing is set up to allow traffic between Azure VNet and your internal subnet.Azure Application Proxy
If you don't want to expose your entire network, use Application Proxy to publish individual WCF services as secure, cloud-accessible endpoints. It handles authentication and traffic routing without needing a full VPN.
Plus, it integrates natively with Azure AD, making it easy to restrict access to only your authenticated Azure app.Azure Arc for Servers
If your WCF servers are registered with Azure Arc, you can use Arc's private link capabilities to create a secure connection between Azure and your on-prem servers. This is great if you already manage on-prem infrastructure via Azure Arc.
To pass Azure AD tokens to WCF and map them to local AD users, follow these steps:
1. Register WCF Service in Azure AD
First, register your WCF service as an Azure AD application (or enterprise app):
- Define a unique
Application ID URI(e.g.,api://your-wcf-service-id) and add scopes (likeaccess_as_user) for authorization. - Grant your Azure app permission to access this WCF service's scope in Azure AD's API permissions section.
2. Configure WCF Service for Token Validation
Update your WCF service's web.config to accept and validate Azure AD JWT tokens:
<bindings> <wsHttpBinding> <binding name="AzureAdSecuredBinding"> <security mode="TransportWithMessageCredential"> <message clientCredentialType="IssuedToken" /> </security> </binding> </wsHttpBinding> </bindings> <behaviors> <serviceBehaviors> <behavior name="SecureWcfBehavior"> <serviceCredentials> <issuedTokenAuthentication> <issuerRegistry type="Microsoft.IdentityModel.Tokens.ConfigurationBasedIssuerRegistry, Microsoft.IdentityModel.Tokens"> <trustedIssuers> <!-- Add your Azure AD tenant's signing certificate thumbprint and issuer URL --> <add thumbprint="YOUR_AZURE_AD_SIGNING_THUMBPRINT" name="https://login.microsoftonline.com/YOUR_TENANT_ID/v2.0" /> </trustedIssuers> </issuerRegistry> </issuedTokenAuthentication> </serviceCredentials> <serviceMetadata httpGetEnabled="true" /> </behavior> </serviceBehaviors> </behaviors> <services> <service name="YourNamespace.YourWcfService" behaviorConfiguration="SecureWcfBehavior"> <endpoint address="" binding="wsHttpBinding" bindingConfiguration="AzureAdSecuredBinding" contract="YourNamespace.IYourWcfService" /> </service> </services>
3. Modify Azure App to Fetch and Pass Azure AD Tokens
In your Azure app's code, fetch an access token for the WCF service and attach it to the WCF client call:
using Azure.Identity; using System.ServiceModel; using System.IdentityModel.Tokens.Jwt; // Fetch Azure AD token for the WCF service var scopes = new[] { "api://your-wcf-service-id/access_as_user" }; var credential = new DefaultAzureCredential(); var tokenResult = await credential.GetTokenAsync(new TokenRequestContext(scopes)); // Initialize WCF client and attach the token var client = new YourWcfServiceClient(); var jwtToken = new JwtSecurityToken(tokenResult.Token); var tokenParam = new System.ServiceModel.Security.Tokens.SecurityTokenParameter(jwtToken); var channel = client.ChannelFactory.CreateChannelWithIssuedToken(tokenParam); var result = await channel.YourServiceMethodAsync();
4. Map Azure AD Tokens to Local AD Users
Once the WCF service validates the token, extract the user's UPN (User Principal Name) from the token and map it to a local AD user. Use the System.DirectoryServices.AccountManagement library to query your local AD:
using System.Security.Claims; using System.DirectoryServices.AccountManagement; using System.ServiceModel; public string YourServiceMethod() { // Extract UPN from the Azure AD token var upnClaim = OperationContext.Current.ServiceSecurityContext.AuthorizationContext.ClaimsIdentity.FindFirst(ClaimTypes.Upn); if (upnClaim == null) throw new SecurityException("UPN claim not found in token"); var userUpn = upnClaim.Value; // Query local AD for the user using (var domainContext = new PrincipalContext(ContextType.Domain, "YOUR_LOCAL_AD_DOMAIN")) { var localUser = UserPrincipal.FindByIdentity(domainContext, userUpn); if (localUser == null) throw new SecurityException("User not found in local AD"); // Optional: Impersonate the local AD user to perform actions with their permissions using (WindowsIdentity.Impersonate(localUser.UserPrincipalSid.Value)) { return $"Hello, {localUser.DisplayName} (authenticated via Azure AD and mapped to local AD)"; } } }
Key Notes:
- Ensure your Azure AD and local AD are synced via Azure AD Connect so user UPNs match across both directories.
- For WCF services published via Application Proxy, enable Azure AD pre-authentication to block unauthenticated requests before they reach your on-prem network.
- Keep Azure AD's signing certificates updated in your WCF config to avoid validation failures.
内容的提问来源于stack exchange,提问作者pierreshiny

