title: How to intercept request Token Jwt in Dotnet Core to Send to other API?
body: <p>I'm trying to do a filter in Dotnet Core to validate a token JWT in other Api of Login(Java) that
  i did. The basic is, thus that received the token, the filter gets the token Jwt and send it to validate 
  in other Api. I'm trying to do but i don't findind how to do this. I did make in alternate method
  but i don't know how to do the correct. </p>
  
  <p>Class SendEmailController.cs:</p>
  
  <pre><code>using System.Threading.Tasks;
  using Microsoft.AspNetCore.Mvc;
  [ApiController]
  [Route("[controller]")]
  public class SendEmailController: ControllerBase
  {
      private readonly IEmailSender emailSender;
  
      public SendEmailController(IEmailSender emailSender){
          this.emailSender = emailSender;
      }
  
      [HttpPost]
      public async Task&lt;ActionResult&gt;  SendEmail(GetEmailDto emailDto) {
          string header = Request.Headers["Authorization"];
          string token = null;
  
          if(header != null &amp;&amp; header.Contains("Bearer")){
              string [] aux = header.Split(" ");
              token = aux.Length &gt; 1 ? aux[1].Trim() : token;
          }
  
          if(token != null &amp;&amp; await LoginService.ValidateToken(token) != null){
            return  Ok(this.emailSender.SendEmailAsync(emailDto));
          } else {
            return BadRequest("Email not sended &gt;&gt; ");
          }
      }
  }
  </code></pre>
  
  <p>LoginService.cs:</p>
  
  <pre><code>using System;
  using System.Net.Http;
  using System.Net.Http.Headers;
  using System.Text;
  using System.Threading.Tasks;
  public class LoginService{
   public static  async Task&lt;string&gt; ValidateToken(string token)
  {
      try{
      string tokenUrl = Environment.GetEnvironmentVariable("TOKEN_VALIDATE_URL");
      HttpClient client = new HttpClient();
      client.DefaultRequestHeaders.Accept.Clear();
      client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
      client.DefaultRequestHeaders.Authorization =
      new AuthenticationHeaderValue("Bearer", token);
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
      return  await client.GetStringAsync(tokenUrl);
      }
      catch(Exception e)
      {
       Console.WriteLine("ERROR &gt;&gt; "+e.Message);
       return null;
      }   
      }
  }
  </code></pre>
  
  <p>Startup.cs:</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Threading.Tasks;
  using Microsoft.AspNetCore.Builder;
  using Microsoft.AspNetCore.Hosting;
  using Microsoft.AspNetCore.HttpsPolicy;
  using Microsoft.AspNetCore.Mvc;
  using Microsoft.Extensions.Configuration;
  using Microsoft.Extensions.DependencyInjection;
  using Microsoft.Extensions.Hosting;
  using Microsoft.Extensions.Logging;
  using Microsoft.EntityFrameworkCore;
  using AutoMapper;
  using Microsoft.AspNetCore.Authentication.JwtBearer;
  using Microsoft.IdentityModel.Tokens;
  using System.Text;
  using System.IdentityModel.Tokens.Jwt;
  using System.Security.Claims;
  
  namespace apiEmail
  {
      public class Startup
      {
          public Startup(IConfiguration configuration)
          {
              Configuration = configuration;
          }
  
          public IConfiguration Configuration { get; }
  
          // This method gets called by the runtime. Use this method to add services to the container.
          public void ConfigureServices(IServiceCollection services)
          {
              services.AddDbContext&lt;DataContext&gt;();
              services.AddCors();
              services.AddControllers();
              services.AddAutoMapper(typeof(Startup));
              services.AddScoped&lt;IEmailService, EmailService&gt;();
              services.AddScoped&lt;IAuthRepository, AuthRepository&gt;();
              services.AddTransient&lt;IEmailSender, AuthMessageSender&gt;();
              services.AddMvc();
              var key = Encoding.ASCII.GetBytes(Environment.GetEnvironmentVariable("SECRET_KEY")+" DOTNET DA DEPRESSAO");
              services.AddAuthentication(x =&gt; {
                 x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                 x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
              })
              .AddJwtBearer(options =&gt; {
                  options.RequireHttpsMetadata = false;
                  options.SaveToken = true;
                  options.TokenValidationParameters = new TokenValidationParameters
                  {
                      ValidateIssuerSigningKey = false,
                       IssuerSigningKey = new SymmetricSecurityKey(key),
                       ValidateIssuer = false,
                       ValidateAudience = false
                  };
              });
          }
  
           private static void UpdateDatabase(IApplicationBuilder app)
              {
                  using (var serviceScope = app.ApplicationServices
                       .GetRequiredService&lt;IServiceScopeFactory&gt;()
                       .CreateScope())
              {
                  using (var context = serviceScope.ServiceProvider.GetService&lt;DataContext&gt;())
                {
                  context.Database.Migrate();
                }
          }
      }
  
          // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
          public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DataContext context)
          {
              UpdateDatabase(app);
              if (env.IsDevelopment())
              {
                  app.UseDeveloperExceptionPage();
              }
              //app.UseHttpsRedirection();
              app.UseRouting();
              app.UseCors(
                  options =&gt; options
                  .AllowAnyOrigin()
                  .AllowAnyMethod()
                  .AllowAnyHeader()
              );
  
             // app.UseAuthentication();
  
             var options = new JwtBearerOptions
             {
                  Audience = "...",
                  Authority = "...",
                  Events = new JwtBearerEvents
              {
                  OnTokenValidated = context =&gt;
                  {
              // Add the access_token as a claim, as we may actually need it
              var accessToken = context.SecurityToken as JwtSecurityToken;
              if (accessToken != null)
              {
                 Console.Write("Token &gt;&gt;", accessToken);
              }
              return Task.CompletedTask;
              }
          }
          };    
             app.UseAuthentication();
              app.UseAuthorization();
              app.UseEndpoints(endpoints =&gt;
              {
                  endpoints.MapControllers();
              });
               context.Database.EnsureCreated();
               context.Database.Migrate();
          }
      }
  }
  </code></pre>
  
  <p>How to do this validation without stay in the Controller, only in filter defined in 
  startup.cs with filter like this class in Java?</p>
  
  <p>Example:</p>
  
  <pre><code>@Slf4j
  @Component
  @AllArgsConstructor(onConstructor = @__(@Autowired))
  public class JwtRequestFilter extends OncePerRequestFilter {
      private JwtUtil jwtUtil;
      private LoginService login;
      @Override
      protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
              throws ServletException, IOException {
          final String authorizationHeader = request.getHeader("Authorization");
          String username = null;
          String jwt = null;
          Users usr = null;
  
          if (authorizationHeader != null &amp;&amp; authorizationHeader.startsWith("Bearer ")) {
              jwt = authorizationHeader.substring(7);
              username = jwtUtil.extractUsername(jwt);
          }
  
          if (username != null &amp;&amp; SecurityContextHolder.getContext().getAuthentication() == null) {
  
              if (jwtUtil.isTokenExpired(jwt)) {
                  throw new IOException("Token expirado ");
              }
              try {
                  usr = login.verifyToken(jwt);
                  Authentication auth = new UsernamePasswordAuthenticationToken(usr.getEmail(), usr.getSenha());
                  Set authorities = new HashSet&lt;&gt;();
                  authorities.add(new SimpleGrantedAuthority(usr.getTipo().toString()));
                  UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken
                          = new UsernamePasswordAuthenticationToken(
                          auth.getName(), auth.getCredentials(), authorities);
                  usernamePasswordAuthenticationToken
                          .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                  SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
              } catch (Exception e) {
                  log.error("Error &gt;&gt; ", e);
                  throw new IOException("Erro ao validar o Token");
              }
  
          }
          chain.doFilter(request, response);
      }
  }
  </code></pre>
  
  <p>class LoginService.java:</p>
  
  <pre><code>public class LoginService{
  public  Users  verifyToken(String token) {
          RestTemplate restTemplate = new RestTemplate();
          HttpHeaders headers = new HttpHeaders();
          headers.setContentType(MediaType.APPLICATION_JSON);
          headers.set("Authorization", "Bearer "+token);
          HttpEntity&lt;String&gt; entity = new HttpEntity&lt;String&gt;(headers);
          return  restTemplate.exchange(Assets.API_TOKEN_DATA, HttpMethod.PUT, entity, Users.class).getBody(); 
      }
  }
  </code></pre>
  
  <p>Thanks</p>