Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authenticating as a Service with Azure AD B2C

We have setup our application using Azure AD B2C and OAuth, this works fine, however I am trying to authenticate as a service in order to make service to service calls. I am slightly new to this, but I have followed some courses on Pluralsight on how to do this on "normal" Azure Active Directory and I can get it to work, but following the same principles with B2C does not work.

I have this quick console app:

class Program
{
    private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"]; //APIClient ApplicationId
    private static string appKey = ConfigurationManager.AppSettings["ida:appKey"]; //APIClient Secret
    private static string aadInstance = ConfigurationManager.AppSettings["ida:aadInstance"]; //https://login.microsoftonline.com/{0}
    private static string tenant = ConfigurationManager.AppSettings["ida:tenant"]; //B2C Tenant 
    private static string serviceResourceId = ConfigurationManager.AppSettings["ida:serviceResourceID"]; //APP Id URI For API
    private static string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);

    private static AuthenticationContext authContext = new AuthenticationContext(authority);
    private static ClientCredential clientCredential = new ClientCredential(clientId, appKey);

    static void Main(string[] args)
    {
        AuthenticationResult result = authContext.AcquireToken(serviceResourceId, clientCredential);
        Console.WriteLine("Authenticated succesfully.. making HTTPS call..");

        string serviceBaseAddress = "https://localhost:44300/";
        HttpClient httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
        HttpResponseMessage response = httpClient.GetAsync(serviceBaseAddress + "api/location?cityName=dc").Result;

        if (response.IsSuccessStatusCode)
        {
            string r = response.Content.ReadAsStringAsync().Result;
            Console.WriteLine(r);
        }
    }
}

And the service is secured like this:

    private void ConfigureAuth(IAppBuilder app)
    {
        var azureADBearerAuthOptions = new WindowsAzureActiveDirectoryBearerAuthenticationOptions
        {
            Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
            TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters()
            {
                ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
            }
        };

        app.UseWindowsAzureActiveDirectoryBearerAuthentication(azureADBearerAuthOptions);
    }

In my B2C tenant I have two different applications that are pretty much setup as this:

Azure B2C app setup Both applications have been setup with secrets coming from the "keys" option. The keys generated are slightly differently structured than when using Azure Active Directory.

I can successfully get a token, but I get 401 when trying to connect to the other service. Do I have to do something different on the authorization side when using B2C compared to Azure Active Directory?

like image 704
ruffen Avatar asked Oct 31 '17 12:10

ruffen


People also ask

How does Azure B2C authentication work?

Azure AD B2C provides various ways in which users can authenticate a user. Users can sign-in to a local account, by using username and password, phone verification (also known as password-less authentication). Email sign-up is enabled by default in your local account identity provider settings.

Does Azure B2C support MFA?

Azure Active Directory B2C (Azure AD B2C) integrates directly with Azure AD Multi-Factor Authentication so that you can add a second layer of security to sign-up and sign-in experiences in your applications. You enable multifactor authentication without writing a single line of code.

How do I authenticate Azure App Service?

In Overview, select your app's management page. On your app's left menu, select Authentication, and then click Add identity provider. In the Add an identity provider page, select Microsoft as the Identity provider to sign in Microsoft and Azure AD identities.


2 Answers

Azure Active Directory B2C can issue access tokens for access by a web or native app to an API app if:

  1. Both of these apps are registered with B2C; and
  2. The access token is issued as result of an interactive user flow (i.e. the authorization code or implicit flows).

Currently, your specific scenario -- where you are needing an access token to be issued for access by a daemon or server app to the API app (i.e. the client credentials flow) -- isn't supported, however you can register both of these apps through the “App Registrations” blade for the B2C tenant.

You can upvote support for the client credentials flow by B2C at:

https://feedback.azure.com/forums/169401-azure-active-directory/suggestions/18529918-aadb2c-support-oauth-2-0-client-credential-flow

If the API app is to receive tokens from both the web/native app as well as the daemon/server app, then you will have to configure the API app to validate tokens from two token issuers: one being B2C and other being the Azure AD directory in your B2C tenant.

like image 64
Chris Padgett Avatar answered Sep 18 '22 16:09

Chris Padgett


I found the following very clear article from Microsoft which explains how to set up a "service account" / application which has management access to a B2C tenant. For me, that was the use case for which I wanted to "Authenticating as a Service with Azure AD B2C".

It is possible that having management access to a B2C tenant doesn't allow you access a protected resource for which your B2C tenant is the Authorization server (I haven't tried that), so the OP's use case may be slightly different but it feels very close.

https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-devquickstarts-graph-dotnet

For automated, continuous tasks, you should use some type of service account that you provide with the necessary privileges to perform management tasks. In Azure AD, you can do this by registering an application and authenticating to Azure AD. This is done by using an Application ID that uses the OAuth 2.0 client credentials grant. In this case, the application acts as itself, not as a user, to call the Graph API. In this article, we'll discuss how to perform the automated-use case. To demonstrate, we'll build a .NET 4.5 B2CGraphClient that performs user create, read, update, and delete (CRUD) operations. The client will have a Windows command-line interface (CLI) that allows you to invoke various methods. However, the code is written to behave in a noninteractive, automated fashion.

like image 22
ubienewbie Avatar answered Sep 20 '22 16:09

ubienewbie