Naruto Reddy

Naruto Reddy

  • 1.9k
  • 123
  • 8.9k

Azure AD with Bearer token authentication for Web API not working

Jul 25 2020 6:20 AM
I have developed Azure Ad authentication for a Web APi using the example from Git site [https://github.com/Azure-Samples/ms-identity-aspnet-webapi-onbehalfof/tree/master/TodoListService] I have been facing an issue with Azure Ad authentication. Please find the code below.
 
Action method from Controller1 class.
  1. [RoutePrefix("api/hospitals")]  
  2. public class HospitalsController : ApiController  
  3. {  
  4. [Route("GetAll")]  
  5. [HttpGet]  
  6. [PmAuthorize(Constants.Roles.Admin,Constants.Roles.Doctor)]  
  7. public async Task<IEnumerable> GetAll()  
  8. {  
  9. //return data;....  
  10. }  
  11. }  
My startup.auth.cs file
  1. public partial class Startup  
  2. {  
  3. string clientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"];  
  4. string redirectUri = System.Configuration.ConfigurationManager.AppSettings["RedirectUri"];  
  5. static string tenant = System.Configuration.ConfigurationManager.AppSettings["Tenant"];  
  6. string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture,  
  7. System.Configuration.ConfigurationManager.AppSettings["Authority"],  
  8. tenant);  
  9. public void ConfigureAuth(IAppBuilder app)  
  10. {  
  11. app.UseWindowsAzureActiveDirectoryBearerAuthentication(  
  12. WindowsAzureActiveDirectoryBearerAuthenticationOptions  
  13. {  
  14. Tenant = tenant, TokenValidationParameters = new TokenValidationParameters  
  15. {  
  16. SaveSigninToken = true, ValidAudience = clientid }  
  17. });  
  18. }  
  19. }  
WebApiConfig.cs
  1. public static class WebApiConfig  
  2. {  
  3. public static void Register(HttpConfiguration config)  
  4. {  
  5. config.MapHttpAttributeRoutes();  
  6. config.Routes.MapHttpRoute(name: "DefaultApi",routeTemplate: "api/{controller}/{id}",  
  7. defaults:  
  8. new { id = RouteParameter.Optional } );  
  9. config.Filters.Add(new ExceptionHandlingAttribute());'  
  10. } }  
When ever i am calling a action method/api method call from hospital controller by passing token getting the error as "Authorization has been denied for this request."
 
Can some one help me here ?.
 
Please add any comments if any addition info required ?
 
Thanks in advance.

Answers (1)