0

My scenario is like I've to deploy the Web API(.NET Framework) in Azure Web App and all the requests should go via Azure AD Authentication. I googled and found similar case provided by Microsoft. I have followed the below sample provided by Microsoft and when I tested this code in machine it is working fine.

Native client to Web API to Web API.

In my case, I am able to generate the OAuth2 token but the problem is I'm always getting 401 Unauthorized error. I have followed many blogs but not able to figure out what is causing the problem. Any help is really appreciated.

Here my code is:

Startup.cs

    public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
    }
}

Startup.Auth.cs

        public void ConfigureAuth(IAppBuilder app)
    {
        app.UseWindowsAzureActiveDirectoryBearerAuthentication(
            new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
                TokenValidationParameters = new TokenValidationParameters { ValidAudience = ConfigurationManager.AppSettings["ida:Audience"] }
            });
    }

Controller.cs

[Authorize]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class AuthController : ApiController
{
    [HttpGet]
    public HttpResponseMessage Get()
    {
        try
        {
            using (sqldbEntities entities = new sqldbEntities())
            {
                return Request.CreateResponse(HttpStatusCode.OK, (ConfigurationManager.AppSettings["GetMethod"]));
            }
        }
        catch (Exception ex)
        {
            Log4net.log.Error(string.Format(ConfigurationManager.AppSettings["ErrorGetData"], ex.Message));
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
        }
    }

Generating the token in two ways: Method 1) From another ASP.NET application

private static AuthenticationContext authContext = null;
        private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
        private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
        private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
        Uri redirectUri = new Uri(ConfigurationManager.AppSettings["ida:RedirectUri"]);

        private static string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
        private static string todoListResourceId = ConfigurationManager.AppSettings["todo:TodoListResourceId"];            

protected async void Button1_Click(object sender, EventArgs e)
        {
            authContext = new AuthenticationContext(authority);
            AuthenticationResult result = null;
            result = await authContext.AcquireTokenAsync(todoListResourceId, clientId, redirectUri, new PlatformParameters(PromptBehavior.Always));
            TextBox1.Text = result.AccessToken;
        }

Method 2) From Postman URL: https://login.microsoftonline.com/myad.onmicrosoft.com/oauth2/token

Method: POST

Body: grant_type=authorization_code&client_id=89479d4f-aaaa-4ebf-80f2-13e423431bfb&client_secret=hZ_8Ls1EmFarH_lPn4=aaaa-k8TJ_&redirect_uri=https://NAClient-OBO/&code=AQABAAIAAABeAFzDwllzTYGDLh_qYbH8KZRKktzMuxXp0hM6k1B__lWQrxaikd6wwrYrKZ470UAdr4g1GqAPWja6JgpqsDtLefE23vW80qP7xgVodury28LkGLzL1Mbq0auUeiBaaaa-oCZf11o5EsaSVRVlke6FMkbIn_ppA_GsEBhIAEjxHXXjkrIcp-e4g0G5t9prme4IZ0Sg2_L4MvN6TAyr-nEPGDlnWZLBkRvu8Izsm3RiI_cnneCi1xonZaKBSlsgONIwpgN1bOaz16OVW2uu5lTiz206CSrJtzWeKkitPNUx2Gnn-RnZcCUVDyLxK-eJy8o_ggn_iu7F7kdjKj-b70Gfp5BPYx6fxB4Zyw8tpnWzVkLG7IbLGx9di112u-UGgVSBfWQiO5w3a4Mx2KdDcUihMlVW_mgBUdQi4160AKq1Id9ZcpJEKCT11KWwkO25_q7huCxJ_6-mEU4ADCGjj8hDOtRLGNeZMwhB13rYTN7qGQMmpX491RoldCfpfevva16DhQl5VHbIqspknkK1pFHvh90J47DSg0VihQOIQp1FZ7EgAA&resource=89479d4f-aaaa-4ebf-80f2-13e423431bfb

Please help.

Rajeshwar
  • 565
  • 1
  • 5
  • 13

1 Answers1

2

According to my test, we can use the following steps to implement it

  1. Configure Azure AD for your web API. For more details, please refer to the document

    a. Create Azure AD web api application

    b. Expose API enter image description here

  2. Create client application to access the web api

  3. Configure code

    • web api

      a. Startup.cs

       public void ConfigureAuth(IAppBuilder app)
      {
         app.UseWindowsAzureActiveDirectoryBearerAuthentication(
             new WindowsAzureActiveDirectoryBearerAuthenticationOptions
             {
                 Tenant = "<your tenant id>",
                 TokenValidationParameters = new TokenValidationParameters
                 {
                     ValidAudiences = new[] { "your web api application app id url", "your web api application app id" }
                 },
             }) ;;
      }
      

      b. Controller

      [Authorize]
      [EnableCors(origins: "*", headers: "*", methods: "*")]
      public class ValuesController : ApiController
      {
      // GET api/values
      public IEnumerable<string> Get()
      {
       return new string[] { "value1", "value2" };
      }
      }
      
    • client application. I use console application to call api
    var authority = "https://login.microsoftonline.com/<your tenat id>";
          AuthenticationContext authContext = new AuthenticationContext(authority);
          var uri = "< your redirect url>";
          var clientId = "< your client application app id>";
          var resource = "<your web api application app id url or your web api application app id>";
         var result = authContext.AcquireTokenAsync(resource, clientId, new Uri(uri), new PlatformParameters(PromptBehavior.Always)).Result;
    
          using (HttpClient httpClient = new HttpClient())
          {
    
              httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
    
              var response = httpClient.GetAsync("https://localhost:44345/api/values").Result;
              Console.WriteLine(response.StatusCode);
              Console.WriteLine(response.Content.ReadAsStringAsync().Result);
    
          }
    

    enter image description here

Jim Xu
  • 21,610
  • 2
  • 19
  • 39