Tuesday, July 18, 2017

Adding Azure Active Directory OAuth 2.0 authentication to a Service Fabric Web API (Stateless) service

... is pretty much the same as adding it to a normal Web API 2.0 application:

[Authorize]
public class ValuesController : ApiController
{
        }

Then in your Startup.cs file:

// This code configures Web API. The Startup class is specified as a type
// parameter in the WebApp.Start method.
public static void ConfigureApp(IAppBuilder appBuilder)
{
CodePackageActivationContext activationContext = FabricRuntime.GetActivationContext();
ConfigurationPackage configurationPackageObject = activationContext.GetConfigurationPackageObject("Config");

ConfigurationSection configurationSection = configurationPackageObject.Settings.Sections["ActiveDirectoryServiceConfigSection"];

appBuilder.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = configurationSection.Parameters["TenantName"].Value,
TokenValidationParameters = new TokenValidationParameters
{
ValidAudience = configurationSection.Parameters["AppIdUri"].Value
},
Provider = new OAuthBearerAuthenticationProvider
{
OnValidateIdentity = OnValidateUserIdentityAsync
}
});

// Configure Web API for self-host. 
HttpConfiguration config = new HttpConfiguration();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

appBuilder.UseWebApi(config);
}

The trick here is to ** ENSURE THAT WAAD BEARER AUTHENTICATION GETS REGISTERED BEFORE REGISTERING WEB API!!! **

No comments:

Post a Comment