Ask Learn
Preview
Ask Learn is an AI assistant that can answer questions, clarify concepts, and define terms using trusted Microsoft documentation.
Please sign in to use Ask Learn.
Sign inThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
I came across one of the requirements, where my customer requested me to create a sample ASP.NET WEB API application, and later be consumed by a rich desktop client like WPF. It had one OAuth 2.0 protocol authorization rider before accessing the WEB API resource. And, the OAuth 2.0 access token must be retrieved from an On-Premise ADFS authorization server.
OAuth 2.0 authorization protocol is supported from ADFS 2012 and beyond.
Create Web API application
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="ida:AdfsMetadataEndpoint" value="https://adfs.contoso.com/federationmetadata/2007-06/federationmetadata.xml" />
<add key="ida:Audience" value="https://win7.contoso.com/MyWebAPIsample/" />
</appSettings>
using Owin;
namespace MyWebAPIsample
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IdentityModel.Tokens;
using System.Linq;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.ActiveDirectory;
using Owin;
namespace MyWebAPIsample
{
public partial class Startup
{
// For more information on configuring authentication, please visit go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
app. UseActiveDirectoryFederationServicesBearerAuthentication (
new ActiveDirectoryFederationServicesBearerAuthenticationOptions
{
MetadataEndpoint = ConfigurationManager.AppSettings["ida:AdfsMetadataEndpoint"],
TokenValidationParameters = new TokenValidationParameters() {
ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
}
});
}
}
}
using System.Web.Http;
namespace MyWebAPIsample.Controllers
{
[Authorize]
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
...
Host the WEB API application on IIS
ADFS provisioning for Web API application
Add-ADFSRelyingPartyTrust -Name WIN7.MyWebAPIsample -Identifier https://win7.contoso.com/MyWebAPIsample/ -IssuanceAuthorizationRules '=> issue(Type = "schemas.microsoft.com/authorization/claims/permit", Value = "true");' -IssuanceTransformRules 'c:[Type == "schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"] => issue(claim = c);'
Add-ADFSClient -Name "WIN7.MyWebAPIsample.Client" -ClientId "09c9a8a2-6bf1-427d-89ba-45c2c02bb9fc" -RedirectUri "anarbitraryreturnuri/"
Note
The ADFS provisioning commands are different for ADFS server 2016. The PowerShell commands such as Add-AdfsRelyingPartyTrust and Add-AdfsClient should map to Add-AdfsWebApiApplication and Add-AdfsNativeClientApplication respectively in ADFS 2016. The documentation /en-us/windows-server/identity/ad-fs/overview/ad-fs-scenarios-for-developers has more details on this.
Consume the Web API on rich client
<Grid> <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="124,78,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/> </Grid>
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Net.Http;
private async void button_Click(object sender, RoutedEventArgs e)
{
string authority = "https://adfs.contoso.com/adfs";
string resourceURI = "https://win7.contoso.com/MyWebAPIsample/";
string clientID = "09c9a8a2-6bf1-427d-89ba-45c2c02bb9fc";
string clientReturnURI = "anarbitraryreturnuri/";
var authContext = new AuthenticationContext(authority, false);
var authResult = await authContext.AcquireTokenAsync(resourceURI, clientID, new Uri(clientReturnURI), new PlatformParameters(PromptBehavior.Auto));
string authHeader = authResult.CreateAuthorizationHeader();
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, "https://win7.contoso.com/MyWebAPIsample/api/values");
request.Headers.TryAddWithoutValidation("Authorization", authHeader);
var response = await client.SendAsync(request);
string responseString = await response.Content.ReadAsStringAsync();
MessageBox.Show(responseString);
}
Debug and run the rich client
References
Note:
Happy Programming!!!
Ask Learn is an AI assistant that can answer questions, clarify concepts, and define terms using trusted Microsoft documentation.
Please sign in to use Ask Learn.
Sign in