Naruto Reddy

Naruto Reddy

  • NA
  • 123
  • 36.6k

Middlaware authentication for Web Api allowanonymous method

Jul 26 2020 8:36 AM
I have a middle ware class as below and expecting token for allow-anonymous method. Can some suggest me what am i missing over here.
 
Middleware class as follows :
  1.  namespace filetrs     
  2.  {  
  3.      public class TestingAuthenticationFilter : IAuthenticationFilter   
  4.       {   
  5.              public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)  
  6.                {   
  7.                  var alias = GetAliasFromJwt(context.Request.Headers.Authorization.ToString());  
  8.                    await Task.Yield();   
  9.                 }  
  10.     public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)   
  11.     {   
  12.         return Task.CompletedTask;   
  13.     }   
  14.     public static string GetAliasFromJwt(string jwt)   
  15.     {       
  16.         string alias, extractedToken;  
  17.         alias = extractedToken = string.Empty; string tokenTypeToRemove = "Bearer ";   
  18.         if (tokenTypeToRemove.Length > 0)   
  19.         {   
  20.             extractedToken = jwt.Substring(tokenTypeToRemove.Length);  
  21.             var handler = new JwtSecurityTokenHandler();  
  22.             var jwtSecurityToken = handler.ReadToken(extractedToken) as JwtSecurityToken;   
  23.             alias = jwtSecurityToken.Claims.First(claim => claim.Type == "abc").Value.Split('@').First();   
  24.         }   
  25.         return alias;  
  26.     }   
  27. }  
Please find APi class as well
  1.  public static class WebApiConfig  
  2.  {  
  3.  public static void Register(HttpConfiguration config)  
  4.  { //var cors = new EnableCorsAttribute("*", "*", "*");  
  5.  //config.EnableCors(cors);   
  6.        config.MapHttpAttributeRoutes();   
  7.         config.Routes.MapHttpRoute(   
  8.         name: "DefaultApi",   
  9.    routeTemplate: "api/{controller}/{id}",   
  10.            defaults: new { id = RouteParameter.Optional } );   
  11.    config.Filters.Add(new TestingAuthenticationFilter());   
  12.   config.Filters.Add(new ExceptionHandlingAttribute());   
  13. }}  
ConfigAuth method from startup.cs as follows
  1. public void ConfigureAuth(IAppBuilder app)  
  2. {  
  3. app.UseWindowsAzureActiveDirectoryBearerAuthentication  
  4. new WindowsAzureActiveDirectoryBearerAuthenticationOptions  
  5. { Tenant = tenant, TokenValidationParameters = new TokenValidationParameters { ValidAudience = clientId }  
  6. });  
I am unable to find the solution. Please someone help me on this?

Answers (2)